Compare commits

..
Author SHA1 Message Date
l0ng-ai 19207f1102 fix(agents): keep selection highlights within reply text 2026-11-24 14:55:39 +08:00
1349 changed files with 7352 additions and 69921 deletions

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
---
name: eval
description: Run the code-intelligence evals (`pnpm eval`), pick the worst failing scenario, diagnose it from the attached timeline, fix it, prove the fix with before / after numbers measured on this machine without regressing other scenarios, and open one PR. Use for "跑 eval", "优化 Java 代码智能", "eval 失败了", an issue labelled `eval`, or any change to Java navigation / usages / gutter markers that needs numbers.
---
# Eval loop: measure → fix → prove
`pnpm eval` drives the production workbench in Chromium against a release `openidea-server`
with real language servers (Java / jdtls for now) and judges every scenario on what the user
sees: time to feedback, to the first result, to the final one, and the results themselves vs
`evals/<language>/golden/`. One machine, before and after: numbers from different machines or
from the nightly host don't judge a fix.
## 0. Preconditions
- `jdtls` on PATH and `JAVA_HOME` pointing at a JDK of the pinned `JAVA` version (projects
compile against it, and the JDK scenarios' results are in its sources; jdtls itself runs on
a newer installed JDK when it needs one). Pinned versions: `.github/tool-versions.env`. A
mismatch prints a warning and the report records both: say so in the PR when it applies.
- First run builds `cargo build --release -p ide-host --bin openidea-server` and the perf
bundle; later iterations of a frontend-only change can use `--no-build` after a
`pnpm exec vite build --mode perf --outDir target/eval/dist`, a backend-only one after the
cargo build alone.
- Run evals one at a time on this machine, with nothing heavy (builds, other evals) beside them.
## 1. Baseline on the base commit
```sh
git switch --detach origin/main # or the fix branch's merge base
pnpm eval --save-baseline # target/eval/baseline.json, this machine only
```
Read `target/eval/report.json`. Each verdict has `status`, `failures` (`kind`: `error`,
`timeout`, `degraded`, `correctness`, `budget`, `golden`), `regressions`, `repro` (the command
that reruns it) and, for failures, `diagnostics`: every command sent to the server in the
slowest run's window (`cmd`, `start`, `ms`, `ok`, `bytes`, `items`), background tasks, server
status changes and the server's log tail.
## 2. Pick one problem
Worst first: wrong or missing results and silent degradation, then timeouts, then the
feedback budget (100 ms), then the slowest `completeMs`. One problem per PR. Say which
scenario and metric, with its value vs budget.
## 3. Diagnose from the timeline
- Commands in the window ordered by `start`: what ran, what waited on what, what's serial
that could overlap, which request returned many `items`/`bytes`, which failed.
- `feedbackMs` far above 16 ms with a fast `firstResultMs`: the UI shows nothing while it
waits (a hint or popup that only appears after a delay).
- A task still running across the window: background work competing with the request.
- For the frontend side rerun with `--trace` and open `target/eval/traces/<id>@<cond>.json`
in Chrome's Performance panel.
- Name the cause at class level (as in `issue-fix`): it usually affects sibling scenarios.
## 4. Fix, then rerun that scenario until it passes
```sh
pnpm eval --only <scenario> --condition <warm|cold> # the verdict's `repro`
```
Correctness is enforced, so a faster answer that drops, truncates or serves stale results
fails. Don't trade a budget miss for a degraded answer.
## 5. Full suite, then PR
```sh
pnpm eval # vs the baseline from step 1: no new failures or regressions
```
PR per `issue-fix` §6, plus in **How it was verified** the before / after table from
`target/eval/report.md` (both on this machine, commits named) and the tool versions line.
## Guard rails
- Goldens (`evals/*/golden/`) and budgets (`evals/budgets.json`) are human-owned. Don't edit
them, and don't run `--update-golden`, to make a scenario pass. When a golden looks wrong
(a tool bump, a deliberate behaviour change), stop and say so: a PR that touches them gets
`needs-decision`.
- Don't weaken a scenario's checks or timeouts in `evals/<language>/scenarios.ts` to pass.
Adding a scenario (for a case the sweep or a user found) is fine; record its golden with
`--update-golden --only <id>` and ask a person to review the file.
- A flaky timing (passes on rerun) is not a regression: rerun once before acting on one.
+91
View File
@@ -0,0 +1,91 @@
---
name: issue-fix
description: Triage and fix a GitHub issue (or a user-reported bug) end to end — reproduce, find the root cause, generalise it to every sibling case, fix the class rather than the instance, verify, and open one PR. Use when given an issue URL/number or asked to fix a reported bug and open a PR ("看看这个 issue", "修一下这个 bug", "提 pr").
---
# Fix an issue: from one case to the whole class
The reported case is one sample of a defect class. A fix that only makes the
screenshot go away is not done: the next question is always "does this break for other
languages / platforms / entry points too?". Answer that before anyone asks.
## 1. Read and reproduce
- `gh issue view <n> --comments` (repo `l0ng-ai/openidea`). Read attached logs/screenshots
closely: OS, language, toolchain versions, exact error text.
- Locate the code path and confirm the claim in code, with `file:line` evidence.
Say plainly whether it is a real bug, a missing feature, or user environment.
- Reproduce locally when possible (`fixtures/` projects, `/verify` for runtime). If the
reporter's platform (often Windows/Linux) can't be reproduced here, say so up front.
- Do not ask for a generic environment/log checklist before trying the flow and inspecting the code.
Record the attempt and result; ask only for a fact that actually blocks the next diagnostic step.
Missing fields, limited time, or unavailable automation are not by themselves reasons to ask the reporter.
- Treat a maintainer-confirmed bug as an investigation task even if local reproduction fails. Distinguish
“not reproduced here” from “not a bug”, and do not require the reporter to prove its existence again.
## 2. Name the root cause as a class
Write one sentence of the form "<mechanism> is missing/wrong, so any <X> hits it",
not "<this button> is broken". Typical classes in this codebase:
- Per-language config handled for one language only (`languages/*.toml`, `ide-sdk`).
- Platform gaps: paths, executables, shells, `.cmd`/`.exe`, separators — macOS-only code.
- Toolchain/version discovery: one probe location, no version check, no rescan.
- Two features each implementing half a flow and never joined (feature isolation →
should go through an action/service).
- State not reset on project switch / window reuse; events not scoped per window.
- Failure surfaced as raw stderr/stack trace or retried until "crashed" instead of a
clear status with an action.
- UI: same primitive styled differently in N places.
## 3. Sweep for siblings
Search systematically, not by memory:
- Same pattern elsewhere: `git grep` the function, the config key, the error string,
the hard-coded path/flag. Check every `languages/*.toml` entry and every platform branch.
- Same flow for other languages/runtimes (Java ↔ Kotlin/Gradle, Python ↔ venv/uv,
Node ↔ Deno/Bun, Go, Rust …): would they fail the same way?
- Other callers/entry points of the same flow (menu, context menu, gutter, shortcut, CLI arg).
- Neighbouring failure modes of the same mechanism (not installed / wrong version /
installed but crashes / slow start / installed mid-session).
For broad sweeps spawn one Explore agent with the class description, not the instance.
## 4. Decide the fix at the right altitude
- Fix the mechanism once (shared helper, action, config hook) so siblings are fixed
by construction; don't patch each call site.
- Respect `AGENTS.md` rules (crate boundaries, no cross-feature imports, `IdeResult`,
UTF-16). If the right fix breaks a rule, pick the rule-respecting design and say why.
- Compare with how established IDEs solve it when relevant; prefer the established answer.
- Present: root cause, sibling table, proposed fix, what's deferred. When the user leaves
the choice to you, go ahead without asking again.
## 5. Implement and test the class
- Tests cover the class: table-driven over languages/platforms/states, not just the
reported input. Include the reporter's case verbatim.
- Run the scoped checks (`pnpm vitest run <path>`, `cargo nextest run -p <crate>`), then
`/verify` in the app for UI or runtime behaviour.
## 6. PR
- One branch `fix/<slug>`, one PR unless the user asks otherwise; `Fixes #<n>` in the body.
- Don't stage untracked IDE-state dirs (`.ideal/`, `.openidea/`) or screenshots.
- PR body follows `.github/pull_request_template.md`: `Closes #<n>`, then
**What and why** (user-visible change + root cause at class level, 2–4 sentences),
**How it was verified** (commands run and results, siblings fixed/deferred, what could break and how
it was checked, what was not verified, e.g. "Windows not tested"; for UI changes the before/after
screenshot paths from `/verify`), **Review focus** (optional). Short and plain.
## Report format
Reply in the user's language:
```
Root cause: <one sentence, class level>
Sibling sweep:
| Location / case | Affected? | Action |
Fixed / not covered (why) / not verified (platform)
PR: <url>
```
+57
View File
@@ -0,0 +1,57 @@
---
name: verify
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
---
# Verify OpenIDEA in the running app
## Launch
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
session already running for this worktree, reuse that one.
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
`location.href` before acting if anything looks off.
- Make sure the binary contains the change: a session already running for this worktree may be an
older build. Restart it after Rust changes; frontend changes reload through Vite.
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
reload shows an empty `#root`. Stop that app and start the session again.
- Stop everything you started when done and nothing else; never use process-name kills.
## Driving
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
screenshots come back black.
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
## Evidence
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
flows: a numbered series (`after-1.png`, `after-2.png`, ...).
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
acceptance entry. Never commit screenshots to the feature branch.
## Fixture
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
## Flows worth driving
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/eval
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/issue-fix
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/verify
+29 -65
View File
@@ -28,9 +28,7 @@ jobs:
# shared runners to others. Pushes, the merge queue and manual runs always run everything.
changes:
name: Changes
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: read
@@ -110,10 +108,10 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [macos-latest, ubuntu-latest, windows-latest]
os: [macos-latest, ubuntu-22.04, windows-latest]
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
@@ -146,8 +144,8 @@ jobs:
- name: Linux deps
if: runner.os == 'Linux'
run: |
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
# tauri-build checks that frontendDist exists.
- run: pnpm install --frozen-lockfile && mkdir -p dist
shell: bash
@@ -158,8 +156,7 @@ jobs:
- run: git config --global core.autocrlf false
- run: cargo nextest run --workspace --no-fail-fast
- name: Remote backend with Docker Compose
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
if: runner.os == 'Linux' && runner.environment != 'self-hosted'
if: runner.os == 'Linux'
run: |
docker pull busybox:latest
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
@@ -178,7 +175,7 @@ jobs:
name: Rust checks
needs: [changes, rust]
if: always()
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- env:
@@ -195,27 +192,16 @@ jobs:
needs: changes
if: needs.changes.outputs.server == 'true'
timeout-minutes: 40
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
with: { targets: x86_64-unknown-linux-musl }
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with: { key: server-musl }
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
shell: bash
run: |
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
if [ "${size:-0}" -gt 40000 ]; then
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- run: dpkg -s musl-tools >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y musl-tools; }
- run: sudo apt-get update && sudo apt-get install -y musl-tools
- run: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl
- run: '"${CARGO_TARGET_DIR:-target}/x86_64-unknown-linux-musl/debug/openidea-server" --version'
- run: target/x86_64-unknown-linux-musl/debug/openidea-server --version
# The plugin SDK, the official plugins and the test fixtures build in their
# own workspaces (the root excludes them), so the jobs above don't see them.
@@ -224,31 +210,18 @@ jobs:
needs: changes
if: needs.changes.outputs.plugins == 'true'
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
runs-on: ubuntu-22.04
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/target-plugins
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
- if: runner.environment != 'self-hosted'
shell: bash
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
key: plugins
cache-directories: target-plugins
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
shell: bash
run: |
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
if [ "${size:-0}" -gt 40000 ]; then
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
echo "CARGO_TARGET_DIR=$CARGO_TARGET_DIR/plugins" >> "$GITHUB_ENV"
- name: Format, lint (host and wasm) and test each crate
shell: bash
run: |
@@ -265,7 +238,7 @@ jobs:
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, package-manager-cache: false }
with: { node-version: 22 }
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
- name: Web pages typecheck and test
shell: bash
@@ -289,7 +262,7 @@ jobs:
needs: changes
if: needs.changes.outputs.deny == 'true'
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
@@ -301,19 +274,13 @@ jobs:
needs: changes
if: needs.changes.outputs.frontend == 'true'
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v5
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
- uses: dtolnay/rust-toolchain@stable
if: runner.environment == 'self-hosted'
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
@@ -328,41 +295,38 @@ jobs:
needs: changes
if: needs.changes.outputs.catalog == 'true'
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
e2e:
name: E2E (${{ matrix.shard }}/4)
name: E2E (${{ matrix.shard }}/2)
needs: changes
if: needs.changes.outputs.e2e == 'true'
timeout-minutes: 45
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
timeout-minutes: 30
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
shard: [1, 2]
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
container: mcr.microsoft.com/playwright:v1.64.1-noble
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm e2e --shard=${{ matrix.shard }}/4
- run: pnpm e2e --shard=${{ matrix.shard }}/2
env:
HOME: /root
- uses: actions/upload-artifact@v6
if: failure()
with:
+18 -57
View File
@@ -23,7 +23,6 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "src/features/build/**"
- "src/features/build-tools/**"
- "src/platform/**"
- "src/workbench/**"
@@ -58,9 +57,6 @@ on:
paths: *paths
workflow_dispatch:
permissions:
contents: read
concurrency:
group: language-smoke-${{ github.ref }}
# A new push supersedes a PR's run; on main every merge runs to the end (and saves the cache).
@@ -69,6 +65,8 @@ concurrency:
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
# Line tables keep test backtraces readable and the binaries the build job hands on small.
CARGO_PROFILE_DEV_DEBUG: line-tables-only
jobs:
# The languages a pull request can affect: a change to one language's fixture, definition or
@@ -76,9 +74,7 @@ jobs:
# run none; anything else runs them all. Pushes and manual runs always run them all.
changes:
name: Changes
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: read
@@ -106,7 +102,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
@@ -143,32 +139,17 @@ jobs:
name: Build
needs: changes
if: needs.changes.outputs.languages != '[]'
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
# The tests find the fixtures through the checkout path compiled into them (CARGO_MANIFEST_DIR),
# which is the same on every GitHub-hosted runner.
runs-on: ubuntu-22.04
timeout-minutes: 30
env:
# Line tables keep test backtraces readable and the binaries handed on small without
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
CARGO_PROFILE_DEV_DEBUG: line-tables-only
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
shell: bash
run: |
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
if [ "${size:-0}" -gt 40000 ]; then
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- run: |
set -euo pipefail
mkdir -p smoke-bin
@@ -176,7 +157,7 @@ jobs:
| jq -r 'select(.reason == "compiler-artifact" and .executable != null and .target.kind == ["test"]) | "\(.target.name) \(.executable)"' \
| while read -r name exe; do cp "$exe" "smoke-bin/$name"; done
cargo build --locked -p ide-host --bin openidea-server
cp "${CARGO_TARGET_DIR:-target}/debug/openidea-server" smoke-bin/
cp target/debug/openidea-server smoke-bin/
ls -l smoke-bin
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
# A tar keeps the executable bits, which artifacts drop.
@@ -191,16 +172,11 @@ jobs:
fail-fast: false
matrix:
language: ${{ fromJSON(needs.changes.outputs.languages) }}
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
timeout-minutes: 40
# Self-hosted runner slots have distinct checkout paths (/persist/slot-<N>/work/...); override
# the compiled-in CARGO_MANIFEST_DIR so binaries from the Build job find this slot's fixtures.
env:
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v4
# Tool versions, shared with the evals (pnpm eval).
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- uses: dtolnay/rust-toolchain@stable
@@ -211,32 +187,18 @@ jobs:
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@v4
with: { version: 11 }
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: actions/setup-node@v4
with: { node-version: 22, cache: pnpm }
- if: matrix.language == 'typescript'
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
# The smoke builds the c-app fixture and debugs it with GDB's own DAP interpreter.
- if: matrix.language == 'c' || matrix.language == 'cpp'
shell: bash
run: |
pkgs=()
command -v clangd >/dev/null || pkgs+=(clangd)
command -v gdb >/dev/null || pkgs+=(gdb)
if [ "${#pkgs[@]}" -gt 0 ]; then
sudo apt-get update
sudo apt-get install -y "${pkgs[@]}"
fi
major=$(gdb --version | head -n1 | grep -Eo '[0-9]+\.[0-9]+' | head -n1 | cut -d. -f1)
if [ "${major:-0}" -lt 14 ]; then
echo "::error::GDB 14+ is required for its DAP interpreter; recreate the runner from scripts/selfhost-runner (Ubuntu 24.04)."
exit 1
fi
sudo apt-get update
sudo apt-get install -y gdb
- if: matrix.language == 'python'
uses: actions/setup-python@v5
@@ -255,7 +217,6 @@ jobs:
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: matrix.language == 'java'
run: |
command -v mvn >/dev/null || { sudo apt-get update && sudo apt-get install -y maven; }
mkdir -p "$RUNNER_TEMP/jdtls"
curl -fsSL "https://download.eclipse.org/jdtls/milestones/${JDTLS%-*}/jdt-language-server-$JDTLS.tar.gz" \
| tar xz -C "$RUNNER_TEMP/jdtls"
+7 -5
View File
@@ -33,12 +33,14 @@ target/
test-results/
playwright-report/
# Local AI agent files
AGENTS.md
CLAUDE.md
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
CLAUDE.local.md
.agents/
.claude/
.claude/*
!.claude/skills/
.claude/skills/*
!.claude/skills/verify
!.claude/skills/issue-fix
!.claude/skills/eval
# Local reference screenshots
pycharm-screenshots/
-15
View File
@@ -1,15 +0,0 @@
{
"detector": {
"ignoreRules": [],
"ignoreFiles": [],
"ignoreValues": [
{
"rule": "gradient-text",
"value": "*",
"files": ["src/features/agents/Session.module.css"],
"createdAt": "2026-11-24T14:58:12.514Z",
"reason": "agent: .shimmer is an animated in-progress sweep on running-step labels (commit 18b286e7e, comment documents intent), not decorative gradient text"
}
]
}
}
-557
View File
@@ -1,557 +0,0 @@
{
"schemaVersion": 2,
"generatedAt": "2026-11-24T15:06:05+00:00",
"title": "Design System: OpenIDEA",
"extensions": {
"colorMeta": {
"workbench-blue": {
"role": "primary",
"displayName": "Workbench Blue",
"canonical": "#3871e1",
"tonalRamp": [
"oklch(15% 0.073 262)",
"oklch(25% 0.121 262)",
"oklch(35% 0.17 262)",
"oklch(48% 0.17 262)",
"oklch(60% 0.17 262)",
"oklch(72% 0.136 262)",
"oklch(84% 0.078 262)",
"oklch(95% 0.024 262)"
]
},
"link-blue": {
"role": "primary",
"displayName": "Link Blue",
"canonical": "#2f5eb9",
"tonalRamp": [
"oklch(15% 0.064 262)",
"oklch(25% 0.107 262)",
"oklch(35% 0.15 262)",
"oklch(48% 0.15 262)",
"oklch(60% 0.15 262)",
"oklch(72% 0.12 262)",
"oklch(84% 0.069 262)",
"oklch(95% 0.021 262)"
]
},
"selection-wash": {
"role": "primary",
"displayName": "Selection Wash",
"canonical": "#d0dffe",
"tonalRamp": [
"oklch(15% 0.034 262)",
"oklch(25% 0.057 262)",
"oklch(35% 0.08 262)",
"oklch(48% 0.08 262)",
"oklch(60% 0.08 262)",
"oklch(72% 0.064 262)",
"oklch(84% 0.037 262)",
"oklch(95% 0.011 262)"
]
},
"tab-wash": {
"role": "primary",
"displayName": "Tab Wash",
"canonical": "#e3ebfe",
"tonalRamp": [
"oklch(15% 0.026 262)",
"oklch(25% 0.043 262)",
"oklch(35% 0.06 262)",
"oklch(48% 0.06 262)",
"oklch(60% 0.06 262)",
"oklch(72% 0.048 262)",
"oklch(84% 0.027 262)",
"oklch(95% 0.009 262)"
]
},
"danger": {
"role": "status",
"displayName": "Danger",
"canonical": "#c54e58",
"tonalRamp": [
"oklch(15% 0.064 18)",
"oklch(25% 0.107 18)",
"oklch(35% 0.15 18)",
"oklch(48% 0.15 18)",
"oklch(60% 0.15 18)",
"oklch(72% 0.12 18)",
"oklch(84% 0.069 18)",
"oklch(95% 0.021 18)"
]
},
"warning": {
"role": "status",
"displayName": "Warning",
"canonical": "#a56906",
"tonalRamp": [
"oklch(15% 0.056 70)",
"oklch(25% 0.093 70)",
"oklch(35% 0.13 70)",
"oklch(48% 0.13 70)",
"oklch(60% 0.13 70)",
"oklch(72% 0.104 70)",
"oklch(84% 0.059 70)",
"oklch(95% 0.019 70)"
]
},
"success": {
"role": "status",
"displayName": "Success",
"canonical": "#338555",
"tonalRamp": [
"oklch(15% 0.047 152)",
"oklch(25% 0.079 152)",
"oklch(35% 0.11 152)",
"oklch(48% 0.11 152)",
"oklch(60% 0.11 152)",
"oklch(72% 0.088 152)",
"oklch(84% 0.05 152)",
"oklch(95% 0.016 152)"
]
},
"frame-grey": {
"role": "neutral",
"displayName": "Frame Grey",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"island-white": {
"role": "neutral",
"displayName": "Island White",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"raised-paper": {
"role": "neutral",
"displayName": "Raised Paper",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink": {
"role": "neutral",
"displayName": "Ink",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-secondary": {
"role": "neutral",
"displayName": "Ink Secondary",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-muted": {
"role": "neutral",
"displayName": "Ink Muted",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-faint": {
"role": "neutral",
"displayName": "Ink Faint",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"hairline": {
"role": "neutral",
"displayName": "Hairline",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"control-edge": {
"role": "neutral",
"displayName": "Control Edge",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"frame-grey-dark": {
"role": "neutral",
"displayName": "Frame Grey (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"island-dark": {
"role": "neutral",
"displayName": "Island (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-dark": {
"role": "neutral",
"displayName": "Ink (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-strong-dark": {
"role": "neutral",
"displayName": "Ink Strong (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-muted-dark": {
"role": "neutral",
"displayName": "Ink Muted (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"control-edge-dark": {
"role": "neutral",
"displayName": "Control Edge (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"selection-wash-dark": {
"role": "primary",
"displayName": "Selection Wash (Dark)",
"canonical": "#2a4371",
"tonalRamp": [
"oklch(15% 0.034 262)",
"oklch(25% 0.057 262)",
"oklch(35% 0.08 262)",
"oklch(48% 0.08 262)",
"oklch(60% 0.08 262)",
"oklch(72% 0.064 262)",
"oklch(84% 0.037 262)",
"oklch(95% 0.011 262)"
]
}
},
"typographyMeta": {
"title": {
"displayName": "Title",
"purpose": "Tool window titles, section headers, dialog titles; weight 600 is the main emphasis."
},
"body": {
"displayName": "Body",
"purpose": "Default UI text, menus, rows, buttons."
},
"label": {
"displayName": "Label",
"purpose": "Secondary metadata, chips, status bar, table cells; the most-used size."
},
"label-tiny": {
"displayName": "Label Tiny",
"purpose": "Stripe labels, counters, badges."
},
"input-large": {
"displayName": "Input Large",
"purpose": "Search Everywhere and other large query fields."
},
"code": {
"displayName": "Code",
"purpose": "Editor, console, terminal and every monospace preview; size and weights are user settings."
}
},
"shadows": [
{
"name": "shadow-popup",
"value": "0 6px 20px rgba(0, 0, 0, 0.12)",
"purpose": "Popups, menus, completion, floating toolbar (Light; Dark uses 0.45 alpha)."
},
{
"name": "shadow-dialog",
"value": "0 0 0 0.5px rgba(0, 0, 0, 0.1), 0 10px 24px rgba(0, 0, 0, 0.1), 0 24px 72px rgba(0, 0, 0, 0.2)",
"purpose": "Window-style shadow for dialogs (Light)."
},
{
"name": "shadow-tooltip",
"value": "0 4px 12px rgba(0, 0, 0, 0.12)",
"purpose": "Hover tooltips (Light)."
},
{
"name": "shadow-balloon",
"value": "0 8px 24px rgba(0, 0, 0, 0.14)",
"purpose": "Notification balloons (Light)."
}
],
"motion": [
{
"name": "ease",
"value": "cubic-bezier(0.2, 0, 0, 1)",
"purpose": "Default easing for every state transition."
},
{
"name": "dur-fast",
"value": "80ms",
"purpose": "Hover, press and focus changes on controls."
},
{
"name": "dur",
"value": "140ms",
"purpose": "Standard transitions such as popup fades."
},
{
"name": "dur-slow",
"value": "220ms",
"purpose": "Upper bound for any state transition."
}
],
"density": [
{
"name": "default",
"value": "rows 24px, fields/buttons 28px, titlebar 40px, tab bar 38px, status bar 30px, island gap 6px, island radius 10px"
},
{
"name": "compact",
"value": "rows 22px, fields/buttons 24px, titlebar/headers 32px, tab bar 32px, status bar 24px, island gap 4px, island radius 8px, chrome text -1px"
}
]
},
"components": [
{
"name": "Primary Button",
"kind": "button",
"refersTo": "button-primary",
"description": "The one default action in a dialog or form.",
"html": "<button class=\"ds-btn ds-btn-primary\">OK</button>",
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-primary { background:var(--bg-button-primary,#3871e1); color:var(--fg-button-primary,#fff); } .ds-btn-primary:hover { background:var(--bg-button-primary-hover,#3366cc); }"
},
{
"name": "Secondary Button",
"kind": "button",
"refersTo": "button-secondary",
"description": "Every other dialog action: Cancel, Apply, Browse.",
"html": "<button class=\"ds-btn ds-btn-secondary\">Cancel</button>",
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-secondary { background:var(--bg-button,#fff); color:var(--fg-strong,#000); box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); } .ds-btn-secondary:hover { background:color-mix(in srgb, var(--bg-button,#fff) 94%, var(--fg-strong,#000)); }"
},
{
"name": "Ghost Button",
"kind": "button",
"refersTo": "button-ghost",
"description": "Low-emphasis text actions in headers and inline rows.",
"html": "<button class=\"ds-btn-ghost\">Show all</button>",
"css": ".ds-btn-ghost { display:inline-flex; align-items:center; height:var(--h-button,28px); padding:0 8px; border:0; background:transparent; border-radius:var(--radius-control,4px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-ui,13px); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-btn-ghost:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-btn-ghost:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-btn-ghost:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; }"
},
{
"name": "Toolbar Icon Button",
"kind": "button",
"refersTo": "icon-button",
"description": "Toolbar and tool window header actions; frameless at rest, toggles show Selection Wash.",
"html": "<div class=\"ds-iconbar\"><button class=\"ds-icon-btn\" aria-label=\"Refresh\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button><button class=\"ds-icon-btn\" aria-label=\"Show options\" aria-pressed=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\"/></svg></button></div>",
"css": ".ds-iconbar { display:flex; gap:2px; } .ds-icon-btn { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; padding:0; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-muted,#6c707e); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-icon-btn:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-icon-btn:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-icon-btn[aria-pressed=\"true\"] { background:var(--bg-toolbar-selected,#d0dffe); color:var(--fg-strong,#000); } .ds-icon-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
},
{
"name": "Text Field",
"kind": "input",
"refersTo": "input",
"description": "Framed text field; the frame doubles in Workbench Blue on focus.",
"html": "<input class=\"ds-input\" placeholder=\"Project name\" />",
"css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }"
},
{
"name": "Chip",
"kind": "chip",
"refersTo": "chip",
"description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.",
"html": "<button class=\"ds-chip\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\"><circle cx=\"5\" cy=\"4\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"11\" cy=\"6\" r=\"1.5\" stroke=\"currentColor\"/><path d=\"M5 5.5v5M11 7.5c0 2-2 2.5-6 3\" stroke=\"currentColor\"/></svg><span>main</span></button>",
"css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
},
{
"name": "Tree Rows",
"kind": "custom",
"refersTo": "list-row-selected",
"description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.",
"html": "<div class=\"ds-tree\" tabindex=\"0\"><div class=\"ds-row\">src</div><div class=\"ds-row ds-row-sel\">main.tsx</div><div class=\"ds-row\">workbench</div></div>",
"css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }"
},
{
"name": "Island on Frame",
"kind": "card",
"description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.",
"html": "<div class=\"ds-frame\"><div class=\"ds-island ds-side\"><div class=\"ds-head\">Project</div></div><div class=\"ds-island ds-main\"><code>fn main() {}</code></div></div>",
"css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }"
},
{
"name": "Tooltip",
"kind": "custom",
"refersTo": "tooltip",
"description": "Floating hover help: one of the few surfaces allowed a shadow.",
"html": "<div class=\"ds-tooltip\">Run 'main' <span class=\"ds-kbd\">⌃R</span></div>",
"css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }"
}
],
"narrative": {
"northStar": "The Quiet Workbench",
"overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.",
"keyCharacteristics": [
"JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.",
"Grey frame, rounded content islands, tonal layering only.",
"A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.",
"High density on a 4px grid. Compact mode is a first-class variant.",
"Controls are quiet at rest: toolbar buttons and chips have no frame until hover.",
"Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.",
"Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins."
],
"rules": [
{
"name": "The IDEA Reference Rule",
"body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.",
"section": "overview"
},
{
"name": "The One Accent Rule",
"body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.",
"section": "colors"
},
{
"name": "The Token Only Rule",
"body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.",
"section": "colors"
},
{
"name": "The Flat Scale Rule",
"body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.",
"section": "typography"
},
{
"name": "The User Owns Size Rule",
"body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.",
"section": "typography"
},
{
"name": "The Flat at Rest Rule",
"body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.",
"section": "elevation"
}
],
"dos": [
"**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).",
"**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.",
"**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.",
"**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.",
"**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.",
"**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.",
"**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.",
"**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`."
],
"donts": [
"**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.",
"**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.",
"**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.",
"**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.",
"**Don't** put shadows on docked panels, islands, rows or controls.",
"**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.",
"**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.",
"**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature."
]
}
}
-26
View File
@@ -147,32 +147,6 @@
"prefer-rest-params": "error",
"prefer-spread": "error"
}
},
{
"files": [
"evals/**/*.ts",
"perf/**/*.ts",
"smoke/**/*.ts",
"src/features/vcs/**/*.ts",
"src/features/vcs/**/*.tsx",
"src/features/run/**/*.ts",
"src/features/run/**/*.tsx",
"src/features/database/**/*.ts",
"src/features/database/**/*.tsx",
"src/features/analysis/**/*.ts",
"src/features/analysis/**/*.tsx",
"src/features/project-tree/**/*.ts",
"src/features/project-tree/**/*.tsx",
"src/features/http-client/**/*.ts",
"src/features/http-client/**/*.tsx",
"src/platform/**/*.ts",
"src/platform/**/*.tsx",
"src/features/debugger/**/*.ts",
"src/features/debugger/**/*.tsx"
],
"rules": {
"no-await-in-loop": "error"
}
}
]
}
+152
View File
@@ -0,0 +1,152 @@
# OpenIDEA — contributor guide
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
Visual style: dark, low-contrast greys, one cool accent
(`src/styles/tokens.css` is the source of truth for colours and metrics).
## Layout
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
types; never reach into another crate's internals.
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
No domain logic here.
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
keymap + dispatcher, context keys / `when` clauses, project store.
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
exporting `activate()` registered in `src/features/index.ts`.
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
- `crates/ide-host` — the `openidea-server` binary for remote development and the
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
`fixtures/` — sample projects per language for manual and automated testing.
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
preview with `npx mint dev` in `docs/`.
## Rules
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
- Long work never blocks the UI thread or a Tauri command thread: use
`spawn_blocking`/rayon, honour `CancellationToken`.
- Frontend features never import each other; communicate via actions, contributions
and services. All user-invocable behaviour is an action with a stable id; default
shortcuts live in `src/platform/keymaps/`.
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
- User-visible text goes through the text catalog: add every new string to both
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
Other locales may lack entries; their UI shows the English text until a translator adds it.
- Keep comments sparse and purposeful; match surrounding style.
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
unavailable or cannot cover the required checks.
## Issues & PRs
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain description, and a
**How it was verified** section with commands run, results and, when the change alters what users
see, before/after screenshots (not for UI removed along with a feature, copy-only or non-visual changes).
Unclear product decisions → `needs-decision` and stop.
## Skills
Do not use Impeccable or its related skills in this repository, including globally installed copies.
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`verify` drives the running app through Tauri MCP and captures screenshot evidence;
`issue-fix` takes an issue from reproduction to one PR;
`eval` takes a failing code-intelligence eval to a fix with before / after numbers.
## Commands
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
`sudo DevToolsSecurity -enable`).
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
`pnpm gen:bindings`.
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
benches vs budgets). Budgets: `perf/budgets.json`.
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
usages, gutter markers) in the production workbench against a release `openidea-server` and
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
## Before opening a PR
Run what CI runs for the parts you touched:
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
commit `src/bindings.ts`; CI fails if it differs.
- Frontend: `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm test`,
`pnpm build`, and `pnpm e2e` for UI flows.
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`).
## Pitfalls
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
the filter and runs the whole suite, which takes several minutes.
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
before committing. A cold build cache can take around 5 minutes. Run long checks one at
a time, not chained in one shell call that may hit the 10-minute tool timeout.
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
doesn't make the first launch fast.
## Parallel worktrees
Several worktrees can be developed and run side by side.
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
`pnpm install` in it.
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
URL to Tauri, and reports an existing launcher instead of starting another for the same
worktree. HMR uses the Vite port.
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
worktree path captured at build time, independent of launch cwd. Launching the same debug
binary again focuses its existing instance and forwards its path argument. Different
worktrees and the installed release can coexist. `--release` uses normal release identity
and bypasses the development wrapper.
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
default MCP session belongs to this worktree.
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
`target` symlinks at a shared directory.
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
- Stop only processes started for the current worktree/session. Never use broad
process-name kills such as `pkill openidea`.
- When done: stop that worktree's app and dev session, delete its build output, then
`git worktree remove ../<name>`.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+1
View File
@@ -1,6 +1,7 @@
# Contributing to OpenIDEA
These rules apply to everyone, and to any coding agent working on their behalf.
Project layout, coding rules, commands and checks are in [AGENTS.md](AGENTS.md).
## Issues
Generated
+48 -56
View File
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4172,7 +4172,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4184,18 +4184,17 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"serde",
"specta",
"tempfile",
"which",
]
[[package]]
name = "ide-build"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"blake3",
"chardetng",
@@ -4213,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4227,7 +4226,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4238,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4249,29 +4248,25 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"encoding_rs",
"libc",
"portable-pty",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"specta-typescript",
"tempfile",
"thiserror 2.0.21",
"tokio-util",
"tracing",
"windows-sys 0.61.2",
]
[[package]]
name = "ide-coverage"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-run",
@@ -4284,7 +4279,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4313,7 +4308,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4325,7 +4320,6 @@ dependencies = [
"ide-http",
"ide-sdk",
"ide-ssh",
"libc",
"notify",
"open",
"oracledb",
@@ -4345,14 +4339,13 @@ dependencies = [
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeroize",
"zip",
]
[[package]]
name = "ide-docker"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"serde",
@@ -4365,7 +4358,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4379,7 +4372,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4399,7 +4392,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-android",
"ide-core",
@@ -4410,7 +4403,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4422,7 +4415,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4435,7 +4428,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"criterion",
"ide-core",
@@ -4454,7 +4447,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4522,7 +4515,6 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-subscriber",
"url",
"uuid",
"windows-sys 0.61.2",
"zip",
@@ -4530,7 +4522,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"hyper-util",
"ide-core",
@@ -4549,7 +4541,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"blake3",
"criterion",
@@ -4572,7 +4564,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4584,7 +4576,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4600,7 +4592,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"libc",
"tempfile",
@@ -4609,7 +4601,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"futures",
"serde",
@@ -4620,7 +4612,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"blake3",
"criterion",
@@ -4679,7 +4671,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"criterion",
"dunce",
@@ -4708,7 +4700,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"bytes",
"dunce",
@@ -4727,7 +4719,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4748,7 +4740,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -4770,7 +4762,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4784,7 +4776,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"dunce",
"futures",
@@ -4804,7 +4796,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"dunce",
"encoding_rs",
@@ -4828,7 +4820,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-tools",
@@ -4844,7 +4836,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4870,7 +4862,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"criterion",
"encoding_rs",
@@ -4891,7 +4883,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"parking_lot",
@@ -4904,7 +4896,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4929,7 +4921,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-language",
@@ -4942,7 +4934,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-language",
@@ -4957,7 +4949,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"ide-core",
"libc",
@@ -4971,7 +4963,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"criterion",
"ide-core",
@@ -4984,7 +4976,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"flate2",
"hex",
@@ -5005,7 +4997,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -5027,7 +5019,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"chardetng",
"dunce",
@@ -5054,7 +5046,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5070,7 +5062,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -6699,7 +6691,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.51"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
View File
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.51"
version = "0.1.50"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
-323
View File
@@ -1,323 +0,0 @@
---
name: OpenIDEA
description: The IDE you know, rebuilt in Rust.
colors:
workbench-blue: "#3871e1"
link-blue: "#2f5eb9"
frame-grey: "#e9eaee"
island-white: "#ffffff"
raised-paper: "#f7f8f9"
ink: "#000000"
ink-secondary: "#5f6269"
ink-muted: "#6c707e"
ink-faint: "#9fa2a8"
hairline: "#e9eaee"
control-edge: "#d1d3d9"
selection-wash: "#d0dffe"
tab-wash: "#e3ebfe"
danger: "#c54e58"
warning: "#a56906"
success: "#338555"
frame-grey-dark: "#26282c"
island-dark: "#191a1c"
ink-dark: "#d1d3d9"
ink-strong-dark: "#dfe1e5"
ink-muted-dark: "#8c8f95"
control-edge-dark: "#40434a"
selection-wash-dark: "#2a4371"
typography:
title:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "13px"
fontWeight: 600
lineHeight: 1.4
body:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "13px"
fontWeight: 400
lineHeight: 1.4
label:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "12px"
fontWeight: 400
lineHeight: 1.4
label-tiny:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "11px"
fontWeight: 400
lineHeight: 1.4
input-large:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "15px"
fontWeight: 400
code:
fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace"
fontSize: "13px"
fontWeight: 400
lineHeight: "22px"
fontFeature: "\"liga\" 0"
rounded:
small: "4px"
control: "4px"
row: "4px"
selection: "5px"
tab: "6px"
toolbar-button: "6px"
tooltip: "6px"
popup: "8px"
island: "10px"
popup-large: "10px"
dialog: "10px"
spacing:
space-0-5: "2px"
space-1: "4px"
space-1-5: "6px"
space-2: "8px"
space-3: "12px"
space-4: "16px"
components:
button-primary:
backgroundColor: "{colors.workbench-blue}"
textColor: "{colors.island-white}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 16px"
height: "28px"
button-secondary:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 16px"
height: "28px"
button-ghost:
textColor: "{colors.ink-secondary}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 8px"
height: "28px"
icon-button:
textColor: "{colors.ink-muted}"
rounded: "{rounded.toolbar-button}"
size: "24px"
icon-button-selected:
backgroundColor: "{colors.selection-wash}"
textColor: "{colors.ink}"
rounded: "{rounded.toolbar-button}"
size: "24px"
input:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 8px"
height: "28px"
chip:
textColor: "{colors.ink-secondary}"
typography: "{typography.label}"
rounded: "{rounded.toolbar-button}"
padding: "0 6px"
height: "22px"
tooltip:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.tooltip}"
padding: "6px 10px"
list-row-selected:
backgroundColor: "{colors.selection-wash}"
textColor: "{colors.ink}"
rounded: "{rounded.row}"
height: "24px"
---
# Design System: OpenIDEA
## Overview
**Creative North Star: "The Quiet Workbench"**
The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.
The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.
Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.
The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.
Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.
### Named Rules
**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.
**Key Characteristics:**
- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.
- Grey frame, rounded content islands, tonal layering only.
- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.
- High density on a 4px grid. Compact mode is a first-class variant.
- Controls are quiet at rest: toolbar buttons and chips have no frame until hover.
- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.
- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins.
## Colors
A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes.
### Project colour
- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome.
### Primary
- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex.
- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands.
### Neutral
- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars).
- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives.
- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island.
- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text.
- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons.
- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`.
### Functional vocabularies
- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners.
- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks.
- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme.
### Named Rules
**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.
**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.
## Typography
**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks)
**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks)
**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus
**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size.
### Hierarchy
- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis.
- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons.
- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints.
- **Label Tiny** (400, 11px): stripe labels, counters and badges.
- **Input Large** (400, 15px): Search Everywhere and similar large query fields.
- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size.
### Named Rules
**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.
**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.
## Layout
The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island.
Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px.
**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes.
The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island.
## Elevation & Depth
Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit.
### Shadow Vocabulary
- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar.
- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow.
- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications.
### Named Rules
**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step.
## Shapes
Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px.
## Components
Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom.
### Buttons
- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding.
- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog.
- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%.
- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash.
- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame.
- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border.
### Icon Buttons (toolbar actions)
- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest.
- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`.
- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button.
- Tone variants (`danger`, `accent`) recolour only the icon.
### Chips
- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon.
- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover.
### Inputs / Fields
- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink.
- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow.
- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame.
- Search fields have a muted leading icon. Monospace fields use the code font.
### Lists and Trees
- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar.
- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`.
### Popups, Menus and Dialogs
- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow.
- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes.
### Tabs
- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding.
- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair.
- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow.
### Tool Window Stripes (signature)
The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window.
## Do's and Don'ts
### Do:
- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).
- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.
- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.
- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.
- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.
- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.
- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.
- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`.
### Don't:
- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.
- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.
- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.
- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.
- **Don't** put shadows on docked panels, islands, rows or controls.
- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.
- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles.
- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature.
-73
View File
@@ -1,73 +0,0 @@
# Product
<!-- impeccable:product-schema 1 -->
## Platform
web
The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope.
## Users
- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients.
- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server.
- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in.
## Product Purpose
OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory.
## Positioning
"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app.
## Operating Context
- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol).
- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend.
- Agent tasks running alongside the developer's own work, with diff review and permission prompts.
- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes.
## Capabilities and Constraints
Hard constraints future work must preserve:
1. The default keymap and interaction habits stay the same as IDEA's.
2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`).
3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this.
4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`.
5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse.
6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry.
7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down.
Other facts:
- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview.
- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout.
## Brand Commitments
- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`).
- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives.
## Evidence on Hand
- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD.
- Demo video linked from `README.md`.
- No testimonials, customer logos or user counts exist. Do not fabricate them.
## Product Principles
1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory.
2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness.
3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound.
4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions.
5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on.
## Accessibility & Inclusion
- Use real `<button>` and `<input>` elements or the primitives that render them. Every icon-only button has a translated `aria-label`.
- Keep focus visible and predictable. Dialogs and popups return focus to where it came from.
- A dark high-contrast theme (`dark-hc`) ships and must be kept working.
+1 -8
View File
@@ -6,13 +6,6 @@
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## Microsoft ConPTY
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
and [package provenance](crates/ide-core/resources/conpty/README.md).
## Project Lombok
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
@@ -73,7 +66,7 @@ At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor
These icons of [flutter-intellij](https://github.com/flutter/flutter-intellij) (commit `d02813ad5890`) are used
under the BSD 3-Clause License:
- `src/ui/expui/flutter/*.svg`: the Flutter tool window icons, copied unmodified from
- `src/ui/expui/flutter/*.svg`: the DevTools tool window icons, copied unmodified from
`resources/icons/expui/`.
- `src/ui/expui/flutter/[email protected]` and `[email protected]`: the Flutter outline's widget
icons, `resources/icons/custom/[email protected]` and `[email protected]`, renamed, content unmodified.
+2 -2
View File
@@ -196,11 +196,11 @@ fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfig
.filter(|o| config::is_per_model_option(o))
.cloned()
.map(|mut o| {
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
if config::is_context_option(&o.id) {
if o.category.is_none() {
o.category = Some("model_config".into());
}
} else if o.category.is_none() {
} else if o.category.as_deref() != Some("thought_level") {
o.category = Some("thought_level".into());
}
o
+3 -4
View File
@@ -168,12 +168,11 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
assert_eq!(calls[1].1["mcpServers"], json!([]));
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
assert_eq!(fast.category.as_deref(), Some("model_config"));
assert_eq!(fast.current.as_deref(), Some("false"));
// The effort option belongs to the session's model; m2 may offer other levels.
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
}
+6 -24
View File
@@ -15,8 +15,6 @@ use tokio::time::Instant;
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
const COOLDOWN: Duration = Duration::from_secs(30);
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
const CATALOG_SCHEMA: u8 = 2;
type Store = Arc<Mutex<HashMap<String, Known>>>;
type Key = (PathBuf, PathBuf, String);
@@ -82,8 +80,6 @@ impl CatalogData {
pub(crate) struct SavedCatalog {
/// An opaque cryptographic digest, never raw launch arguments or credentials.
fingerprint: String,
#[serde(default)]
schema: u8,
#[serde(flatten)]
catalog: CatalogData,
}
@@ -115,7 +111,7 @@ impl LaunchContext {
hash.update(&(value.len() as u64).to_le_bytes());
hash.update(value);
}
field(&mut hash, b"openidea-model-catalog-v2");
field(&mut hash, b"openidea-model-catalog-v1");
field(
&mut hash,
match self.spec.driver {
@@ -204,14 +200,7 @@ impl AgentCatalogs {
cache
.get(provider)
.and_then(|known| known.catalogs.get(&shared.root_key()))
.map(|saved| {
let mut catalog = saved.catalog.clone();
if saved.schema < CATALOG_SCHEMA {
catalog.refreshed_at_ms = None;
catalog.thought_levels.clear();
}
catalog
})
.map(|saved| saved.catalog.clone())
.unwrap_or_default()
}
@@ -239,8 +228,7 @@ impl AgentCatalogs {
}
drop(state);
let cache = shared.known.lock();
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
}
pub(super) async fn load_levels(
@@ -293,7 +281,7 @@ impl AgentCatalogs {
AgentModelCatalog {
provider: provider.to_owned(),
config: shared.config_for_new_task(catalog.config, provider),
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
thought_levels: catalog.thought_levels,
refreshing: entry.flight.is_some(),
refreshed_at_ms: catalog.refreshed_at_ms,
retry_at_ms: model_failure
@@ -330,9 +318,7 @@ impl AgentCatalogs {
let generation = state.generation;
let saved =
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
let matching = saved
.as_ref()
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
let age = saved
.as_ref()
.filter(|_| matching)
@@ -503,11 +489,7 @@ impl AgentCatalogs {
}
known.catalogs.insert(
shared.root_key(),
SavedCatalog {
fingerprint: entry.context.fingerprint(),
schema: CATALOG_SCHEMA,
catalog: catalog.clone(),
},
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
);
entry.catalog = Some(catalog);
shared.persist_known(&cache);
+27 -99
View File
@@ -65,7 +65,7 @@ fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
}
/// Moves options that approve everything without asking to a value that asks: the agent's
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
/// default or ask mode, else its first one that asks.
pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
for option in config {
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
@@ -73,15 +73,9 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
continue;
}
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
let value = option
.default_value
.as_deref()
.and_then(|def| option.values.iter().filter(asks).find(|v| v.value == def))
.or_else(|| {
["default", "ask"]
.iter()
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
})
let value = ["default", "ask"]
.iter()
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
.or_else(|| option.values.iter().find(asks));
if let Some(value) = value {
option.current = Some(value.value.clone());
@@ -89,26 +83,11 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
}
}
/// Moves approval-bearing options (`mode`, `permissions`, `approval`) to their approving value.
pub(crate) fn apply_bypass_approvals(config: &mut [AgentConfigOption]) {
for option in config {
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
if let Some(value) = option.values.iter().find(|v| bypass(&v.value)) {
option.current = Some(value.value.clone());
}
}
}
/// Applies provider-specific defaults to per-model options for new tasks without altering `default_value`.
pub(crate) fn apply_model_defaults(provider: &str, options: &mut [AgentConfigOption]) {
if provider != "cursor" {
return;
}
if let Some(fast) = options.iter_mut().find(|o| is_fast_option(&o.id))
&& fast.values.iter().any(|v| v.value == "false")
{
fast.current = Some("false".into());
}
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
let value = option.values.iter().find(|v| is_bypass_mode(&v.value))?;
Some((option, value))
}
fn is_bypass_mode(mode: &str) -> bool {
@@ -147,20 +126,14 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
}
pub(crate) fn is_context_option(id: &str) -> bool {
matches!(id, "context" | "context_tier" | "contextTier")
}
pub(crate) fn is_fast_option(id: &str) -> bool {
id == "fast"
matches!(id, "context_tier" | "contextTier")
}
/// Whether an option's available values and default belong to the selected model
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
/// rather than the provider as a whole.
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_fast_option(&o.id)
|| is_context_option(&o.id)
}
@@ -191,7 +164,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
.then(|| "thought_level".into())
})
.or_else(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
}),
current,
default_value,
@@ -364,11 +337,6 @@ fn legacy(
}
}
fn clean_label(s: String, fallback: &str) -> String {
let trimmed = s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200B}'..='\u{200D}' | '\u{FEFF}'));
if trimmed.is_empty() { fallback.to_owned() } else { trimmed.to_owned() }
}
fn value_of(v: &Value) -> Option<AgentConfigValue> {
let value = v.get("value")?.as_str()?.to_owned();
let meta = v.get("_meta");
@@ -384,7 +352,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
.filter(|s| !s.is_empty())
.map(str::to_owned);
Some(AgentConfigValue {
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
description: str_of(v, "description"),
cost_category,
usage_multiplier,
@@ -466,16 +434,19 @@ mod tests {
]}
}));
assert!(bypass_approvals(&full_access));
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
let mut asking = options_of(&json!({
let asking = options_of(&json!({
"modes": {"currentModeId": "ask", "availableModes": [
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
]}
}));
assert!(!bypass_approvals(&asking));
apply_bypass_approvals(&mut asking);
assert_eq!(asking[0].current.as_deref(), Some("full-access"));
assert!(bypass_approvals(&asking));
assert_eq!(
bypass_mode(&asking).map(|(_, v)| v.value.as_str()),
Some("full-access"),
"the offered bypass mode stays available"
);
let permissions = |current: &str| {
options_of(&json!({"configOptions": [{
@@ -532,7 +503,7 @@ mod tests {
}
#[test]
fn effort_context_and_fast_are_per_model_options() {
fn effort_and_fast_categories_are_inferred_from_ids() {
let mut c = options_of(&json!({
"configOptions": [
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
@@ -541,39 +512,19 @@ mod tests {
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
{"id": "effort", "type": "select", "currentValue": "medium",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "context", "type": "select", "currentValue": "256k",
"options": [{"value": "256k", "name": "256K"}, {"value": "500k", "name": "500K"}]},
{"id": "contextTier", "type": "select", "currentValue": "default",
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
{"id": "fast", "type": "select", "currentValue": "true",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
{"id": "fast", "type": "select", "currentValue": "false",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
]
}));
assert_eq!(c.len(), 5);
assert_eq!(c.len(), 4);
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
assert_eq!(c[2].category.as_deref(), Some("model_config"));
assert_eq!(c[3].category.as_deref(), Some("model_config"));
assert_eq!(c[4].category.as_deref(), Some("model_config"));
assert_eq!(c[4].values[1].name, "Fast");
assert!(
is_per_model_option(&c[1])
&& is_per_model_option(&c[2])
&& is_per_model_option(&c[3])
&& is_per_model_option(&c[4])
);
assert!(!is_per_model_option(&c[0]));
// Cursor defaults fast off for new tasks while preserving the agent's own default_value.
let mut cursor_opts = c.clone();
apply_model_defaults("cursor", &mut cursor_opts);
let fast = cursor_opts.iter().find(|o| o.id == "fast").unwrap();
assert_eq!((fast.current.as_deref(), fast.default_value.as_deref()), (Some("false"), Some("true")));
let mut other_opts = c.clone();
apply_model_defaults("claude", &mut other_opts);
assert_eq!(other_opts.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("true"));
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
// Editing effort on the same model preserves its initial `default_value` for Reset.
merge_update(
@@ -595,34 +546,11 @@ mod tests {
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
{"id": "effort", "type": "select", "currentValue": "low",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "context", "type": "select", "currentValue": "1m",
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
]),
);
let effort = c.iter().find(|o| o.id == "effort").unwrap();
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
let context = c.iter().find(|o| o.id == "context").unwrap();
assert_eq!((context.current.as_deref(), context.default_value.as_deref()), (Some("1m"), Some("1m")));
}
#[test]
fn apply_bypass_approvals_covers_mode_permissions_and_approval() {
let mut c = options_of(&json!({"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "ask",
"options": [{"value": "ask"}, {"value": "full-access"}]},
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "off",
"options": [{"value": "off"}, {"value": "on"}]},
{"id": "approval", "category": "approval", "type": "select", "currentValue": "ask",
"options": [{"value": "ask"}, {"value": "bypass"}]}
]}));
apply_bypass_approvals(&mut c);
assert_eq!(ids(&c), [("mode", Some("full-access")), ("allow_all", Some("on")), ("approval", Some("bypass"))]);
// Original agent default_values stay intact.
assert_eq!(
c.iter().map(|o| o.default_value.as_deref()).collect::<Vec<_>>(),
[Some("ask"), Some("off"), Some("ask")]
);
}
#[test]
-143
View File
@@ -1,143 +0,0 @@
//! Images in agent content: ACP content blocks, `data:` URLs and image files on disk.
use crate::model::AgentImage;
use base64::Engine;
use serde_json::{Value, json};
use std::path::Path;
/// Image files larger than this are not inlined into the conversation.
const MAX_FILE_BYTES: u64 = 10 * 1024 * 1024;
/// The image an ACP content block shows: an `image` (inline or by URI), a `resource` with an
/// image blob, or a `resource_link` to an image file.
pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
match str_of(content, "type")? {
"image" => {
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
&& mime.starts_with("image/")
{
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
from_uri(str_of(content, "uri")?)
}
"resource" => {
let resource = content.get("resource")?;
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
}
"resource_link" => {
let uri = str_of(content, "uri")?;
let declared = str_of(content, "mimeType").is_some_and(|m| m.starts_with("image/"));
if !declared && mime_of(Path::new(&uri_path(uri))).is_none() {
return None;
}
let mut image = from_uri(uri)?;
image.name = str_of(content, "name").map(str::to_owned);
Some(image)
}
_ => None,
}
}
fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
}
/// The image at a `data:` URL or a `file://` URI.
pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
if let Some(rest) = uri.strip_prefix("data:") {
let (mime, data) = rest.split_once(";base64,")?;
return (mime.starts_with("image/") && !data.is_empty()).then(|| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
});
}
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
}
/// The image file at `path`, when it has an image extension and isn't too large.
pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
let mime = mime_of(path)?;
if std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
return None;
}
let bytes = std::fs::read(path).ok()?;
(!bytes.is_empty()).then(|| AgentImage {
mime_type: mime.into(),
data: base64::engine::general_purpose::STANDARD.encode(bytes),
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
})
}
/// `image` as an ACP image content block.
pub(crate) fn content(image: &AgentImage) -> Value {
json!({ "type": "image", "mimeType": image.media_type(), "data": image.data })
}
fn mime_of(path: &Path) -> Option<&'static str> {
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
Some(match ext.as_str() {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"bmp" => "image/bmp",
"svg" => "image/svg+xml",
_ => return None,
})
}
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
pub(crate) fn uri_path(uri: &str) -> String {
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
let bytes = rest.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
let path = String::from_utf8_lossy(&out).into_owned();
// `file:///C:/x` on Windows.
match path.as_bytes() {
[b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => path[1..].to_owned(),
_ => path,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn content_blocks_inline_data_urls_blobs_and_image_files() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("shot 1.png");
std::fs::write(&file, b"\x89PNG\r\n").unwrap();
std::fs::write(dir.path().join("notes.txt"), b"hi").unwrap();
let uri = crate::file_uri(&file);
let inline = json!({"type": "image", "mimeType": "image/png", "data": "aW1n"});
assert_eq!(from_content(&inline).unwrap().data, "aW1n");
let by_url = json!({"type": "image", "uri": "data:image/jpeg;base64,AAA"});
assert_eq!(from_content(&by_url).unwrap().mime_type, "image/jpeg");
let by_file = from_content(&json!({"type": "image", "uri": uri})).unwrap();
assert_eq!(by_file.data, base64::engine::general_purpose::STANDARD.encode(b"\x89PNG\r\n"));
let blob = json!({"type": "resource", "resource": {"uri": "x", "mimeType": "image/gif", "blob": "R0lG"}});
assert_eq!(from_content(&blob).unwrap().mime_type, "image/gif");
let link = from_content(&json!({"type": "resource_link", "uri": uri, "name": "shot"})).unwrap();
assert_eq!((link.mime_type.as_str(), link.name.as_deref()), ("image/png", Some("shot")));
let text = crate::file_uri(&dir.path().join("notes.txt"));
assert!(from_content(&json!({"type": "resource_link", "uri": text, "name": "notes"})).is_none());
assert!(from_content(&json!({"type": "resource", "resource": {"uri": "x", "text": "t"}})).is_none());
assert!(from_content(&json!({"type": "image", "uri": "https://example.com/a.png"})).is_none());
assert!(from_file(&dir.path().join("missing.png")).is_none());
}
}
File diff suppressed because it is too large. Load diff
-10
View File
@@ -801,16 +801,6 @@ pub enum AgentEvent {
from: u32,
text: String,
},
/// Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
/// units of its output when the previous event for it was sent. Any other change of the
/// tool (status, title, diffs…) arrives as an `Entry`.
ToolOutput {
task: String,
subagent: Option<String>,
index: u32,
from: u32,
text: String,
},
/// An agent reported the usage limits of its account (shared by every task of `provider`).
Limits {
provider: String,
@@ -473,39 +473,6 @@ fn history_replays_turns() {
assert_eq!(updates[4]["status"], "completed");
}
#[test]
fn viewed_generated_and_attached_images_carry_their_pixels() {
let dir = tempfile::tempdir().unwrap();
let png = dir.path().join("shot.png");
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
let png_path = png.to_str().unwrap();
let encoded = "iVBORw0K";
let view = json!({"id": "v", "type": "imageView", "path": png_path});
assert!(tool_call(&view, false, None, None).unwrap().get("content").is_none());
let image = &tool_call(&view, true, None, None).unwrap()["content"][0]["content"];
assert_eq!((image["type"].as_str(), image["data"].as_str()), (Some("image"), Some(encoded)));
let missing = json!({"id": "v", "type": "imageView", "path": dir.path().join("gone.png")});
assert!(tool_call(&missing, true, None, None).unwrap().get("content").is_none());
let inline = json!({"id": "g", "type": "imageGeneration", "status": "completed", "result": encoded});
let image = &tool_call(&inline, true, None, None).unwrap()["content"][0]["content"];
assert_eq!((image["mimeType"].as_str(), image["data"].as_str()), (Some("image/png"), Some(encoded)));
let saved =
json!({"id": "g", "type": "imageGeneration", "status": "completed", "fileId": "f", "savedPath": png_path});
assert_eq!(tool_call(&saved, true, None, None).unwrap()["content"][0]["content"]["data"], encoded);
let thread = json!({"turns": [{"items": [{"type": "userMessage", "id": "u", "content": [
{"type": "image", "url": "data:image/jpeg;base64,/9j/"},
{"type": "image", "url": "https://example.com/a.png"},
{"type": "localImage", "path": png_path},
{"type": "localImage", "path": "/gone.png"}
]}]}]});
let contents: Vec<Value> = history(&thread, None).into_iter().map(|u| u["content"].clone()).collect();
assert_eq!(contents[0], json!({"type": "image", "mimeType": "image/jpeg", "data": "/9j/"}));
assert_eq!(contents[1]["type"], "resource_link");
assert_eq!(contents[2], json!({"type": "image", "mimeType": "image/png", "data": encoded}));
assert_eq!(contents[3], json!({"type": "text", "text": "/gone.png"}));
}
#[test]
fn history_preserves_async_questions_with_stable_answer_ids() {
let updates = history(
+26 -43
View File
@@ -348,18 +348,36 @@ pub(super) fn user_input(prompt: &Value) -> Vec<Value> {
}
"resource" => {
let r = b.get("resource")?;
let path = crate::images::uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
let path = uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
let text = r.get("text").and_then(Value::as_str)?;
Some(json!({ "type": "text", "text": format!("<file path=\"{path}\">\n{text}\n</file>") }))
}
"resource_link" => {
Some(json!({ "type": "text", "text": crate::images::uri_path(b.get("uri")?.as_str()?) }))
}
"resource_link" => Some(json!({ "type": "text", "text": uri_path(b.get("uri")?.as_str()?) })),
_ => None,
})
.collect()
}
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
fn uri_path(uri: &str) -> String {
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
let bytes = rest.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// A `session/update` notification's `update` for content.
pub(super) fn chunk(kind: &str, text: &str) -> Value {
json!({ "sessionUpdate": kind, "content": { "type": "text", "text": text } })
@@ -449,9 +467,6 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
"imageView" => {
let path = item.get("path").and_then(Value::as_str).unwrap_or_default();
call.insert("locations".into(), json!([{ "path": path }]));
if done && let Some(image) = crate::images::from_file(std::path::Path::new(path)) {
call.insert("content".into(), json!([image_content(&image)]));
}
(format!("View {}", display_path(path, cwd)), "read")
}
"collabAgentToolCall" => {
@@ -467,12 +482,7 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
}
"contextCompaction" => ("Compact the conversation".to_owned(), "other"),
"sleep" => ("Wait".to_owned(), "other"),
"imageGeneration" => {
if done && let Some(image) = generated_image(item) {
call.insert("content".into(), json!([image_content(&image)]));
}
("Generate an image".to_owned(), "other")
}
"imageGeneration" => ("Generate an image".to_owned(), "other"),
_ => return None,
};
call.insert("sessionUpdate".into(), json!(if done { "tool_call_update" } else { "tool_call" }));
@@ -483,19 +493,6 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
Some(Value::Object(call))
}
fn image_content(image: &crate::model::AgentImage) -> Value {
json!({ "type": "content", "content": crate::images::content(image) })
}
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
}
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
}
/// The output of a running command, as a `tool_call_update`.
pub(super) fn command_output(id: &str, output: &str) -> Value {
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "content": [text_content(&tail(output))] })
@@ -859,23 +856,9 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
"user_message_chunk",
c.get("text").and_then(Value::as_str).unwrap_or_default(),
)),
Some("image") => {
let url = c.get("url").and_then(Value::as_str).unwrap_or_default();
let content = crate::images::from_uri(url).map_or_else(
|| json!({ "type": "resource_link", "uri": url, "name": "image" }),
|image| crate::images::content(&image),
);
out.push(json!({ "sessionUpdate": "user_message_chunk", "content": content }));
}
Some("localImage") => {
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
out.push(match crate::images::from_file(std::path::Path::new(path)) {
Some(image) => json!({ "sessionUpdate": "user_message_chunk",
"content": crate::images::content(&image) }),
None => chunk("user_message_chunk", path),
});
}
Some("mention" | "skill") => {
Some("image") => out.push(json!({ "sessionUpdate": "user_message_chunk",
"content": { "type": "resource_link", "uri": c.get("url"), "name": "image" } })),
Some("localImage" | "mention" | "skill") => {
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
out.push(chunk("user_message_chunk", path));
}
File diff suppressed because it is too large. Load diff
+44 -103
View File
@@ -8,9 +8,6 @@ use std::collections::HashMap;
/// Tool output kept per call; longer output keeps its tail.
const MAX_OUTPUT: usize = 64 * 1024;
/// Image files a read tool names that are shown when it reports none itself.
const MAX_READ_IMAGES: usize = 4;
#[derive(Default)]
pub(crate) struct Timeline {
pub entries: Vec<AgentEntry>,
@@ -174,17 +171,51 @@ impl Timeline {
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
if let Some(content) = update.get("content").and_then(Value::as_array) {
merge_content(content, output, images, diffs);
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
let content = item.get("content");
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
&& let (Some(data), Some(mime)) =
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
&& !data.is_empty()
&& mime.starts_with("image/")
{
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
if let Some(t) = content_text(content) {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&t);
}
}
Some("diff") => {
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
let (added, removed) = line_stats(old, new);
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
}
_ => {}
}
}
// Agents that only name the image a read tool opened (Cursor): show the file itself.
if *status == AgentToolStatus::Completed && kind == "read" && images.is_empty() {
images.extend(
locs.iter()
.filter(|p| p.0.is_absolute())
.take(MAX_READ_IMAGES)
.filter_map(|p| crate::images::from_file(&p.0)),
);
if !text.is_empty() {
// The command a call announced (`$ cmd`) stays above the result that replaces it.
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
text = format!("{command}\n{text}");
}
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
@@ -351,54 +382,6 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
})
}
/// Folds a tool update's content into its output, diffs and images.
fn merge_content(
content: &[Value],
output: &mut Option<String>,
images: &mut Vec<AgentImage>,
diffs: &mut Vec<AgentToolDiff>,
) {
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
let content = item.get("content");
if let Some(image) = content.and_then(crate::images::from_content) {
new_images.push(image);
} else if let Some(t) = content_text(content) {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&t);
}
}
Some("diff") => {
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
let (added, removed) = line_stats(old, new);
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
}
_ => {}
}
}
if !text.is_empty() {
// The command a call announced (`$ cmd`) stays above the result that replaces it.
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
text = format!("{command}\n{text}");
}
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
/// The text of a list of content blocks, one per line.
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
@@ -449,7 +432,6 @@ fn tail(mut text: String) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::model::AgentImage;
use serde_json::json;
#[test]
@@ -496,47 +478,6 @@ mod tests {
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
}
#[test]
fn tool_images_come_from_linked_files_and_resource_blobs() {
let dir = tempfile::tempdir().unwrap();
let png = dir.path().join("out.png");
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r", "title": "Read", "kind": "read"}));
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "r", "content": [
{"type": "content", "content": {"type": "text", "text": "Read the image"}},
{"type": "content", "content": {"type": "resource_link", "uri": crate::file_uri(&png), "name": "out.png"}},
{"type": "content", "content": {"type": "resource", "resource": {"uri": "mem:1", "mimeType": "image/gif", "blob": "R0lG"}}}
]}));
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
let types: Vec<&str> = images.iter().map(|i| i.mime_type.as_str()).collect();
assert_eq!(types, ["image/png", "image/gif"]);
assert_eq!(output.as_deref(), Some("Read the image"));
}
#[test]
fn a_completed_read_shows_the_image_file_it_names() {
let dir = tempfile::tempdir().unwrap();
let png = dir.path().join("icon.png");
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
let text = dir.path().join("a.rs");
std::fs::write(&text, b"fn main() {}").unwrap();
let mut t = Timeline::default();
for (id, path) in [("img", &png), ("src", &text)] {
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": id, "title": "Read", "kind": "read",
"locations": [{"path": path}]}));
}
let images = |t: &Timeline, i: usize| match &t.entries[i] {
AgentEntry::Tool { images, .. } => images.len(),
_ => panic!(),
};
assert_eq!(images(&t, 0), 0, "not before the read completes");
for id in ["img", "src"] {
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}));
}
assert_eq!((images(&t, 0), images(&t, 1)), (1, 0));
}
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
+62 -240
View File
@@ -697,24 +697,12 @@ pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
out.insert(rel, stamp(&s.path));
}
if let Some(old) = &s.renamed_from
&& let Some(rel) = nested_rel(&base, repo, &roots, &repo.root().join(old))
{
out.entry(rel).or_insert(None);
}
}
}
return Ok(out);
}
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
let mut out = BTreeMap::new();
for s in repo.status()? {
out.insert(s.rel_path, stamp(&s.path));
if let Some(old) = s.renamed_from {
out.entry(old).or_insert(None);
}
}
Ok(out)
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
}
/// The files whose state changed between two snapshots of a checkout: edited, new, deleted,
@@ -775,36 +763,6 @@ pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Pa
Ok(saved)
}
fn restore_content(
cwd: &Path,
rev: Option<&str>,
change: &AgentChange,
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<Option<Vec<u8>>> {
match before.get(&change.rel_path) {
Some(None) => Ok(None),
Some(Some(_)) => {
let copy =
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
IdeError::invalid(format!(
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
change.rel_path
))
})?;
Ok(Some(std::fs::read(copy)?))
}
None => match rev {
Some(rev) => {
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
repo.file_bytes_at(&change.path.0, Some(rev))
}
None => Ok(None),
},
}
}
/// Rolls `change` back: to the copy saved when the task started when the file had changes
/// then (`before`, `saved` holding the copies), otherwise to `rev` (removed when `rev` lacks
/// it, or when there is no `rev`: the repository had no commits).
@@ -815,35 +773,28 @@ pub(crate) fn restore(
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<()> {
put(&change.path.0, restore_content(cwd, rev, change, before, saved)?)
}
/// The files the task changed since it started, with what to put back. Fails, changing
/// nothing, when one can't be put back.
pub(crate) fn plan_restore(
at: &TaskBase,
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
touched: Option<&BTreeSet<String>>,
) -> IdeResult<Vec<PutBack>> {
let changes = made_by_task(at.changes(before, None)?, touched);
let rev = at.rev()?;
let sources = match rev.as_deref() {
Some(rev) => rename_sources(at.cwd(), rev)?,
None => Default::default(),
};
let mut seen = BTreeSet::new();
let mut out = Vec::new();
for change in &changes {
for change in std::iter::once(change).chain(sources.get(&change.rel_path)) {
if !seen.insert(change.rel_path.clone()) {
continue;
}
let content = restore_content(at.cwd(), rev.as_deref(), change, before, saved)?;
out.push(PutBack { rel: change.rel_path.clone(), path: change.path.0.clone(), content });
let content = match before.get(&change.rel_path) {
Some(None) => None,
Some(Some(_)) => {
let copy =
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
IdeError::invalid(format!(
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
change.rel_path
))
})?;
Some(std::fs::read(copy)?)
}
}
Ok(out)
None => match rev {
Some(rev) => {
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
repo.file_bytes_at(&change.path.0, Some(rev))?
}
None => None,
},
};
put(&change.path.0, content)
}
/// Writes `content` to `path`, or removes the file when there is none.
@@ -868,7 +819,7 @@ pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option<Vec<u8>> {
std::fs::read(dir.join(saved_name(rel))).ok()
}
/// The checkout as one of the task's turns started: what that turn's changes are compared with
/// The checkout as the task's last turn started: what that turn's changes are compared with
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
/// and copies of those.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -889,45 +840,13 @@ pub(crate) struct TurnStart {
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub changed: Option<BTreeSet<String>>,
/// The copies are named by file and stamp, so the turns share them; the turn recorded
/// before that named them by file alone.
#[serde(default, skip_serializing_if = "is_false")]
pub stamped: bool,
}
fn is_false(b: &bool) -> bool {
!*b
}
/// The name of the copy of `rel` as stamped `stamp`: the same while the file is unchanged.
fn turn_copy_name(rel: &str, stamp: &Stamp) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(rel.as_bytes());
hasher.update(&[0]);
if let Some((len, modified)) = stamp {
hasher.update(&[1]);
hasher.update(&len.to_le_bytes());
hasher.update(&modified.to_le_bytes());
}
let hex = hasher.finalize().to_hex();
format!("t{}", &hex[..16])
}
impl TurnStart {
/// The name of the copy saved of `rel` as the turn began.
fn copy_name(&self, rel: &str) -> Option<String> {
if !self.stamped {
return Some(saved_name(rel));
}
Some(turn_copy_name(rel, self.before.get(rel)?))
}
}
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
/// A copy an earlier turn saved of a file unchanged since is used rather than made again, so
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
/// starting a turn copies little more than what the turn before it changed.
pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult<TurnStart> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart { stamped: true, ..Default::default() }) };
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
let mut heads = BTreeMap::new();
let head = if at.nested {
for repo in &at.repos {
@@ -940,95 +859,37 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult<TurnStart> {
// As the turn's end is read, so the two compare.
let before = snapshot(cwd)?;
let mut saved = BTreeSet::new();
match previous {
Some(previous) => {
for rel in &previous.saved {
let unchanged =
before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
if unchanged {
saved.insert(rel.clone());
} else {
let _ = std::fs::remove_file(dir.join(saved_name(rel)));
}
}
}
None => {
let _ = std::fs::remove_dir_all(dir);
}
}
for (rel, stamp) in &before {
let path = at.base.join(rel);
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
continue;
}
let copy = dir.join(turn_copy_name(rel, stamp));
if copy.is_file() {
saved.insert(rel.clone());
if stamp.is_none()
|| saved.contains(rel)
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
{
continue;
}
std::fs::create_dir_all(dir)?;
// One that can't be copied is listed but can't be rolled back, as a large one.
if std::fs::copy(&path, &copy).is_ok() {
if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
saved.insert(rel.clone());
}
}
Ok(TurnStart { head, heads, before, saved, changed: None, stamped: true })
}
/// Removes the copies in `dir` that none of `turns` uses any more.
pub(crate) fn prune_turn_copies<'a>(dir: &Path, turns: impl IntoIterator<Item = &'a TurnStart>) {
let used: BTreeSet<String> =
turns.into_iter().flat_map(|t| t.saved.iter().filter_map(move |rel| t.copy_name(rel))).collect();
let Ok(read) = std::fs::read_dir(dir) else { return };
for entry in read.flatten() {
if !used.contains(&*entry.file_name().to_string_lossy()) {
let _ = std::fs::remove_file(entry.path());
}
}
}
/// A file to put back as it was.
pub(crate) struct PutBack {
/// Relative to the checkout, as the task names it.
pub rel: String,
pub path: PathBuf,
/// `None`: there was no file.
pub content: Option<Vec<u8>>,
}
/// The files among `rels` that differ from how they were as the turn `start` began, with what
/// to put back. Fails, changing nothing, when one can't be put back.
pub(crate) fn rewind(cwd: &Path, start: &TurnStart, dir: &Path, rels: &BTreeSet<String>) -> IdeResult<Vec<PutBack>> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
let mut lower_counts: BTreeMap<String, usize> = BTreeMap::new();
for rel in rels {
*lower_counts.entry(rel.to_lowercase()).or_default() += 1;
}
let mut out = Vec::new();
for rel in rels {
let path = at.base.join(rel);
// A folder (a submodule, say) has nothing to put back.
if path.is_dir() {
continue;
}
let then = at_turn_start(&at, rel, start, dir)?;
// On a case-insensitive disk, `existing(&path)` can read a case-only rename's new name;
// keep the write so `put_back` deletes the new name and recreates the old one.
let case_collision = lower_counts.get(&rel.to_lowercase()).is_some_and(|&n| n > 1);
if !case_collision && existing(&path).is_some_and(|now| now == then) {
continue;
}
out.push(PutBack { rel: rel.clone(), path, content: then });
}
Ok(out)
}
/// Writes what `rewind` or `plan_restore` planned, returning the files back to their saved
/// pre-task copy so `before` can be restamped.
pub(crate) fn put_back(
mut planned: Vec<PutBack>,
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<Vec<(String, Stamp)>> {
// Removals first so a case-only rename on a case-insensitive disk ends at its old name.
planned.sort_by_key(|f| f.content.is_some());
let mut restamped = Vec::new();
for file in planned {
let should_restamp = matches!(before.get(&file.rel), Some(Some(_)))
&& file
.content
.as_deref()
.is_some_and(|bytes| saved.and_then(|d| saved_copy(d, &file.rel)).as_deref() == Some(bytes));
put(&file.path, file.content)?;
if should_restamp {
restamped.push((file.rel, stamp(&file.path)));
}
}
Ok(restamped)
Ok(TurnStart { head, heads, before, saved, changed: None })
}
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
@@ -1058,12 +919,7 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
match start.before.get(rel) {
Some(None) => Ok(None),
Some(Some(_)) => match start
.saved
.contains(rel)
.then(|| start.copy_name(rel).and_then(|name| std::fs::read(dir.join(name)).ok()))
.flatten()
{
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
Some(bytes) => Ok(Some(bytes)),
None => Err(IdeError::invalid(format!(
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
@@ -1456,64 +1312,30 @@ mod tests {
git(&repo, &["commit", "-q", "-m", "init"]);
let dir = tmp.path().join("turn");
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::<BTreeSet<_>>();
let copy = |turn: &TurnStart, rel: &str| std::fs::read(dir.join(turn.copy_name(rel).unwrap())).ok();
let at = |turn: &TurnStart, rel: &str| {
at_turn_start(&TurnRepos::of(&repo).unwrap().unwrap(), rel, turn, &dir).unwrap()
};
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
let first = start_turn(&repo, &dir).unwrap();
let first = start_turn(&repo, &dir, None).unwrap();
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
// A copy made again would replace this mark.
std::fs::write(dir.join(first.copy_name("b.txt").unwrap()), "kept\n").unwrap();
std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
let second = start_turn(&repo, &dir).unwrap();
let second = start_turn(&repo, &dir, Some(&first)).unwrap();
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
assert_eq!(copy(&second, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
assert_eq!(copy(&second, "b.txt").as_deref(), Some(&b"kept\n"[..]));
// The first turn keeps its own copy of the file changed since.
assert_eq!(at(&first, "a.txt").as_deref(), Some(&b"turn 1\n"[..]));
assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
// Back as committed: nothing to keep a copy of, and the committed text is the start.
// Back as committed: nothing to keep a copy of.
git(&repo, &["checkout", "--", "a.txt"]);
let third = start_turn(&repo, &dir).unwrap();
let third = start_turn(&repo, &dir, Some(&second)).unwrap();
assert_eq!(third.saved, set(&["b.txt"]));
assert_eq!(at(&third, "a.txt").as_deref(), Some(&b"base\n"[..]));
// Dropping the earlier turns drops the copies only they used.
prune_turn_copies(&dir, [&third]);
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
assert_eq!(copy(&third, "b.txt").as_deref(), Some(&b"kept\n"[..]));
}
#[test]
fn put_back_removes_new_name_before_writing_old_name_for_case_only_rename() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("A.txt"), "upper\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let dir = tmp.path().join("turn");
let start = start_turn(&repo, &dir).unwrap();
git(&repo, &["mv", "A.txt", "a.txt"]);
let changed = changed_in_turn(&repo, &start).unwrap().1;
let planned = rewind(&repo, &start, &dir, &changed).unwrap();
put_back(planned, &BTreeMap::new(), None).unwrap();
assert_eq!(std::fs::read_to_string(repo.join("A.txt")).unwrap(), "upper\n");
let entries: Vec<String> = std::fs::read_dir(&repo)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n != ".git")
.collect();
assert_eq!(entries, ["A.txt"]);
assert_eq!(saved_copy(&dir, "a.txt"), None);
// Without a record of the last turn (a task from before), every copy is made afresh.
let fresh = start_turn(&repo, &dir, None).unwrap();
assert_eq!(fresh.saved, set(&["b.txt"]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
}
#[cfg(unix)]
@@ -1528,7 +1350,7 @@ mod tests {
git(&repo, &["commit", "-q", "-m", "init"]);
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
let dir = tmp.path().join("turn");
let start = start_turn(&repo, &dir).unwrap();
let start = start_turn(&repo, &dir, None).unwrap();
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
let link = tmp.path().join("link");
-3
View File
@@ -10,6 +10,3 @@ ide-core.workspace = true
serde.workspace = true
specta.workspace = true
which = "8"
[dev-dependencies]
tempfile.workspace = true
+2 -74
View File
@@ -12,12 +12,11 @@ mod process;
pub use model::*;
use ide_core::process::{own_group, prepare};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::process::Command;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use std::time::Duration;
/// `adb devices` is quick unless it starts the daemon, which can take a moment.
const DEVICES: Duration = Duration::from_secs(20);
@@ -29,8 +28,6 @@ const TAIL_LINES: u32 = 200;
/// while `IDLE` makes sure a quiet stream still shows its last line promptly.
const BATCH_IDLE: Duration = Duration::from_millis(60);
const BATCH_MAX: usize = 300;
/// How long a started emulator gets to fail: a locked or broken AVD exits within it.
const EMULATOR_STARTUP: Duration = Duration::from_secs(3);
fn exe(name: &str) -> String {
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
@@ -94,51 +91,6 @@ fn executable() -> IdeResult<PathBuf> {
})
}
/// The SDK's `emulator` executable, which starts AVDs.
pub fn emulator_executable() -> Option<PathBuf> {
let name = exe("emulator");
sdk_roots().into_iter().map(|root| root.join("emulator").join(&name)).find(|p| p.is_file())
}
/// Starts AVD `avd` in its own process group, so it
/// outlives whoever asked: a restarted `flutter daemon`, a closed project, the IDE. Fails when
/// the emulator exits within its first seconds, with what it printed.
pub fn launch_emulator(avd: &str) -> IdeResult<()> {
let emulator = emulator_executable().ok_or_else(|| {
IdeError::unavailable(
"the Android emulator was not found: install it with the Android SDK Manager, or set ANDROID_HOME",
)
})?;
start_emulator(&emulator, avd)
}
fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
let log = std::fs::File::create(&log_path)?;
let mut cmd = Command::new(emulator);
cmd.arg("-avd").arg(avd);
cmd.stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
let mut child = prepare(own_group(&mut cmd)).spawn()?;
let deadline = Instant::now() + EMULATOR_STARTUP;
while Instant::now() < deadline {
if let Some(status) = child.try_wait()? {
let output = std::fs::read_to_string(&log_path).unwrap_or_default();
let tail: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
return Err(IdeError::unavailable(if tail.is_empty() {
format!("the emulator exited ({status})")
} else {
tail
}));
}
std::thread::sleep(Duration::from_millis(100));
}
// Reaps it whenever it ends.
std::thread::spawn(move || child.wait());
Ok(())
}
/// Connected devices, online ones first; starting the adb daemon when needed.
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
let adb = executable()?;
@@ -254,30 +206,6 @@ mod tests {
}
}
#[cfg(unix)]
#[test]
fn an_emulator_that_fails_at_once_says_why_and_one_that_runs_is_left_running() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let script = |name: &str, body: &str| {
let path = dir.path().join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
};
let broken = script("broken", "echo \"PANIC: Missing emulator engine for $2\" >&2\nexit 1\n");
let e = start_emulator(&broken, "Pixel_9").unwrap_err();
assert_eq!(e.message, "PANIC: Missing emulator engine for Pixel_9");
let args = dir.path().join("args");
let running =
script("running", &format!("echo $$ > '{0}.pid'\necho \"$@\" > '{0}'\nexec sleep 30\n", args.display()));
start_emulator(&running, "Pixel_9").unwrap();
assert_eq!(std::fs::read_to_string(&args).unwrap().trim(), "-avd Pixel_9");
let pid = std::fs::read_to_string(dir.path().join("args.pid")).unwrap();
assert!(Command::new("kill").arg(pid.trim()).status().unwrap().success(), "still running");
}
#[test]
fn executable_is_absolute_when_found() {
if let Some(adb) = adb_executable() {
+1 -2
View File
@@ -26,10 +26,9 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
let module = dunce::canonicalize(root.join(module))?;
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
let mut args = p.options.clone();
let repo = crate::maven::local_repository_for(&p.options);
args.extend([
"process-resources".into(),
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
"help:evaluate".into(),
"-Dexpression=project.build.outputDirectory".into(),
format!("-Doutput={}", manifest.display()),
]);
+14 -34
View File
@@ -15,12 +15,12 @@ pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, module_classpaths,
single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
structure_war_plan, structure_web_artifacts,
};
pub use up_to_date::{menu_up_to_date, record_menu_build};
@@ -965,7 +965,6 @@ pub struct LaunchBuild {
/// Compiles the module at `module` with its build system before a JVM launch and
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
/// The build's console, messages and progress stream to `on_event` as it runs.
pub fn build_for_launch(
root: &Path,
model: &BuildModel,
@@ -973,9 +972,8 @@ pub fn build_for_launch(
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<LaunchBuild> {
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?;
Ok(built.pop().unwrap())
}
@@ -988,10 +986,9 @@ pub fn build_for_launches(
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Vec<LaunchBuild>> {
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
let result = run(root, &plan, cancel, on_event)?;
let result = run(root, &plan, cancel, &|_| {})?;
let failure = if !result.success {
let errors: Vec<String> = result
.messages
@@ -1825,16 +1822,8 @@ mod tests {
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut model = reactor_model();
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
let dirs = build_for_launch(
root,
&model,
&root.join("app"),
true,
BuildKind::Build,
&CancellationToken::new(),
&|_| {},
)
.unwrap();
let dirs = build_for_launch(root, &model, &root.join("app"), true, BuildKind::Build, &CancellationToken::new())
.unwrap();
assert_eq!(
dirs.class_dirs,
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
@@ -1845,25 +1834,16 @@ mod tests {
"mvnw",
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
);
let error = build_for_launch(
root,
&model,
&root.join("app"),
false,
BuildKind::Build,
&CancellationToken::new(),
&|_| {},
)
.unwrap()
.failure
.unwrap();
let error =
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new())
.unwrap()
.failure
.unwrap();
assert!(error.contains("Kotlin compilation failed"), "{error}");
let cancel = CancellationToken::new();
cancel.cancel();
assert_eq!(
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel, &|_| {})
.unwrap_err()
.kind,
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel).unwrap_err().kind,
ide_core::error::ErrorKind::Cancelled
);
}
+7 -35
View File
@@ -200,22 +200,19 @@ fn kotlin_line(line: &str) -> Option<RawMessage> {
kotlin_location(rest, severity)
}
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`
/// (and localized javac prefixes such as Chinese/Japanese `错误:` / `錯誤:` / `エラー:` / `警告:`).
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`.
fn javac_header(line: &str) -> Option<RawMessage> {
let (path, ln, col, rest) = path_line_col(line)?;
if !looks_like_source_path(path) {
return None;
}
let rest = rest.trim_start_matches(':').trim_start();
let (severity, msg) = ["error:", "错误:", "錯誤:", "エラー:"]
.into_iter()
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Error, m)))
.or_else(|| {
["warning:", "警告:"]
.into_iter()
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Warning, m)))
})?;
let (severity, msg) = if let Some(m) = rest.strip_prefix("error:") {
(Severity::Error, m)
} else {
let m = rest.strip_prefix("warning:")?;
(Severity::Warning, m)
};
Some(RawMessage::new(severity, msg.trim(), ColUnit::Char).at(path, ln, col))
}
@@ -558,31 +555,6 @@ mod tests {
assert_eq!(out[1].text, "[removal] finalize() has been deprecated");
}
#[test]
fn localized_javac_errors_and_warnings() {
let out = parse(
Format::Gradle,
"/p/src/A.java:12: 错误: 找不到符号\n\
\x20 Foo foo = new Foo();\n\
\x20 ^\n\
\x20 符号: 类 Foo\n\
\x20 位置: 类 A\n\
/p/src/B.java:5: 錯誤: 需要 ';'\n\
\x20 int x = 1\n\
\x20 ^\n\
/p/src/C.java:8: 警告: [deprecation] old() 已过时\n\
\x20 old();\n\
\x20 ^\n",
);
assert_eq!(out.len(), 3, "{out:?}");
assert_eq!(pos(&out[0]), (Severity::Error, "/p/src/A.java", 12, Some(9)));
assert_eq!(out[0].text, "找不到符号\n符号: 类 Foo\n位置: 类 A");
assert_eq!(pos(&out[1]), (Severity::Error, "/p/src/B.java", 5, Some(14)));
assert_eq!(out[1].text, "需要 ';'");
assert_eq!(pos(&out[2]), (Severity::Warning, "/p/src/C.java", 8, Some(5)));
assert_eq!(out[2].text, "[deprecation] old() 已过时");
}
#[test]
fn gradle_kotlin() {
let out = parse(
+60 -356
View File
@@ -1,4 +1,4 @@
//! Single-file Java compilation with `javac` for the Recompile action (#2476).
//! Single-file Java compilation with `javac` for the Compile File action (#2476).
//!
//! A module build (`-pl … -am`) still walks every upstream module, and packaging
//! walks the whole reactor; compiling one file only needs that file's module
@@ -6,93 +6,12 @@
use super::*;
use serde::{Deserialize, Serialize};
use std::fs;
use std::process::Command as ProcCommand;
/// Output file of the `dependency:build-classpath` probe, relative to each module.
const CP_FILE: &str = "target/ide-compile-cp.txt";
// Older records include undeclared reactor test outputs even in runtime classpaths.
const CLASSPATH_CACHE_VERSION: u32 = 1;
const GRADLE_COMPILE_CP_INIT_SCRIPT: &str = include_str!("../gradle-compile-cp.init.gradle");
pub(super) fn is_java_file(file: &Path) -> IdeResult<String> {
if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
Ok(file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())
}
pub(super) fn is_test_source(rel: &str) -> bool {
let parts: Vec<&str> = rel.split(['/', '\\']).collect();
parts.windows(2).any(|w| w == ["src", "test"])
}
pub(super) fn java_home_major(env: &BTreeMap<String, String>) -> Option<u32> {
let home = env.get("JAVA_HOME").filter(|h| !h.trim().is_empty())?;
let release = fs::read_to_string(Path::new(home).join("release")).ok()?;
let value = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?;
let value = value.trim().trim_matches(['"', '\'']);
language_release(value)
}
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
pub(super) fn release_args(level: Option<u32>, jdk_major: Option<u32>) -> Vec<String> {
let Some(level) = level else { return Vec::new() };
if jdk_major.is_none_or(|m| m >= 9) {
vec!["--release".into(), level.to_string()]
} else {
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
}
}
pub(super) fn join_classpath(entries: impl IntoIterator<Item = String>) -> String {
let separator = if cfg!(windows) { ";" } else { ":" };
let mut seen = HashSet::new();
let mut out = Vec::new();
for entry in entries {
if !entry.is_empty() && seen.insert(entry.clone()) {
out.push(entry);
}
}
out.join(separator)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_javac_step(
javac: &str,
cwd: &Path,
out_dir: &Path,
classpath: &str,
sources: &[PathBuf],
release: Vec<String>,
file: &Path,
env: BTreeMap<String, String>,
) -> IdeResult<BuildStep> {
fs::create_dir_all(out_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
if !classpath.is_empty() {
step.args.extend(["-cp".into(), classpath.to_owned()]);
}
// Classes of the module that were never built (or are older than their source) are read
// from its sources; only `file` is written, so a test compile never puts main classes
// into test-classes.
if !sources.is_empty() {
let separator = if cfg!(windows) { ";" } else { ":" };
step.args.push("-sourcepath".into());
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
step.args.push("-implicit:none".into());
}
step.args.extend(release);
step.args.push(file.to_string_lossy().into_owned());
step.env = env;
step.mkdirs = vec![out_dir.to_path_buf()];
Ok(step)
}
/// The resolved dependency classpath for one module and scope, tied to the same
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
@@ -122,7 +41,12 @@ pub struct SingleFileTarget {
/// Locates the linked Maven module owning a `.java` source file.
pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<SingleFileTarget> {
is_java_file(file)?;
if file.extension().is_none_or(|ext| ext != "java") {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
let Some(m) = &model.maven else {
return Err(IdeError::not_found("no linked Maven project found for module"));
};
@@ -146,7 +70,8 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
let top_dir = subdir(root, &top.dir);
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
// Test sources see the test classpath and compile into test classes.
let test = is_test_source(&rel);
let parts: Vec<&str> = rel.split('/').collect();
let test = parts.windows(2).any(|w| w == ["src", "test"]);
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
}
@@ -187,17 +112,7 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
pub fn single_file_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
single_file_classpath_cancellable(root, model, target, &CancellationToken::new())
}
fn single_file_classpath_cancellable(
root: &Path,
model: &BuildModel,
target: &SingleFileTarget,
cancel: &CancellationToken,
) -> IdeResult<String> {
let scope = if target.test { "test" } else { "compile" };
classpath(root, model, target, scope, false, cancel)
classpath(root, model, target, "test", false)
}
/// Runtime (or test) dependency classpath for a launch module.
@@ -257,12 +172,10 @@ pub fn module_classpaths(
}
let scope = if test { "test" } else { "runtime" };
let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect();
let classpaths = match classpaths(root, model, &targets, scope, true, cancel) {
let classpaths = match classpaths(root, model, &targets, scope, true) {
Ok(classpaths) => classpaths,
// Another module's failure must not cost this launch its own probe.
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => {
classpaths(root, model, &targets[..1], scope, true, cancel)?
}
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => classpaths(root, model, &targets[..1], scope, true)?,
Err(e) => return Err(e),
};
if cancel.is_cancelled() {
@@ -323,9 +236,8 @@ fn classpath(
target: &SingleFileTarget,
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
Ok(classpaths(root, model, &[target], scope, compile_first)?.pop().unwrap())
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -335,7 +247,6 @@ fn classpaths(
targets: &[&SingleFileTarget],
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<Vec<String>> {
let top = &targets[0].top;
let probe = CP_FILE;
@@ -361,21 +272,18 @@ fn classpaths(
if compile_first {
args.push("compile");
}
let build_classpath =
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
if e.kind == ide_core::error::ErrorKind::Cancelled {
e
} else {
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
}
})?;
if !out.success {
let mut command = ProcCommand::new(&top.command);
command.args(&args).envs(&top.env).current_dir(&top_dir);
let status = ide_core::process::prepare(&mut command)
.output()
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
if !status.status.success() {
let stdout = String::from_utf8_lossy(&status.stdout);
let stderr = String::from_utf8_lossy(&status.stderr);
// Maven reports reactor/dependency failures on stdout, not only stderr.
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
@@ -417,14 +325,39 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
})?;
let separator = if cfg!(windows) { ';' } else { ':' };
entries.extend(content.split([separator, '\n', '\r']).map(str::trim).filter(|e| !e.is_empty()).map(str::to_owned));
Ok(join_classpath(entries))
entries.dedup();
Ok(entries.join(&separator.to_string()))
}
/// The `javac` step compiling `file` into `target`'s output directory.
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
fs::create_dir_all(&target.out_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", target.out_dir.display())))?;
let mut step = BuildStep::new(javac, &[], &target.module, Format::Gradle);
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
step.args.push("-encoding".into());
step.args.push("UTF-8".into());
step.args.push("-d".into());
step.args.push(target.out_dir.to_string_lossy().into_owned());
step.args.push("-cp".into());
step.args.push(classpath.to_owned());
// Classes of the module that were never built (or are older than their source) are read
// from its sources; only `file` is written, so a test compile never puts main classes
// into test-classes.
let sources = source_roots(target);
let release = release_args(target.java_version, java_home_major(&target.top.env));
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
if !sources.is_empty() {
let separator = if cfg!(windows) { ";" } else { ":" };
step.args.push("-sourcepath".into());
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
step.args.push("-implicit:none".into());
}
if let Some(version) = target.java_version {
step.args.push("--release".into());
step.args.push(version.to_string());
}
step.args.push(file.to_string_lossy().into_owned());
step.env = target.top.env.clone();
Ok(step)
}
/// The module's Java source folders that exist, generated ones included; test sources see
@@ -450,18 +383,8 @@ fn source_roots(target: &SingleFileTarget) -> Vec<PathBuf> {
/// Resolves the classpath and plans the `javac` invocation for one Java source.
pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<BuildPlan> {
compile_file_plan_cancellable(root, model, file, &CancellationToken::new())
}
/// Cancellable [`compile_file_plan`].
pub fn compile_file_plan_cancellable(
root: &Path,
model: &BuildModel,
file: &Path,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let target = single_file_target(root, model, file)?;
let classpath = single_file_classpath_cancellable(root, model, &target, cancel)?;
let classpath = single_file_classpath(root, model, &target)?;
let javac = find_javac(&target.top.env);
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Ok(BuildPlan {
@@ -471,140 +394,6 @@ pub fn compile_file_plan_cancellable(
})
}
fn gradle_for_file<'a>(
root: &Path,
model: &'a BuildModel,
file: &Path,
) -> Option<(&'a crate::GradleModel, &'a crate::GradleProject, PathBuf)> {
let file = normalize(file);
let file_ref = &file;
model
.gradle
.iter()
.flat_map(|g| {
let g_dir = normalize(&subdir(root, &g.dir));
let g_depth = g_dir.components().count();
g.projects.iter().filter_map(move |p| {
let p_dir = normalize(&subdir(root, &p.dir));
file_ref.starts_with(&p_dir).then_some((g, p, p_dir, g_depth))
})
})
.max_by_key(|(_, _, p_dir, g_depth)| (p_dir.components().count(), *g_depth))
.map(|(g, p, p_dir, _)| (g, p, p_dir))
}
/// Whether `file` lies inside a linked Gradle project of `model`.
pub fn has_gradle_file_target(root: &Path, model: &BuildModel, file: &Path) -> bool {
gradle_for_file(root, model, file).is_some()
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GradleCompileCp {
out_dir: Option<String>,
#[serde(default)]
classpath: Vec<String>,
#[serde(default)]
src_dirs: Vec<String>,
release: Option<u32>,
}
/// Resolves the compile classpath from Gradle and plans a single-file `javac` step.
pub fn gradle_compile_file_plan(
root: &Path,
model: &BuildModel,
file: &Path,
cache: &Path,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let name = is_java_file(file)?;
let (gradle, project, module_dir) = gradle_for_file(root, model, file)
.ok_or_else(|| IdeError::not_found("no linked Gradle project found for file"))?;
let rel = rel_str(&module_dir, file);
let test = is_test_source(&rel);
let scope = if test { "test" } else { "main" };
fs::create_dir_all(cache)?;
let init_script = cache.join("gradle-compile-cp.init.gradle");
fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
let args = vec![
"--console=plain".into(),
"-q".into(),
"-Dorg.gradle.configuration-cache=false".into(),
"--init-script".into(),
init_script.to_string_lossy().into_owned(),
format!("-Popenidea.target={}", project.path),
format!("-Popenidea.scope={scope}"),
"help".into(),
];
let gradle_dir = subdir(root, &gradle.dir);
let mut reported: Option<String> = None;
let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
reported = Some(json.to_owned());
}
})
.map_err(|e| {
if e.kind == ide_core::error::ErrorKind::Cancelled {
e
} else {
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
}
})?;
if !out.success {
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
let json = reported.ok_or_else(|| {
IdeError::internal(format!(
"cannot resolve the compile classpath: Gradle did not report source set '{scope}' for {}",
project.path
))
})?;
let cp: GradleCompileCp = serde_json::from_str(&json)
.map_err(|e| IdeError::internal(format!("cannot parse Gradle compile classpath: {e}")))?;
let out_dir = cp
.out_dir
.filter(|d| !d.trim().is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| module_dir.join("build/classes/java").join(scope));
let mut cp_entries: Vec<String> = Vec::new();
if out_dir.is_dir() {
cp_entries.push(out_dir.to_string_lossy().into_owned());
}
if test {
let main_out = module_dir.join("build/classes/java/main");
if main_out.is_dir() {
cp_entries.push(main_out.to_string_lossy().into_owned());
}
}
for sibling in &gradle.projects {
let sibling_dir = subdir(root, &sibling.dir);
if sibling_dir == module_dir {
continue;
}
let classes = sibling_dir.join("build/classes/java/main");
if classes.is_dir() {
cp_entries.push(classes.to_string_lossy().into_owned());
}
}
cp_entries.extend(cp.classpath);
let classpath = join_classpath(cp_entries);
let mut sources: Vec<PathBuf> = cp.src_dirs.into_iter().map(PathBuf::from).filter(|p| p.is_dir()).collect();
if sources.is_empty() {
let fallback: &[&str] = if test { &["src/test/java", "src/main/java"] } else { &["src/main/java"] };
sources.extend(fallback.iter().map(|s| module_dir.join(s)).filter(|p| p.is_dir()));
}
let javac = find_javac(&gradle.env);
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
let step =
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
}
#[cfg(test)]
mod tests {
use super::*;
@@ -650,8 +439,7 @@ mod tests {
#[test]
fn target_finds_the_owning_module_and_the_test_scope() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
let model = fixture(root);
let main = single_file_target(root, &model, &root.join("app/src/main/java/demo/Main.java")).unwrap();
assert_eq!(main.module, root.join("app"));
@@ -665,8 +453,7 @@ mod tests {
#[test]
fn target_rejects_non_java_missing_and_unlinked_files() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
let model = fixture(root);
write(root, "app/pom.xml", "<project/>");
assert!(single_file_target(root, &model, &root.join("app/pom.xml")).is_err());
@@ -678,8 +465,7 @@ mod tests {
#[test]
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
let model = fixture(root);
let file = root.join("app/src/test/java/demo/MainTest.java");
let target = single_file_target(root, &model, &file).unwrap();
@@ -715,8 +501,7 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -747,7 +532,6 @@ mod tests {
assert!(cp.split(separator).count() >= 3, "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(!args.lines().any(|a| a == "compile" || a == "package"), "{args}");
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=compile"), "{args}");
fs::create_dir_all(root.join("app/target/test-classes")).unwrap();
let target = single_file_target(root, &model, &root.join("app/src/test/java/demo/MainTest.java")).unwrap();
let cp = single_file_classpath(root, &model, &target).unwrap();
@@ -755,8 +539,6 @@ mod tests {
assert_eq!(paths[0], root.join("app/target/test-classes"));
assert!(paths.contains(&root.join("app/target/classes")), "{cp}");
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
/// Launches request Maven's matching scope without adding reactor test outputs.
@@ -766,8 +548,7 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -824,8 +605,7 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
fixture(root);
write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}");
let script = root.join("mvnw");
@@ -866,8 +646,7 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
fixture(root);
let script = root.join("mvnw");
// `dependency:build-classpath` reports reactor outputs as absolute paths. Keep
@@ -933,79 +712,4 @@ mod tests {
calls.push('x');
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
}
#[test]
fn javac_step_omits_empty_classpath_and_uses_source_target_on_jdk_8() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let mut model = fixture(root);
let file = root.join("app/src/main/java/demo/Main.java");
let jdk8 = root.join("jdk8");
fs::create_dir_all(jdk8.join("bin")).unwrap();
fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"\n").unwrap();
let project = model.maven.as_mut().unwrap().projects.iter_mut().find(|p| p.dir == "app").unwrap();
project.java_version = Some(8);
let mut target = single_file_target(root, &model, &file).unwrap();
target.top.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
let step = javac_step(&target, &file, "", "javac").unwrap();
assert!(!step.args.iter().any(|a| a == "-cp"), "{:?}", step.args);
assert!(step.args.iter().any(|a| a == "-g"), "{:?}", step.args);
assert!(step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]), "{:?}", step.args);
assert!(!step.args.iter().any(|a| a == "--release"), "{:?}", step.args);
}
#[cfg(unix)]
#[test]
fn gradle_single_file_compiles_with_source_set_classpath_and_siblings() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
write(root, "settings.gradle", "include ':lib', ':app'");
write(root, "lib/build.gradle", "plugins { id 'java' }");
write(root, "app/build.gradle", "plugins { id 'java' }");
write(root, "app/src/main/java/demo/App.java", "package demo; class App {}");
write(root, "app/src/test/java/demo/AppTest.java", "package demo; class AppTest {}");
fs::create_dir_all(root.join("lib/build/classes/java/main")).unwrap();
fs::create_dir_all(root.join("app/build/classes/java/main")).unwrap();
let wrapper = root.join("gradlew");
fs::write(
&wrapper,
"#!/bin/sh\nprintf '%s\\n' \"$@\" > gradle_args.txt\nscope='main'\nfor a in \"$@\"; do\ncase \"$a\" in -Popenidea.scope=*) scope=\"${a#-Popenidea.scope=}\" ;; esac\ndone\nprintf '@openidea-compile-cp\\t{\"outDir\":\"%s/app/build/classes/java/%s\",\"classpath\":[\"%s/deps/guava.jar\"],\"srcDirs\":[\"%s/app/src/%s/java\"],\"release\":17}\\n' \"$PWD\" \"$scope\" \"$PWD\" \"$PWD\" \"$scope\"\n",
)
.unwrap();
fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
let model = crate::load(root, &root.join("cache"), None);
let cache = root.join("cache");
let cancel = CancellationToken::new();
let main_file = root.join("app/src/main/java/demo/App.java");
let main_plan = gradle_compile_file_plan(root, &model, &main_file, &cache, &cancel).unwrap();
assert_eq!(main_plan.system, BuildSystem::Gradle);
assert_eq!(main_plan.title, "Compile App.java");
let step = &main_plan.steps[0];
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Popenidea.target=:app"), "{args}");
assert!(args.lines().any(|a| a == "-Popenidea.scope=main"), "{args}");
let cp = &step.args[step.args.iter().position(|a| a == "-cp").unwrap() + 1];
let paths: Vec<_> = std::env::split_paths(cp).collect();
assert!(paths.contains(&root.join("app/build/classes/java/main")), "{cp}");
assert!(paths.contains(&root.join("lib/build/classes/java/main")), "{cp}");
assert!(paths.contains(&root.join("deps/guava.jar")), "{cp}");
assert!(step.args.windows(2).any(|w| w == ["--release", "17"]), "{:?}", step.args);
assert!(step.args.iter().any(|a| a == "-implicit:none"), "{:?}", step.args);
let test_file = root.join("app/src/test/java/demo/AppTest.java");
let test_plan = gradle_compile_file_plan(root, &model, &test_file, &cache, &cancel).unwrap();
assert_eq!(test_plan.title, "Compile AppTest.java");
let test_step = &test_plan.steps[0];
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Popenidea.scope=test"), "{args}");
assert!(
test_step.args.windows(2).any(|w| w == ["-d", &root.join("app/build/classes/java/test").to_string_lossy()])
);
}
}
+21 -157
View File
@@ -162,6 +162,16 @@ fn classpath(entries: &[String]) -> String {
entries.join(if cfg!(windows) { ";" } else { ":" })
}
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
fn release_args(level: Option<u32>, jdk: Option<&StructureJdk>) -> Vec<String> {
let Some(level) = level else { return Vec::new() };
if jdk.is_none_or(|j| j.major >= 9) {
vec!["--release".into(), level.to_string()]
} else {
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
}
}
/// `"17"`, `"1.8"`, `"JDK_17"` → the release number.
pub fn language_release(level: &str) -> Option<u32> {
let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', ".");
@@ -169,25 +179,6 @@ pub fn language_release(level: &str) -> Option<u32> {
digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0)
}
fn structure_compiler(
root: &Path,
ps: &ProjectStructureSettings,
jdk: Option<&StructureJdk>,
language_level: &str,
) -> (Option<u32>, BTreeMap<String, String>, String) {
let module = root_module(root, ps);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release);
let env: BTreeMap<String, String> = jdk
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
let javac = find_javac(&env);
(level, env, javac)
}
/// The Build / Rebuild plan of a project without a build tool, or `None` when it has no
/// Java sources under its source roots. `language_level`: the project's, unless the module
/// overrides it. Writes the javac argument files below `cache`.
@@ -212,7 +203,16 @@ pub fn structure_plan(
return Ok(None);
}
let (main_out, test_out) = structure_outputs(root, ps);
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
let module = root_module(root, ps);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release);
let env: BTreeMap<String, String> = jdk
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
let javac = find_javac(&env);
let args_dir = cache.join("javac");
fs::create_dir_all(&args_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", args_dir.display())))?;
@@ -241,7 +241,7 @@ pub fn structure_plan(
if !cp.is_empty() {
step.args.extend(["-cp".into(), classpath(cp)]);
}
step.args.extend(single::release_args(level, jdk.map(|j| j.major)));
step.args.extend(release_args(level, jdk));
step.args.push(format!("@{}", args_file.to_string_lossy()));
step.env = env.clone();
step.mkdirs = vec![out.to_path_buf()];
@@ -281,47 +281,6 @@ pub fn structure_plan(
Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps }))
}
/// Single-file `javac` plan for a Java project without a build tool (Project Structure).
pub fn structure_compile_file_plan(
root: &Path,
ps: &ProjectStructureSettings,
roots: &StructureRoots,
jdk: Option<&StructureJdk>,
language_level: &str,
file: &Path,
) -> IdeResult<BuildPlan> {
let name = single::is_java_file(file)?;
let rel = rel_str(root, file);
let test = if roots.tests.is_empty() {
single::is_test_source(&rel)
} else {
let file_norm = normalize(file);
roots.tests.iter().any(|t| file_norm.starts_with(normalize(t)))
};
let (main_out, test_out) = structure_outputs(root, ps);
let out_dir = if test { &test_out } else { &main_out };
let mut cp: Vec<String> = Vec::new();
if test && test_out.is_dir() {
cp.push(test_out.to_string_lossy().into_owned());
}
if main_out.is_dir() {
cp.push(main_out.to_string_lossy().into_owned());
}
cp.extend(library_entries(root, ps, test));
let cp = single::join_classpath(cp);
let mut src_roots: Vec<PathBuf> = Vec::new();
if test {
src_roots.extend(roots.tests.iter().filter(|p| p.is_dir()).cloned());
}
src_roots.extend(roots.sources.iter().filter(|p| p.is_dir()).cloned());
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
let release = single::release_args(level, jdk.map(|j| j.major));
let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?;
Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] })
}
/// Where an artifact goes: its output folder, else `out/artifacts/<name>`.
pub fn artifact_output(root: &Path, artifact: &ArtifactConfig) -> PathBuf {
resolve_dir(root, &artifact.output_directory)
@@ -1049,99 +1008,4 @@ mod tests {
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("c.jar").is_file());
}
#[test]
fn plans_single_file_javac_for_main_test_and_jdk8() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("shop");
write(&root.join("src/com/a/Main.java"), "package com.a; class Main {}");
write(&root.join("test/com/a/MainTest.java"), "package com.a; class MainTest {}");
write(&root.join("out/production/shop/com/a/Helper.class"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary { name: "core".into(), classes: vec!["lib/core.jar".into()], ..Default::default() },
ProjectLibrary {
name: "junit".into(),
classes: vec!["lib/junit.jar".into()],
scope: DependencyScope::Test,
..Default::default()
},
],
..Default::default()
};
let roots =
StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() };
let jdk21 = StructureJdk { home: PathBuf::from("/jdk21"), major: 21 };
let main_plan =
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk21), "17", &root.join("src/com/a/Main.java"))
.unwrap();
assert_eq!(main_plan.system, BuildSystem::Javac);
assert_eq!(main_plan.title, "Compile Main.java");
let main_step = &main_plan.steps[0];
let cp = &main_step.args[main_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
assert!(cp.contains("core.jar") && !cp.contains("junit.jar"), "{cp}");
assert!(main_step.args.windows(2).any(|w| w == ["--release", "17"]));
assert!(main_step.args.iter().any(|a| a == "-implicit:none"));
let jdk8 = StructureJdk { home: PathBuf::from("/jdk8"), major: 8 };
let test_plan =
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk8), "8", &root.join("test/com/a/MainTest.java"))
.unwrap();
let test_step = &test_plan.steps[0];
let test_cp = &test_step.args[test_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
assert!(test_cp.contains("out/production/shop") || test_cp.contains("out\\production\\shop"), "{test_cp}");
assert!(test_cp.contains("junit.jar"), "{test_cp}");
assert!(test_step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]));
assert!(test_step.args.windows(2).any(|w| w[0] == "-d" && Path::new(&w[1]).ends_with("out/test/shop")));
}
#[test]
fn compiles_only_the_target_java_file_and_reports_errors() {
let exe = if cfg!(windows) { "javac.exe" } else { "javac" };
if !std::process::Command::new(exe).arg("-version").output().is_ok_and(|o| o.status.success()) {
return;
}
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("demo");
let good = root.join("src/p/Good.java");
let broken_sibling = root.join("src/p/BrokenSibling.java");
let bad_target = root.join("src/p/BadTarget.java");
write(&good, "package p;\npublic class Good { public static int ok() { return 1; } }\n");
write(&broken_sibling, "package p;\npublic class BrokenSibling { MissingType field; }\n");
write(&bad_target, "package p;\npublic class BadTarget {\n UnknownSymbol field;\n}\n");
let ps = ProjectStructureSettings::default();
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let cancel = CancellationToken::new();
// 1. Valid file compiles cleanly without touching or failing on BrokenSibling.java.
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &good).unwrap();
let events = std::sync::Mutex::new(Vec::new());
let result = run(&root, &plan, &cancel, &|e| events.lock().unwrap().push(e)).unwrap();
assert!(result.success, "expected single-file compile to succeed: {:?}", result.messages);
assert_eq!(result.errors, 0);
assert!(root.join("out/production/demo/p/Good.class").is_file());
assert!(!root.join("out/production/demo/p/BrokenSibling.class").exists());
// 2. Broken target fails, streams raw compiler output, and produces structured diagnostics.
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &bad_target).unwrap();
let bad_events = std::sync::Mutex::new(Vec::new());
let bad_result = run(&root, &plan, &cancel, &|e| bad_events.lock().unwrap().push(e)).unwrap();
assert!(!bad_result.success);
assert!(bad_result.errors >= 1, "{bad_result:?}");
assert!(
bad_events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Output { .. })),
"expected streamed output"
);
assert!(
bad_result.messages.iter().any(|m| {
m.severity == Severity::Error
&& m.path.as_ref().is_some_and(|p| <ide_core::IpcPath as AsRef<Path>>::as_ref(p) == bad_target)
&& m.range.is_some_and(|r| r.start.line == 2)
}),
"messages={:?}",
bad_result.messages
);
}
}
@@ -1,58 +0,0 @@
// OpenIDEA single-file javac classpath probe for Gradle projects.
// Prints the target source set's output directory, compile classpath, source dirs and release version.
import groovy.json.JsonOutput
def identity = { Project p -> try { p.identityPath.toString() } catch (ignored) { p.path } }
gradle.projectsEvaluated { g ->
def wantedTarget = g.rootProject.findProperty('openidea.target')?.toString() ?: ':'
def scope = g.rootProject.findProperty('openidea.scope')?.toString() ?: 'main'
def project = g.rootProject.allprojects.find { identity(it) == wantedTarget }
if (project == null && g.parent == null) {
project = g.rootProject.allprojects.find { it.path == wantedTarget }
}
if (project == null) return
def sets = project.extensions.findByName('sourceSets') ?: project.findProperty('sourceSets')
def ss = sets?.findByName(scope)
if (ss == null) return
def outDir = null
try { outDir = ss.java.destinationDirectory.get().asFile.canonicalPath } catch (ignored) {}
if (outDir == null) {
try { outDir = ss.output.classesDirs.files.iterator().next().canonicalPath } catch (ignored) {}
}
def cp = []
if (scope == 'test') {
def mainSet = sets.findByName('main')
try { mainSet?.output?.classesDirs?.files?.each { cp << it.canonicalPath } } catch (ignored) {}
}
try { ss.compileClasspath.files.each { cp << it.canonicalPath } } catch (ignored) {}
cp = cp.unique()
def srcDirs = []
try { ss.java.srcDirs.each { srcDirs << it.canonicalPath } } catch (ignored) {}
if (scope == 'test') {
def mainSet = sets.findByName('main')
try { mainSet?.java?.srcDirs?.each { srcDirs << it.canonicalPath } } catch (ignored) {}
}
srcDirs = srcDirs.unique()
def release = null
try {
def compileTask = project.tasks.findByName(ss.compileJavaTaskName)
release = compileTask?.options?.release?.getOrNull()
} catch (ignored) {}
if (release == null) {
try {
def java = project.extensions.findByName('java')
def lv = null
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
def target = java != null ? java.targetCompatibility : project.findProperty('targetCompatibility')
release = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
} catch (ignored) {}
}
println '@openidea-compile-cp\t' + JsonOutput.toJson([outDir: outDir, classpath: cp, srcDirs: srcDirs, release: release])
}
-1
View File
@@ -16,7 +16,6 @@ mod process;
#[cfg(test)]
mod process_numbers;
pub mod sbt;
pub mod surefire;
mod sync;
pub mod web;
mod xml;
-71
View File
@@ -517,59 +517,6 @@ pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
Some(PathBuf::from(repo.replace("${user.home}", &home)))
}
/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=`
/// first, then `<localRepository>` of the `-s` settings, then the user's default.
pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) {
return Some(PathBuf::from(repo));
}
let mut args = options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return local_repository_of(Path::new(path)).or_else(default_local_repo);
}
}
default_local_repo()
}
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
/// in the local repository, which a repository filled from a private mirror often lacks even when
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
/// downloaded, else a pinned one.
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
let (artifact, pinned) = match prefix {
"help" => ("maven-help-plugin", "3.5.1"),
"dependency" => ("maven-dependency-plugin", "3.8.1"),
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
};
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
}
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
/// from major version `min_major` up.
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
let dir = repo.join("org/apache/maven/plugins").join(artifact);
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
std::fs::read_dir(&dir)
.ok()?
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter_map(|v| parse(&v).map(|n| (n, v)))
.filter(|(n, v)| {
n.first().is_some_and(|&major| major >= min_major)
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
})
.max()
.map(|(_, v)| v)
}
impl Resolver {
fn new(local_repo: Option<PathBuf>, profiles: &[String]) -> Self {
Self::new_with_jdk(local_repo, profiles, None)
@@ -2610,24 +2557,6 @@ mod tests {
assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none());
}
#[test]
fn ide_goals_resolve_from_the_repository_the_run_uses() {
let tmp = tempfile::tempdir().unwrap();
let settings = tmp.path().join("settings.xml");
std::fs::write(&settings, "<settings><localRepository>/srv/m2</localRepository></settings>").unwrap();
let s = settings.to_string_lossy().into_owned();
let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2")));
assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2")));
let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]);
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
// No repository known: a pinned version, still by coordinates.
assert_eq!(
plugin_goal("dependency:build-classpath", None),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
);
}
#[test]
fn effective_pom_goals_come_from_the_local_repository_it_is_given() {
let tmp = tempfile::tempdir().unwrap();
-216
View File
@@ -1,216 +0,0 @@
//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of
//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM.
//!
//! Read from the effective POM the last sync cached (Maven merged parents, profiles and
//! `pluginManagement` there), else from the module's own `pom.xml` and its `<properties>`.
use crate::maven::{MavenModel, interpolate};
use crate::xml::{self, Element};
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
const SUREFIRE: &str = "maven-surefire-plugin";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SurefireConfig {
/// `<argLine>`, split into JVM options.
pub arg_line: Vec<String>,
/// `<systemPropertyVariables>` and the older `<systemProperties>`.
pub system_properties: BTreeMap<String, String>,
/// `<environmentVariables>`.
pub environment: BTreeMap<String, String>,
pub working_directory: Option<String>,
/// `<additionalClasspathElements>`.
pub additional_classpath: Vec<String>,
/// `<classpathDependencyExcludes>`: `groupId:artifactId`.
pub classpath_excludes: Vec<String>,
}
/// The Surefire configuration of the Maven module at `module` (absolute), if it is one.
pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option<SurefireConfig> {
let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?;
let pom = root.join(&project.pom);
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
// A cache written before the POM last changed would apply an old configuration.
let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| {
let name = path.file_name()?.to_str()?;
if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) {
return None;
}
let root = xml::parse(&xml::read_text(&path)?)?;
let projects: Vec<Element> = if root.name == "projects" {
root.children.into_iter().filter(|p| p.name == "project").collect()
} else {
vec![root]
};
projects.into_iter().find(|p| {
let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned()));
group.as_deref() == Some(project.group_id.as_str())
&& p.text_of("artifactId").as_deref() == Some(&project.artifact_id)
})
});
let (element, own) = match effective {
Some(e) => (e, false),
// ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them.
None => (xml::parse(&xml::read_text(&pom)?)?, true),
};
let mut props: HashMap<String, String> = element
.child("properties")
.map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
.unwrap_or_default();
let dir = module.to_string_lossy().into_owned();
for (key, value) in [
("basedir", dir.clone()),
("project.basedir", dir.clone()),
("project.build.directory", format!("{dir}/target")),
("project.groupId", project.group_id.clone()),
("project.artifactId", project.artifact_id.clone()),
("project.version", project.version.clone()),
] {
props.entry(key.into()).or_insert(value);
}
Some(read(&element, &props, own))
}
/// `<build><plugins>` Surefire's configuration, then its `default-test` execution's.
fn read(project: &Element, props: &HashMap<String, String>, own: bool) -> SurefireConfig {
let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE);
let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect();
if own && plugins.is_empty() {
plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect();
}
let mut configurations: Vec<&Element> = Vec::new();
for plugin in plugins {
configurations.extend(plugin.child("configuration"));
let default_test = plugin
.list("executions", "execution")
.into_iter()
.find(|e| e.text_of("id").as_deref() == Some("default-test"));
configurations.extend(default_test.and_then(|e| e.child("configuration")));
}
let value = |text: &str| resolve(text.trim(), props);
let mut config = SurefireConfig::default();
for c in configurations {
if let Some(arg_line) = c.child("argLine") {
config.arg_line = split_arg_line(&value(&arg_line.text));
}
for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) {
config.system_properties.insert(p.name.clone(), value(&p.text));
}
// `<systemProperties>`: `<property><name/><value/></property>` (deprecated, still honoured).
for p in c.list("systemProperties", "property") {
if let Some(name) = p.text_of("name") {
config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default()));
}
}
for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) {
config.environment.insert(e.name.clone(), value(&e.text));
}
if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) {
config.working_directory = Some(dir);
}
let texts = |list: &str, item: &str| -> Vec<String> {
c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect()
};
config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement"));
config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude"));
}
config
}
/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin
/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA).
fn resolve(text: &str, props: &HashMap<String, String>) -> String {
let mut out = interpolate(text, props);
for open in ["@{", "${"] {
while let Some(start) = out.find(open) {
let Some(len) = out[start..].find('}') else { break };
let key = &out[start + 2..start + len];
let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() };
out.replace_range(start..=start + len, &replacement);
}
}
out.trim().to_owned()
}
/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes.
fn split_arg_line(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current: Option<String> = None;
let mut quote: Option<char> = None;
for c in line.chars() {
match quote {
Some(q) if c == q => quote = None,
Some(_) => current.get_or_insert_default().push(c),
None if c == '"' || c == '\'' => {
quote = Some(c);
current.get_or_insert_default();
}
None if c.is_whitespace() => out.extend(current.take()),
None => current.get_or_insert_default().push(c),
}
}
out.extend(current);
out
}
#[cfg(test)]
mod tests {
use super::*;
const POM: &str = r#"<project>
<groupId>com.example</groupId><artifactId>orders</artifactId><version>1</version>
<properties><openideaFail>true</openideaFail><mockito>/m2/mockito.jar</mockito></properties>
<build><plugins><plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>@{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}</argLine>
<systemPropertyVariables><openidea.fail>${openideaFail}</openidea.fail><dir>${project.build.directory}</dir></systemPropertyVariables>
<systemProperties><property><name>old</name><value>style</value></property></systemProperties>
<environmentVariables><TZ>UTC</TZ></environmentVariables>
<additionalClasspathElements><additionalClasspathElement>${basedir}/extra</additionalClasspathElement></additionalClasspathElements>
<classpathDependencyExcludes><classpathDependencyExclude>org.slf4j:slf4j-simple</classpathDependencyExclude></classpathDependencyExcludes>
</configuration>
<executions><execution><id>default-test</id><configuration><workingDirectory>${basedir}/work</workingDirectory></configuration></execution></executions>
</plugin></plugins></build>
</project>"#;
fn model(dir: &Path) -> MavenModel {
crate::maven::load(dir)
}
#[test]
fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("pom.xml"), POM).unwrap();
let cache = root.join("cache");
std::fs::create_dir_all(&cache).unwrap();
let config = surefire_config(root, &cache, &model(root), root).unwrap();
let d = root.to_string_lossy();
assert_eq!(
config.arg_line,
["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="]
);
assert_eq!(config.system_properties["openidea.fail"], "true");
assert_eq!(config.system_properties["dir"], format!("{d}/target"));
assert_eq!(config.system_properties["old"], "style");
assert_eq!(config.environment["TZ"], "UTC");
assert_eq!(config.working_directory, Some(format!("{d}/work")));
assert_eq!(config.additional_classpath, [format!("{d}/extra")]);
assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]);
// A sync's effective POM wins: it has what the module inherits.
let effective = POM.replace("<argLine>", "<argLine>-Xmx1g ").replace("<TZ>UTC</TZ>", "<TZ>Asia/Tokyo</TZ>");
std::fs::write(cache.join("effective-pom-0.xml"), format!("<projects>{effective}</projects>")).unwrap();
let config = surefire_config(root, &cache, &model(root), root).unwrap();
assert_eq!(config.arg_line[0], "-Xmx1g");
assert_eq!(config.environment["TZ"], "Asia/Tokyo");
}
#[test]
fn splits_arg_line_like_surefire() {
assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]);
}
}
+36 -54
View File
@@ -86,37 +86,22 @@ const MAVEN_CACHE_VERSION: u32 = 1;
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
/// in the local repository is.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own
/// plugin version is, which may be cached instead.
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
const DEPENDENCY_TREE_JAR: &str =
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
/// still resolves the dependency tree instead of failing to download the help plugin.
/// `repo` is the local repository the build resolves from.
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
let tree = if pinned {
DEPENDENCY_TREE.to_owned()
} else {
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|| "dependency:tree".to_owned(),
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
)
};
let has_help =
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
let mut goals = Vec::with_capacity(4);
if has_help {
goals.push(maven::plugin_goal("help:effective-pom", repo));
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
}
goals.push(tree);
goals.push("-Dverbose".into());
goals
vec![
"help:effective-pom".into(),
format!("-Doutput={}", effective.to_string_lossy()),
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
"-Dverbose".into(),
]
}
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
@@ -382,8 +367,25 @@ pub fn sync_maven(
verbose: true,
..MavenCache::default()
};
// Where the build resolves its jars, and therefore where the plugin goals are read from.
let repo = maven::local_repository_for(&options.maven_options);
// Where the build resolves its jars, and therefore where the plugin goals are read
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
// then the user's default repository (which `plugin()` resolves itself).
let local_repo: Option<PathBuf> =
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|| {
let mut args = options.maven_options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return maven::local_repository_of(Path::new(path));
}
}
None
},
);
let mut errors: Vec<String> = Vec::new();
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
@@ -405,6 +407,7 @@ pub fn sync_maven(
if !options.profiles.is_empty() {
args.push(format!("-P{}", options.profiles.join(",")));
}
let repo = local_repo.clone().or_else(maven::default_local_repo);
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let command = options.maven_command.as_deref().unwrap_or(&top.command);
@@ -422,7 +425,7 @@ pub fn sync_maven(
}
})?;
let effective_projects = std::fs::read_to_string(&effective)
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
.unwrap_or_default();
let trees = maven::parse_dependency_tree(&out.text);
for (key, plugins, deps) in effective_projects {
@@ -950,32 +953,11 @@ mod tests {
#[test]
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
let tmp = tempfile::tempdir().unwrap();
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
let online = maven_sync_goals(Path::new("e.xml"), false, None);
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
// since the prefix needs group metadata a repository filled from a private mirror may lack;
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
let jar =
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
}
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
std::fs::write(&help_jar, "").unwrap();
// A version folder without its jar (only the POM was fetched) doesn't count.
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
assert_eq!(offline[2], "dependency:tree");
assert!(offline.contains(&"-Dverbose".to_owned()));
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
@@ -1047,7 +1029,7 @@ mod tests {
let cache = tmp.path().join("cache");
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
assert!(args.contains("maven-help-plugin:"), "args: {args}");
assert!(args.contains("help:effective-pom"), "args: {args}");
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
let maven = loaded.maven.unwrap();
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
@@ -1072,6 +1054,6 @@ mod tests {
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
// `-T1` pins the daemon serial so the dependency trees stay parseable.
assert!(args.contains("-T1"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
assert!(args.contains("help:effective-pom"), "args: {args}");
}
}
+7 -4
View File
@@ -137,16 +137,19 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
// POM's effective identity first; profiles and -D options can change its GAV.
let output = cache.join("artifact-project.txt");
let mut probe = top.options.clone();
let evaluate =
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
probe.extend([
"-f".into(),
root.join(&p.pom).to_string_lossy().into_owned(),
evaluate.clone(),
"help:evaluate".into(),
"-Dexpression=project.id".into(),
format!("-Doutput={}", output.display()),
]);
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
args.extend([
"-DskipTests".into(),
"package".into(),
"help:evaluate".into(),
format!("-Doutput={}", manifest.display()),
]);
return Ok(WebBuild {
command: top.command.clone(),
args,
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
version.workspace = true
edition.workspace = true
license.workspace = true
-85
View File
@@ -1,85 +0,0 @@
use std::io::{Cursor, Error, ErrorKind, Result};
/// A top-down BITMAPV5HEADER and BGRA pixels. The alpha mask lets native paste targets
/// retain transparency; the PNG flavor is also written for browsers and image editors.
pub(crate) fn png_to_dib(png: &[u8]) -> Result<Vec<u8>> {
let invalid = |error| Error::new(ErrorKind::InvalidData, error);
let mut decoder = png::Decoder::new(Cursor::new(png));
decoder.set_transformations(png::Transformations::normalize_to_color8());
let mut reader = decoder.read_info().map_err(invalid)?;
let rgba_size = (reader.info().width as usize)
.checked_mul(reader.info().height as usize)
.and_then(|pixels| pixels.checked_mul(4))
.filter(|size| *size <= 64 * 1024 * 1024)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
let size = reader
.output_buffer_size()
.filter(|size| *size <= 64 * 1024 * 1024)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
let mut pixels = vec![0; size];
let info = reader.next_frame(&mut pixels).map_err(invalid)?;
let mut dib = vec![0; 124];
dib[0..4].copy_from_slice(&124u32.to_le_bytes());
dib[4..8].copy_from_slice(&info.width.to_le_bytes());
dib[8..12].copy_from_slice(&(-(info.height as i32)).to_le_bytes());
dib[12..14].copy_from_slice(&1u16.to_le_bytes());
dib[14..16].copy_from_slice(&32u16.to_le_bytes());
dib[16..20].copy_from_slice(&3u32.to_le_bytes()); // BI_BITFIELDS
dib[20..24].copy_from_slice(&(rgba_size as u32).to_le_bytes());
for (at, value) in [(40, 0x00ff0000u32), (44, 0x0000ff00), (48, 0x000000ff), (52, 0xff000000), (56, 0x73524742)] {
dib[at..at + 4].copy_from_slice(&value.to_le_bytes());
}
dib[108..112].copy_from_slice(&4u32.to_le_bytes()); // LCS_GM_IMAGES
for pixel in pixels[..info.buffer_size()].chunks_exact(info.color_type.samples()) {
let rgba = match info.color_type {
png::ColorType::Rgba => [pixel[0], pixel[1], pixel[2], pixel[3]],
png::ColorType::Rgb => [pixel[0], pixel[1], pixel[2], 255],
png::ColorType::Grayscale => [pixel[0], pixel[0], pixel[0], 255],
png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
png::ColorType::Indexed => unreachable!("palette expansion requested"),
};
dib.extend_from_slice(&[rgba[2], rgba[1], rgba[0], rgba[3]]);
}
Ok(dib)
}
#[cfg(test)]
mod tests {
use super::*;
fn encode(color: png::ColorType, pixels: &[u8]) -> Vec<u8> {
let mut png = Vec::new();
{
let mut encoder = png::Encoder::new(&mut png, 1, 2);
encoder.set_color(color);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(pixels).unwrap();
}
png
}
#[test]
fn keeps_rgba_colors_alpha_and_top_down_row_order() {
let png = encode(png::ColorType::Rgba, &[255, 0, 0, 128, 0, 255, 0, 255]);
let dib = png_to_dib(&png).unwrap();
assert_eq!(i32::from_le_bytes(dib[8..12].try_into().unwrap()), -2);
assert_eq!(&dib[124..], &[0, 0, 255, 128, 0, 255, 0, 255]);
let round_trip = crate::dib_to_png(&dib).unwrap();
let mut reader = png::Decoder::new(Cursor::new(round_trip)).read_info().unwrap();
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
reader.next_frame(&mut pixels).unwrap();
assert_eq!(pixels, [255, 0, 0, 128, 0, 255, 0, 255]);
}
#[test]
fn supports_rgb_and_grayscale_without_assuming_an_alpha_channel() {
for (color, pixels, expected) in [
(png::ColorType::Rgb, vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 0, 255, 0, 255]),
(png::ColorType::Grayscale, vec![20, 200], vec![20, 20, 20, 255, 200, 200, 200, 255]),
(png::ColorType::GrayscaleAlpha, vec![20, 10, 200, 250], vec![20, 20, 20, 10, 200, 200, 200, 250]),
] {
assert_eq!(&png_to_dib(&encode(color, &pixels)).unwrap()[124..], expected);
}
assert!(png_to_dib(b"not a PNG").is_err());
}
}
+5 -259
View File
@@ -16,12 +16,8 @@
//! thread: AppKit and WebKit also access the general pasteboard there, and its
//! mutable type cache cannot be protected by a mutex in this crate.
//!
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
//! one URI per line), read and written through the GTK clipboard on X11 and
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
//! fails there.
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
//!
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
@@ -29,29 +25,6 @@
use std::path::PathBuf;
#[cfg(any(windows, test))]
mod image;
/// Writes a PNG as a native image, independently of WebView clipboard permissions.
/// Call on the main thread on macOS and Linux; `owner` is a window handle on Windows.
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
if png.get(..8) != Some(b"\x89PNG\r\n\x1a\n") || png.get(12..16) != Some(b"IHDR") || png.len() < 24 {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
}
let width = u32::from_be_bytes(png[16..20].try_into().unwrap()) as usize;
let height = u32::from_be_bytes(png[20..24].try_into().unwrap()) as usize;
if width == 0
|| height == 0
|| !width
.checked_mul(height)
.and_then(|pixels| pixels.checked_mul(4))
.is_some_and(|size| size <= 64 * 1024 * 1024)
{
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Clipboard image is too large"));
}
imp::set_png(png, owner)
}
/// Replaces every clipboard flavor with plain text. `owner` is the calling window
/// handle on Windows, ignored elsewhere. Call on the main thread on macOS and Linux.
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
@@ -83,7 +56,6 @@ const HEADER: usize = 20;
/// The absolute paths on the clipboard, empty when it holds no file list.
/// Read failures remain errors so callers can retain an internal copy.
/// Empty on Linux, where [`request_files`] reads it.
pub fn files() -> std::io::Result<Vec<PathBuf>> {
imp::files()
}
@@ -106,7 +78,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
/// 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", target_os = "linux", test))]
#[cfg(any(windows, target_os = "macos", test))]
fn names_text(paths: &[PathBuf], separator: &str) -> String {
paths
.iter()
@@ -117,82 +89,6 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
.join(separator)
}
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
/// hosts or schemes are skipped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
}
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
/// path; its percent-escapes are raw bytes, as GLib writes them.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_to_path(uri: &str) -> Option<PathBuf> {
use std::os::unix::ffi::OsStringExt;
let rest = uri.strip_prefix("file://")?;
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
let path = path.split(['?', '#']).next()?;
if !path.starts_with('/') {
return None;
}
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
let bytes = path.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let escaped =
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
match escaped {
Some(b) => {
out.push(b);
i += 3;
}
None => {
out.push(bytes[i]);
i += 1;
}
}
}
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
}
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
/// percent-escaped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn file_uri(path: &std::path::Path) -> String {
use std::fmt::Write;
use std::os::unix::ffi::OsStrExt;
let mut uri = String::from("file://");
for &b in path.as_os_str().as_bytes() {
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
uri.push(b as char);
} else {
let _ = write!(uri, "%{b:02X}");
}
}
uri
}
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
/// then GNOME's list, and calls `done` with the paths (empty without a list).
/// Call on the main thread; `done` runs there later.
#[cfg(target_os = "linux")]
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
fn paths_in(data: &gtk::SelectionData) -> Vec<PathBuf> {
// A failed request has a negative length and no data.
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
}
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
let paths = paths_in(data);
if !paths.is_empty() {
return done(paths);
}
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
});
}
/// `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> {
@@ -344,7 +240,6 @@ mod imp {
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
/// bitmap on the clipboard reads as one.
const CF_DIB: u32 = 8;
const CF_DIBV5: u32 = 17;
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
/// keeps transparency, so it is read first.
@@ -527,48 +422,6 @@ mod imp {
}
}
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
let dib = super::image::png_to_dib(png)?;
let format = png_format();
if format == 0 {
return Err(std::io::Error::last_os_error());
}
let formats = [(format, png), (CF_DIBV5, dib.as_slice())];
// SAFETY: allocations remain ours until SetClipboardData accepts them. Prepare both
// before replacing the clipboard; free only allocations the OS did not take.
unsafe {
let mut blocks: Vec<_> = formats.iter().map(|(_, bytes)| global_bytes(bytes)).collect();
if blocks.iter().any(|memory| memory.is_null()) || !open_for(owner as Handle) {
let error = std::io::Error::last_os_error();
for memory in blocks {
if !memory.is_null() {
GlobalFree(memory);
}
}
return Err(error);
}
let mut result = Ok(());
if EmptyClipboard() == 0 {
result = Err(std::io::Error::last_os_error());
} else {
for ((format, _), memory) in formats.iter().zip(&mut blocks) {
if SetClipboardData(*format, *memory).is_null() {
result = Err(std::io::Error::last_os_error());
break;
}
*memory = ptr::null_mut();
}
}
CloseClipboard();
for memory in blocks {
if !memory.is_null() {
GlobalFree(memory);
}
}
result
}
}
pub fn set_files(paths: &[PathBuf]) -> bool {
let bytes = encode(paths);
if bytes.len() <= HEADER {
@@ -636,7 +489,7 @@ mod imp {
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
};
use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString, NSURL};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
use std::path::PathBuf;
use super::names_text;
@@ -734,23 +587,6 @@ mod imp {
})
}
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
let data = NSData::with_bytes(png);
if NSBitmapImageRep::imageRepWithData(&data).is_none() {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
}
let board = NSPasteboard::generalPasteboard();
board.clearContents();
if board.setData_forType(Some(&data), unsafe { NSPasteboardTypePNG }) {
Ok(())
} else {
Err(std::io::Error::other("Cannot write clipboard image"))
}
})
}
pub fn set_files(paths: &[PathBuf]) -> bool {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
@@ -781,21 +617,6 @@ mod imp {
mod imp {
use std::path::PathBuf;
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
#[cfg(target_os = "linux")]
{
let image = gtk::gdk_pixbuf::Pixbuf::from_read(std::io::Cursor::new(png.to_vec()))
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).set_image(&image);
Ok(())
}
#[cfg(not(target_os = "linux"))]
{
let _ = png;
Err(std::io::Error::other("Clipboard images are unavailable on this platform"))
}
}
pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> {
#[cfg(target_os = "linux")]
{
@@ -809,25 +630,8 @@ mod imp {
}
}
#[cfg(target_os = "linux")]
pub const URI_LIST: &str = "text/uri-list";
#[cfg(target_os = "linux")]
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
pub fn has_files() -> bool {
#[cfg(target_os = "linux")]
{
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
targets.into_iter().any(|target| {
let name = target.name();
name == URI_LIST || name == GNOME_COPIED
})
})
}
#[cfg(not(target_os = "linux"))]
{
false
}
false
}
pub fn has_image() -> bool {
@@ -845,33 +649,6 @@ mod imp {
Ok(Vec::new())
}
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
/// list (Nautilus, Thunar) and their names as text, rendered on request.
#[cfg(target_os = "linux")]
pub fn set_files(paths: &[PathBuf]) -> bool {
use gtk::{TargetEntry, TargetFlags};
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
let gnome = format!("copy\n{}", uris.join("\n"));
let names = super::names_text(paths, "\n");
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
let targets = [
entry(URI_LIST, 0),
entry(GNOME_COPIED, 1),
entry("UTF8_STRING", 2),
entry("text/plain;charset=utf-8", 2),
entry("text/plain", 2),
];
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
1 => data.set(&data.target(), 8, gnome.as_bytes()),
_ => {
let _ = data.set_text(&names);
}
})
}
#[cfg(not(target_os = "linux"))]
pub fn set_files(_paths: &[PathBuf]) -> bool {
false
}
@@ -881,41 +658,10 @@ mod imp {
mod tests {
use super::*;
#[test]
fn invalid_or_oversized_images_are_rejected_before_accessing_the_clipboard() {
assert!(set_png(b"not a PNG", 0).is_err());
let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
header.extend_from_slice(&100_000u32.to_be_bytes());
header.extend_from_slice(&100_000u32.to_be_bytes());
assert!(set_png(&header, 0).is_err());
}
fn paths(list: &[&str]) -> Vec<PathBuf> {
list.iter().map(PathBuf::from).collect()
}
#[cfg(unix)]
#[test]
fn file_manager_uri_lists_become_paths() {
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
// Other hosts and schemes are not local files.
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
}
#[cfg(unix)]
#[test]
fn written_uris_read_back_as_the_same_paths() {
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
}
#[test]
fn a_written_list_reads_back_unchanged() {
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
+1 -5
View File
@@ -15,16 +15,12 @@ specta.workspace = true
specta-typescript.workspace = true
thiserror.workspace = true
tokio-util.workspace = true
portable-pty.workspace = true
[dev-dependencies]
sha2 = "0.10"
tempfile.workspace = true
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
dirs.workspace = true
tracing.workspace = true
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
-21
View File
@@ -1,21 +0,0 @@
Copyright (c) Microsoft Corporation. All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,39 +0,0 @@
# Bundled Windows console host
Unmodified files from Microsoft's MIT-licensed
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
puts full-screen applications' redraws in normal scrollback. A current console host
preserves those transitions, including while resizing and updating a running TUI.
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
Run and debugger builds work offline and do not depend on another installed IDE.
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
extracts them atomically to a versioned user cache and preloads the DLL's absolute
path before portable-pty initializes.
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
failure is logged and falls back to the system backend. Windows builds before
19041 also retain the system backend.
Source archive:
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
For each architecture, `conpty.dll` comes from
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
| File | SHA-256 |
| --------------------- | ------------------------------------------------------------------ |
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
console application and requires alternate-screen entry and exit to reach the
reader; a system ConPTY that consumes them fails this check.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-30
View File
@@ -201,7 +201,6 @@ pub struct FoldingSettings {
pub file_header: bool,
pub imports: bool,
pub doc_comments: bool,
pub go_short_blocks: bool,
}
impl Default for FoldingSettings {
@@ -212,7 +211,6 @@ impl Default for FoldingSettings {
file_header: true,
imports: true,
doc_comments: false,
go_short_blocks: true,
}
}
}
@@ -338,7 +336,6 @@ pub struct CodeEditingSettings {
/// Next / previous error goes to errors only (skips warnings).
pub next_error_errors_only: bool,
pub sticky_lines_max: u32,
pub sticky_lines_disabled_languages: Vec<String>,
}
impl Default for CodeEditingSettings {
@@ -351,7 +348,6 @@ impl Default for CodeEditingSettings {
quick_doc_delay: 500,
next_error_errors_only: true,
sticky_lines_max: 5,
sticky_lines_disabled_languages: Vec::new(),
}
}
}
@@ -364,8 +360,6 @@ pub struct InlayHintsSettings {
pub parameters: bool,
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
/// The Dart server's closing labels (`// Column` after a widget's closing bracket).
pub closing_labels: bool,
pub disabled_languages: Vec<String>,
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
pub code_vision: bool,
@@ -398,7 +392,6 @@ impl Default for InlayHintsSettings {
types: true,
parameters: true,
other: true,
closing_labels: true,
disabled_languages: Vec::new(),
code_vision: true,
code_vision_usages: true,
@@ -480,12 +473,6 @@ pub struct LanguageCodeStyle {
/// PHP: align `=` of consecutive assignment statements after formatting.
#[serde(skip_serializing_if = "Option::is_none")]
pub align_consecutive_assignments: Option<bool>,
/// SQL › Case › Keywords: `upper` | `lower` | `keep` (other languages ignore it).
#[serde(skip_serializing_if = "Option::is_none")]
pub keyword_case: Option<String>,
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -598,20 +585,3 @@ mod folding_tests {
}
}
}
#[cfg(test)]
mod sticky_lines_tests {
use super::CodeEditingSettings;
#[test]
fn sticky_lines_language_exclusions_round_trip_and_default_to_empty() {
let old: CodeEditingSettings = serde_json::from_value(serde_json::json!({"stickyLinesMax": 3})).unwrap();
assert_eq!(old.sticky_lines_max, 3);
assert!(old.sticky_lines_disabled_languages.is_empty());
let json = serde_json::json!(["markdown", "rust"]);
let saved: CodeEditingSettings =
serde_json::from_value(serde_json::json!({"stickyLinesDisabledLanguages": json})).unwrap();
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
}
}
-5
View File
@@ -41,11 +41,6 @@ pub enum ErrorData {
AmendConflict {
commit: String,
},
/// jdtls could not set a module up as a Java project: the errors on its build files and
/// the builds enclosing it (`path: message`, the path relative to the project), nearest first.
JavaBuildProblems {
problems: Vec<String>,
},
}
/// Git's reported result for each destination ref. A remote with several push URLs can
-18
View File
@@ -264,20 +264,6 @@ pub struct FlutterDevice {
pub emulator: bool,
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
pub unavailable: Option<String>,
/// The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`.
#[serde(default)]
#[specta(optional)]
pub emulator_id: Option<String>,
}
/// An Android emulator (AVD) or the iOS Simulator that `flutter emulators --launch` can start.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FlutterEmulator {
pub id: String,
pub name: String,
/// `android` or `ios`.
pub platform_type: Option<String>,
}
/// See [`FlutterDeviceList`].
@@ -303,10 +289,6 @@ pub enum FlutterDaemonStatus {
pub struct FlutterDeviceList {
pub status: FlutterDaemonStatus,
pub devices: Vec<FlutterDevice>,
/// The emulators that no listed device runs on.
#[serde(default)]
#[specta(optional)]
pub emulators: Vec<FlutterEmulator>,
}
/// See [`IdeEvent::Direnv`].
-1
View File
@@ -25,7 +25,6 @@ pub mod project_dir;
pub mod project_env;
pub mod project_roots;
pub mod proxy_settings;
pub mod pty;
pub mod real_path;
pub mod remote_settings;
pub mod settings;
+2 -19
View File
@@ -402,14 +402,12 @@ mod windows_job {
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
use windows_sys::Win32::Foundation::{ERROR_MORE_DATA, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, IsProcessInJob, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JobObjectBasicProcessIdList, JobObjectExtendedLimitInformation, QueryInformationJobObject,
SetInformationJobObject, TerminateJobObject,
};
use windows_sys::Win32::System::Threading::{
IO_COUNTERS, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE,
};
use windows_sys::Win32::System::Threading::{IO_COUNTERS, OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
/// A job object holding one launch's processes. The handle is kept open for the
/// launch's lifetime: `KILL_ON_JOB_CLOSE` ends anything still in the job when the
@@ -512,21 +510,6 @@ mod windows_job {
ok != 0
}
/// Whether the running process belongs to this specific launch's job.
pub fn contains_pid(&self, pid: u32) -> bool {
// SAFETY: a non-null result is a process handle owned by this call.
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
if handle.is_null() {
return false;
}
// SAFETY: the process handle was just opened above and the job handle is owned here.
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
let mut contained = 0;
// SAFETY: both handles remain valid and `contained` is a writable BOOL.
(unsafe { IsProcessInJob(handle.as_raw_handle(), self.0.as_raw_handle(), &mut contained) }) != 0
&& contained != 0
}
/// Terminates every process in the job. `false` when the call failed (the job
/// handle is invalid): callers then fall back to `taskkill /T /F`. Termination is
/// asynchronous; poll [`Job::is_running`] (bounded by [`TREE_EXIT_WAIT`]) until
-254
View File
@@ -1,254 +0,0 @@
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
#[cfg(windows)]
windows::initialize();
portable_pty::native_pty_system()
}
#[cfg(windows)]
mod windows {
use std::fs;
use std::io::{self, Write};
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use windows_sys::Win32::Foundation::FreeLibrary;
use windows_sys::Win32::System::LibraryLoader::{
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
};
const VERSION: &str = "1.25.260930003";
#[cfg(target_arch = "x86_64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x64",
include_bytes!("../resources/conpty/x64/conpty.dll"),
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
);
#[cfg(target_arch = "aarch64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"arm64",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
);
#[cfg(target_arch = "x86")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x86",
include_bytes!("../resources/conpty/x86/conpty.dll"),
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
);
pub(super) fn initialize() -> bool {
static BUNDLED: OnceLock<bool> = OnceLock::new();
*BUNDLED.get_or_init(|| {
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
return false;
}
match load() {
Ok(()) => true,
Err(error) => {
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
false
}
}
})
}
fn load() -> io::Result<()> {
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
fs::create_dir_all(&directory)?;
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
let library = directory.join("conpty.dll");
install(&library, RUNTIME.1)?;
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
// Windows reuses this module, without adding the project directory to DLL search.
// SAFETY: the path is terminated and the module is retained for the process lifetime.
let module = unsafe {
LoadLibraryExW(
wide.as_ptr(),
std::ptr::null_mut(),
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
)
};
if module.is_null() {
return Err(io::Error::last_os_error());
}
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
// SAFETY: `module` is loaded and each name is a terminated export name.
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
// SAFETY: no PTY uses this rejected module yet; release our load reference.
unsafe { FreeLibrary(module) };
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
}
}
// Keep this reference for the process lifetime, including between PTY sessions.
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
Ok(())
}
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
if fs::read(path).is_ok_and(|existing| existing == data) {
return Ok(());
}
static NEXT: AtomicU64 = AtomicU64::new(0);
let pending =
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let result = (|| {
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
file.write_all(data)?;
file.sync_all()?;
drop(file);
match fs::rename(&pending, path) {
Ok(()) => Ok(()),
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
Err(error) => Err(error),
}
})();
let _ = fs::remove_file(pending);
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn installs_atomically_and_repairs_incomplete_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("conpty.dll");
fs::write(&path, b"partial").unwrap();
std::thread::scope(|scope| {
for _ in 0..8 {
let path = &path;
scope.spawn(move || install(path, b"complete runtime").unwrap());
}
});
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
}
#[test]
fn loads_the_bundled_backend() {
assert!(initialize());
}
#[test]
fn conpty_output_child() {
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
return;
}
use windows_sys::Win32::System::Console::{
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
};
// SAFETY: the inherited console output handle and a local writable mode word.
unsafe {
let output = GetStdHandle(STD_OUTPUT_HANDLE);
let mut mode = 0;
assert_ne!(GetConsoleMode(output, &mut mode), 0);
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
}
std::io::stdout()
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
.unwrap();
std::io::stdout().flush().unwrap();
}
#[test]
fn conpty_preserves_alternate_screen_transitions() {
use std::io::Read;
use std::sync::mpsc;
use std::time::{Duration, Instant};
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
let mut reader = pair.master.try_clone_reader().unwrap();
let mut writer = pair.master.take_writer().unwrap();
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
let mut child = pair.slave.spawn_command(command).unwrap();
drop(pair.slave);
let (tx, rx) = mpsc::channel();
let reading = std::thread::spawn(move || {
let mut bytes = [0; 4096];
while let Ok(count) = reader.read(&mut bytes) {
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
break;
}
}
});
let deadline = Instant::now() + Duration::from_secs(10);
let mut output = Vec::new();
let mut cursor_replied = false;
while Instant::now() < deadline {
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
output.extend_from_slice(&bytes);
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
writer.write_all(b"\x1b[1;1R").unwrap();
cursor_replied = true;
}
if output.windows(7).any(|s| s == b"VT_DONE") {
break;
}
}
}
let _ = child.kill();
let _ = child.wait();
drop(writer);
drop(pair.master);
reading.join().unwrap();
let output = String::from_utf8_lossy(&output);
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
}
}
}
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
#[cfg(test)]
mod checksums {
use sha2::{Digest, Sha256};
const FILES: [(&str, &[u8], &str); 6] = [
(
"arm64/conpty.dll",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
),
(
"arm64/OpenConsole.exe",
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
),
(
"x64/conpty.dll",
include_bytes!("../resources/conpty/x64/conpty.dll"),
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
),
(
"x64/OpenConsole.exe",
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
),
(
"x86/conpty.dll",
include_bytes!("../resources/conpty/x86/conpty.dll"),
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
),
(
"x86/OpenConsole.exe",
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
),
];
#[test]
fn embedded_runtime_matches_the_pinned_package() {
for (name, bytes, expected) in FILES {
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(actual, expected, "{name}");
}
}
}
+1 -31
View File
@@ -145,7 +145,7 @@ impl Default for AgentSettings {
show_work_time: true,
show_usage_limits: true,
show_cost: false,
fold_turns: false,
fold_turns: true,
smooth_text: true,
fit_window_width: false,
thinking: ThinkingDisplay::Auto,
@@ -941,8 +941,6 @@ pub struct FileIconThemeOptions {
#[serde(default, rename_all = "camelCase")]
pub struct MainToolbarSettings {
pub left: Vec<String>,
/// Centred in the toolbar (between the other two groups when they leave too little room).
pub center: Vec<String>,
pub right: Vec<String>,
/// Widgets the user removed.
pub hidden: Vec<String>,
@@ -1218,7 +1216,6 @@ pub struct LanguagesSettings {
pub markdown: MarkdownSettings,
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
}
impl Default for LanguagesSettings {
@@ -1250,7 +1247,6 @@ impl Default for LanguagesSettings {
markdown: MarkdownSettings::default(),
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
}
}
}
@@ -1517,15 +1513,6 @@ pub struct ZigSettings {
pub zig: String,
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FlutterSettings {
/// Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
/// `PATH`. Empty = `PATH`.
pub sdk: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GoSettings {
@@ -1668,20 +1655,6 @@ pub struct MavenSettings {
/// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
/// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
pub update_snapshots: bool,
/// Who runs the JUnit 5 tests of the gutter's Run / Debug.
pub run_tests_using: MavenRunTestsUsing,
}
/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build
/// and run actions are delegated to Maven.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MavenRunTestsUsing {
/// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`).
#[default]
Ide,
/// Surefire (`mvn test -Dtest=…`).
Maven,
}
impl MavenSettings {
@@ -2124,10 +2097,8 @@ mod tests {
assert!(old.agents.show_cost);
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
assert!(!old.agents.fit_window_width);
assert!(!old.agents.fold_turns);
assert!(!Settings::default().agents.show_cost);
assert!(!Settings::default().agents.fit_window_width);
assert!(!Settings::default().agents.fold_turns);
let mut settings = Settings::default();
settings.agents.show_usage_limits = false;
settings.agents.fit_window_width = true;
@@ -2345,7 +2316,6 @@ mod maven_linkage_tests {
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
assert!(old.runner_jre.is_empty());
assert!(!old.delegate_build);
assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide);
assert!(MavenSettings::default().runner_jre.is_empty());
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old };
let encoded = serde_json::to_string(&settings).unwrap();
-28
View File
@@ -460,16 +460,6 @@ impl Default for ConsoleSettings {
}
}
/// Whether compiled classes are reloaded into running Java debug sessions after compilation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HotSwapPolicy {
#[default]
Ask,
Always,
Never,
}
/// Build, Execution, Deployment › Debugger (+ Data Views, Stepping, Python Debugger).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -497,8 +487,6 @@ pub struct DebuggerSettings {
pub debug_server_page: bool,
/// Flutter: saving a Dart file of a running debug session hot reloads the app.
pub flutter_hot_reload_on_save: bool,
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
}
@@ -520,7 +508,6 @@ impl Default for DebuggerSettings {
skip_library_code: true,
debug_server_page: false,
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
}
}
@@ -731,19 +718,4 @@ mod tests {
let off: GitSettings = serde_json::from_str(r#"{"syncBranchOperations":false}"#).unwrap();
assert!(!off.sync_branch_operations);
}
#[test]
fn debugger_hotswap_after_compile_defaults_to_ask_and_roundtrips() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert_eq!(missing.hot_swap_after_compile, HotSwapPolicy::Ask);
for (raw, expected) in
[("ask", HotSwapPolicy::Ask), ("always", HotSwapPolicy::Always), ("never", HotSwapPolicy::Never)]
{
let parsed: DebuggerSettings =
serde_json::from_str(&format!(r#"{{"hotSwapAfterCompile":"{raw}"}}"#)).unwrap();
assert_eq!(parsed.hot_swap_after_compile, expected);
let serialized = serde_json::to_value(&parsed).unwrap();
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
}
+1 -27
View File
@@ -1,6 +1,5 @@
//! Class-table snapshots of a debugged JVM, read over the HotSpot attach listener or, where
//! that is unavailable, counted by the debugger; the JVM's objects through the debugger; and
//! its thread dumps.
//! that is unavailable, counted by the debugger; and the JVM's objects through the debugger.
mod fallback;
mod heap;
@@ -11,7 +10,6 @@ mod snapshot;
pub(crate) mod test_support;
#[cfg(test)]
mod tests;
mod threads;
use crate::session::Session;
use crate::session::Suspension;
@@ -30,8 +28,6 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
pub(crate) use scan::watch_for_attached_jvm;
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, VirtualThreadsNote, run_jvm_thread_dump};
pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
pub const HISTOGRAM_TIMEOUT: Duration = Duration::from_secs(10);
@@ -194,25 +190,6 @@ fn histogram_pid(session: &Session) -> Result<Option<i32>, JvmMemoryUnavailable>
Ok(None)
}
/// Whether `session` is a JVM session attached to `run` that may hold `pid`: its JVM is `pid` or
/// not located yet.
pub(crate) fn attached_to_run(session: &Session, run: ide_core::RunId, pid: u32) -> bool {
let located = session.jvm_pid.load(Ordering::Acquire);
session.run == Some(run)
&& JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& (located <= 0 || located == i64::from(pid))
}
/// Whether `session` debugs the JVM `pid`: the program it launched or the JVM its attach found.
pub(crate) fn debugs_jvm(session: &Session, pid: u32) -> bool {
let jvm = if session.request == "launch" { launch_pid(session) } else { session.jvm_pid.load(Ordering::Acquire) };
JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& jvm > 0
&& jvm == i64::from(pid)
}
/// The JVM a launch session started: the one the IDE started for an app-launched (Kotlin)
/// session, else the program the adapter reported; 0 when neither is known.
pub(crate) fn launch_pid(session: &Session) -> i64 {
@@ -229,8 +206,6 @@ pub(crate) enum JvmTarget<'a> {
/// The JVM of an attach session. While `pid` is 0 it is looked up by `jdwp_port`, which is
/// `None` for a remote JVM.
Attached { pid: &'a AtomicI64, jdwp_port: Option<u16> },
/// A JVM the session debugs, found from outside it (in a run's process tree).
Known(i32),
/// Known without asking any JVM: no histogram can be taken, for this reason.
Unavailable(JvmMemoryUnavailable),
}
@@ -286,7 +261,6 @@ async fn histogram(
fn lookup(target: JvmTarget<'_>) -> Result<Lookup, JvmMemoryUnavailable> {
match target {
JvmTarget::Launched(pid) => Ok(Lookup::Tree(pid)),
JvmTarget::Known(pid) => Ok(Lookup::Known(pid)),
JvmTarget::Attached { pid, jdwp_port } => match i32::try_from(pid.load(Ordering::Acquire)) {
Ok(p) if p > 0 => Ok(Lookup::Known(p)),
_ => jdwp_port.map(Lookup::Scan).ok_or(JvmMemoryUnavailable::AttachedJvmNotFound),
+1 -24
View File
@@ -15,8 +15,7 @@ use std::time::Duration;
const VERSION_TIMEOUT: Duration = Duration::from_secs(2);
const FLAGS_TIMEOUT: Duration = Duration::from_secs(2);
/// The attach calls a snapshot, a heap dump or a thread dump makes, so tests can stand in for a
/// JVM.
/// The attach calls a snapshot or a heap dump makes, so tests can stand in for a JVM.
pub(crate) trait AttachProbe: Send + Sync {
fn has_listener(&self, pid: u32) -> bool;
/// Asks only the JVMs whose pid `may_query` accepts.
@@ -28,12 +27,6 @@ pub(crate) trait AttachProbe: Send + Sync {
fn heap_dump(&self, pid: u32, path: &Path, timeout: Duration) -> Result<HeapDumpReply, AttachError>;
/// `None` where the free space is not known.
fn free_bytes(&self, dir: &Path) -> Option<u64>;
fn thread_print(&self, pid: u32) -> Result<String, AttachError>;
/// Opens `pid`'s attach listener unless it runs; refuses a process not confirmed HotSpot.
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
/// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
fn is_application_jvm(&self, pid: u32) -> bool;
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError>;
}
pub(super) struct JdkProbe {
@@ -80,22 +73,6 @@ impl AttachProbe for JdkProbe {
fn free_bytes(&self, dir: &Path) -> Option<u64> {
ide_heap::free_bytes(dir)
}
fn thread_print(&self, pid: u32) -> Result<String, AttachError> {
ide_jvm_attach::thread_print(pid, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
ide_jvm_attach::ensure_listener(pid, ide_jvm_attach::LISTENER_START_TIMEOUT)
}
fn is_application_jvm(&self, pid: u32) -> bool {
ide_jvm_attach::is_application_jvm(pid)
}
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError> {
ide_jvm_attach::thread_dump_json(pid, dir, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
}
}
fn alive(pid: u32) -> bool {
-521
View File
@@ -3,7 +3,6 @@ use super::heap::*;
use super::scan::*;
use super::snapshot::*;
use super::test_support::{BareSession, FakeInspector, bare_session, bare_session_of};
use super::threads::*;
use super::*;
use ide_core::CancellationToken;
use ide_jvm_attach::{AttachError, HeapDumpReply, HistogramRow, JavaVersion};
@@ -40,15 +39,6 @@ struct FakeProbe {
free: Option<u64>,
/// Answering this command stops the program: runs the hook.
stops_on: Option<(&'static str, StopHook)>,
thread_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
/// Replies to `ensure_listener`, in order; `Ok` once empty.
listener_starts: parking_lot::Mutex<VecDeque<Result<(), AttachError>>>,
/// Pids `is_application_jvm` confirms.
application_jvms: Vec<u32>,
/// Pids `ensure_listener` was asked for.
ensured: parking_lot::Mutex<Vec<u32>>,
json_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
json_dirs: parking_lot::Mutex<Vec<PathBuf>>,
}
type StopHook = Box<dyn Fn() + Send + Sync>;
@@ -107,12 +97,6 @@ impl FakeProbe {
dump_bytes: 64,
free: None,
stops_on: None,
thread_dumps: parking_lot::Mutex::new(VecDeque::new()),
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
application_jvms: Vec::new(),
ensured: parking_lot::Mutex::new(Vec::new()),
json_dumps: parking_lot::Mutex::new(VecDeque::new()),
json_dirs: parking_lot::Mutex::new(Vec::new()),
}
}
@@ -183,26 +167,6 @@ impl AttachProbe for FakeProbe {
fn free_bytes(&self, _dir: &Path) -> Option<u64> {
self.free
}
fn thread_print(&self, _pid: u32) -> Result<String, AttachError> {
self.enter("thread_print");
std::thread::sleep(self.delay);
self.leave();
self.thread_dumps.lock().pop_front().expect("unexpected thread dump request")
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
self.record("ensure_listener");
self.ensured.lock().push(pid);
self.listener_starts.lock().pop_front().unwrap_or(Ok(()))
}
fn is_application_jvm(&self, pid: u32) -> bool {
self.application_jvms.contains(&pid)
}
fn thread_dump_json(&self, _pid: u32, dir: &Path) -> Result<String, AttachError> {
self.enter("thread_dump_json");
self.json_dirs.lock().push(dir.to_owned());
self.leave();
self.json_dumps.lock().pop_front().expect("unexpected JSON thread dump request")
}
}
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
@@ -1196,491 +1160,6 @@ async fn jdk11_is_refused_while_the_link_is_suspended_before_dap_stops() {
assert!(!dir.exists());
}
const THREADS: &str = "Full thread dump OpenJDK 64-Bit Server VM (21.0.5+11-LTS mixed mode, sharing):\n\n\"main\" #1 [259] prio=5 os_prio=31 cpu=31.20ms elapsed=1.70s tid=0x1 nid=259 runnable [0x2]\n java.lang.Thread.State: RUNNABLE\n";
fn dumping_threads(listener: u32, dumps: Vec<Result<String, AttachError>>) -> FakeProbe {
let fake = FakeProbe::new(listener, Vec::new());
*fake.thread_dumps.lock() = dumps.into();
fake
}
fn threads_unavailable(r: JvmThreadsResult) -> JvmThreadsUnavailable {
match r {
JvmThreadsResult::Unavailable { reason } => reason,
other => panic!("{other:?}"),
}
}
fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
JvmThreadsUnavailable::Jvm { reason }
}
/// The text dump alone: without a directory no JSON dump is asked for.
fn dump_text(fake: &FakeProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
dump_threads(fake, pid, suspended, None, &|| suspended)
}
fn ready_dump(r: JvmThreadsResult) -> JvmThreadDump {
match r {
JvmThreadsResult::Ready { dump } => dump,
other => panic!("{other:?}"),
}
}
const VIRTUAL_JSON: &str = r#"{"threadDump":{"threadContainers":[]}}"#;
fn json_dir() -> &'static Path {
Path::new("/data/cache/heap-snapshots/x")
}
#[test]
fn threads_below_21_ask_for_no_json() {
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_on_21_add_the_json_after_the_text() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!(dump.text, THREADS);
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
}
#[test]
fn a_failed_json_dump_keeps_the_text_dump() {
let cases = [
(AttachError::TooLarge, VirtualThreadsNote::TooLarge),
(AttachError::Timeout, VirtualThreadsNote::Failed),
(AttachError::Protocol("no thread dump file".into()), VirtualThreadsNote::Failed),
];
for (error, note) in cases {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Err(error)].into();
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!((dump.text.as_str(), dump.virtual_json, dump.virtual_note), (THREADS, None, Some(note)));
}
// No directory to write the file into.
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let dump = ready_dump(dump_text(&fake, 12, false));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::Failed)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn a_failed_text_dump_asks_for_no_json() {
let fake = dumping_threads(99, vec![Err(AttachError::Timeout)]);
let r = dump_threads(&fake, 12, false, Some(json_dir()), &|| false);
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::TimedOut));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_suspended_on_21_skip_the_json() {
let fake = dumping_threads(12, vec![Ok(THREADS.into())]);
let dump = ready_dump(dump_threads(&fake, 12, true, Some(json_dir()), &|| true));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// The program hits a breakpoint while the text dump is taken.
let stopped = Arc::new(AtomicBool::new(false));
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let stop = stopped.clone();
fake.stops_on = Some(("thread_print", Box::new(move || stop.store(true, Ordering::SeqCst))));
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| stopped.load(Ordering::SeqCst)));
assert!(!dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_running_start_the_listener() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let r = dump_text(&fake, 12, false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
assert!(!dump.taken_while_suspended);
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_suspended_without_listener_do_not_attach() {
let fake = dumping_threads(99, Vec::new());
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_while_suspended_on_11_are_refused() {
let mut fake = dumping_threads(12, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
assert_eq!(
threads_unavailable(dump_text(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
);
fake.version = None;
assert_eq!(
threads_unavailable(dump_text(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
);
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_while_suspended_on_17_use_the_running_listener() {
let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let r = dump_text(&fake, 12, true);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.java_version, "17.0.13");
assert_eq!(*fake.commands.lock(), ["thread_print"]);
}
#[test]
fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
// A shell (10) started a Gradle client (11) that started the program's JVM (12).
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![12];
let r = dump_tree(&fake, &[10, 11, 12], false, None, &|| false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 12);
assert_eq!(*fake.ensured.lock(), [12]);
// No JVM at all: the reported pid is asked, which tells an exited program from a non-JVM.
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
assert_eq!(
threads_unavailable(dump_tree(&fake, &[10, 11], false, None, &|| false)),
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
);
assert_eq!(*fake.ensured.lock(), [10]);
}
#[cfg(unix)]
#[tokio::test]
async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reported_pid() {
struct Child(std::process::Child);
impl Drop for Child {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let child = Child(std::process::Command::new("sleep").arg("30").spawn().unwrap());
let jvm = child.0.id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(0, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![jvm];
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(std::process::id() as i32);
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, jvm);
assert_eq!(*fake.ensured.lock(), [jvm]);
}
#[tokio::test]
async fn a_session_debugs_the_jvm_it_launched_or_found() {
let attach = bare_session("attach");
attach.session.jvm_pid.store(4242, Ordering::Release);
assert!(debugs_jvm(&attach.session, 4242));
assert!(!debugs_jvm(&attach.session, 4243));
let launch = bare_session("launch");
launch.session.debuggee_pid.store(77, Ordering::Release);
assert!(debugs_jvm(&launch.session, 77));
let python = bare_session_of("debugpy", "attach");
python.session.jvm_pid.store(4242, Ordering::Release);
assert!(!debugs_jvm(&python.session, 4242));
attach.session.terminated.store(true, Ordering::Release);
assert!(!debugs_jvm(&attach.session, 4242));
// An attach whose JVM is not found yet debugs no pid.
assert!(!debugs_jvm(&bare_session("attach").session, 0));
}
#[tokio::test]
async fn a_session_attached_to_a_run_may_hold_its_jvm_before_it_is_located() {
let run = ide_core::RunId(7);
let mut bare = bare_session("attach");
Arc::get_mut(&mut bare.session).unwrap().run = Some(run);
// Gradle bootRun Debug opens no attach listener, so the attach-time scan finds no pid.
assert!(attached_to_run(&bare.session, run, 555));
assert!(!attached_to_run(&bare.session, ide_core::RunId(8), 555));
bare.session.jvm_pid.store(4242, Ordering::Release);
assert!(attached_to_run(&bare.session, run, 4242));
assert!(!attached_to_run(&bare.session, run, 555), "another JVM of the same run");
bare.session.terminated.store(true, Ordering::Release);
assert!(!attached_to_run(&bare.session, run, 4242));
let mut python = bare_session_of("debugpy", "attach");
Arc::get_mut(&mut python.session).unwrap().run = Some(run);
assert!(!attached_to_run(&python.session, run, 555));
assert!(!attached_to_run(&bare_session("attach").session, run, 555), "not linked to a run");
}
#[tokio::test]
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
// Stopped at a breakpoint, no listener: refused with the resume reason, no listener start.
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
// Running: the run's JVM is dumped under the session's turn.
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
assert_eq!(*fake.ensured.lock(), [555]);
}
/// A run's JVM held at a breakpoint by a debugger attached to it (Debug of `spring-boot:run`).
fn stopped_attach(pid: u32) -> BareSession {
let bare = bare_session("attach");
bare.session.jvm_pid.store(i64::from(pid), Ordering::Release);
bare.session.suspended.stopped(None, true);
bare
}
#[tokio::test]
async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
let bare = stopped_attach(4242);
let mut fake = dumping_threads(4242, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
assert!(fake.commands.lock().is_empty());
// No listener: none is started, the JVM's Signal Dispatcher being stopped.
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.pid, 4242);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_asks_for_no_json_while_the_session_holds_it() {
let bare = stopped_attach(4242);
let fake = Arc::new(dumping_threads(4242, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
assert!(dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// Running at first, the program hits a breakpoint while the text dump is taken.
let bare = bare_session("attach");
bare.session.jvm_pid.store(4242, Ordering::Release);
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
let session = bare.session.clone();
fake.stops_on = Some(("thread_print", Box::new(move || session.suspended.stopped(None, true))));
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
assert!(!dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[tokio::test]
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located_asks_for_no_json_while_stopped() {
// Gradle bootRun Debug after an earlier run dump opened the listener: the session's pid is still 0.
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
assert_eq!((dump.pid, dump.taken_while_suspended), (555, true));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// Running, the same session gets the JSON dump too.
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let bare = bare_session("attach");
bare.session.jvm_pid.store(4242, Ordering::Release);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let histogram = bare.session.jvm_memory.lock().await;
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242, None));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind the session's histogram.
bare.session.suspended.stopped(None, true);
drop(histogram);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_of_an_exited_program() {
let mut fake = dumping_threads(99, Vec::new());
fake.alive = false;
*fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
}
#[test]
fn thread_dump_errors_map_to_reasons() {
let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
let mut fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
fake.alive = false;
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_text(&fake, 12, false)) else {
panic!("not a failure")
};
assert!(message.contains("no"), "{message}");
}
#[test]
fn thread_results_serialize_with_camel_case_tags() {
let r = JvmThreadsResult::Unavailable { reason: threads_jvm(JvmMemoryUnavailable::ListenerNotRunning) };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "jvm", "reason": {"kind": "listenerNotRunning"}}})
);
let r = JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::ListenerDidNotStart };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "listenerDidNotStart"}})
);
let dump = JvmThreadDump {
text: "t".into(),
pid: 7,
java_version: String::new(),
taken_while_suspended: true,
elapsed_ms: 3,
virtual_json: None,
virtual_note: Some(VirtualThreadsNote::WhileSuspended),
};
assert_eq!(
serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
serde_json::json!({
"status": "ready",
"dump": {
"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3,
"virtualJson": null, "virtualNote": "whileSuspended"
}
})
);
assert_eq!(serde_json::to_value(VirtualThreadsNote::TooLarge).unwrap(), serde_json::json!("tooLarge"));
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn threads_take_the_memory_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
*fake.histograms.lock() = vec![Ok(HISTOGRAM.into())].into();
fake.delay = Duration::from_millis(100);
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = Suspension::default();
let (classes, threads) = tokio::join!(
snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32), None)
);
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
let threads = threads.unwrap();
assert!(matches!(threads, JvmThreadsResult::Ready { .. }), "{threads:?}");
assert_eq!(fake.max_in_flight.load(Ordering::SeqCst), 1);
assert_eq!(*fake.commands.lock(), ["histogram", "ensure_listener", "thread_print"]);
}
#[cfg(unix)]
#[tokio::test]
async fn queued_thread_dump_reads_suspension_under_the_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let suspended = Arc::new(Suspension::default());
let fake = Arc::new(dumping_threads(0, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = state.lock().await;
let stopped = suspended.clone();
let target = JvmTarget::Launched(pid as i32);
let mut queued = Box::pin(thread_dump(&state, move || stopped.get(), |_| probe, target, Some(json_dir().into())));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind a class-table request.
suspended.stopped(None, true);
drop(running);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[tokio::test]
async fn attached_thread_dump_keeps_the_scanned_jvm() {
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let jvm_pid = AtomicI64::new(0);
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.jdwp = Some((5005, 4242));
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 4242);
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
}
#[cfg(unix)]
#[tokio::test]
async fn session_thread_dump_writes_the_json_into_the_given_directory() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(pid as i32);
let r = thread_dump(&state, || false, |_| probe, target, Some(json_dir().into())).await.unwrap();
assert_eq!(ready_dump(r).virtual_json.as_deref(), Some(VIRTUAL_JSON));
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
}
#[tokio::test]
async fn capability_matches_memory() {
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
-260
View File
@@ -1,260 +0,0 @@
//! A thread dump (`Thread.print -l`) of a debugged or running JVM.
use super::heap::capture_suspended;
use super::snapshot::{AttachProbe, JdkProbe, attach_failure, gone, pick_jvm_pid};
use super::{
JvmMemoryState, JvmMemoryUnavailable, JvmTarget, histogram_pid, keep_found, lookup, resolve_jvm,
safe_while_suspended, session_target, until_located,
};
use crate::session::Session;
use ide_core::{IdeError, IdeResult};
use ide_jvm_attach::{AttachError, JavaVersion};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The first release whose virtual threads are final and that writes the JSON dump.
const VIRTUAL_THREADS_MAJOR: u32 = 21;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JvmThreadDump {
pub text: String,
pub pid: u32,
/// Empty when unknown.
pub java_version: String,
pub taken_while_suspended: bool,
/// Wall time of the `Thread.print` request.
pub elapsed_ms: u32,
/// `Thread.dump_to_file -format=json`, which also lists virtual threads; JDK 21+ only.
pub virtual_json: Option<String>,
/// Why `virtual_json` is missing from a JDK 21+ dump; none below 21.
pub virtual_note: Option<VirtualThreadsNote>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum VirtualThreadsNote {
/// A debugger holds the VM, which would hang the JSON request until it resumes.
WhileSuspended,
/// Over the attach reply limit (64 MiB).
TooLarge,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsUnavailable {
/// The reason a class table could not be read applies to the dump too.
Jvm {
reason: JvmMemoryUnavailable,
},
/// The JVM ignored the request to open its attach listener (`-XX:+DisableAttachMechanism`).
ListenerDidNotStart,
/// A run on a remote host, whose JVM this machine cannot attach to.
RemoteRun,
Failed {
message: String,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "status", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsResult {
Ready { dump: JvmThreadDump },
Unavailable { reason: JvmThreadsUnavailable },
}
/// A thread dump of `pid`, a JVM no debugger holds; `json_dir` is an absolute, owner-only
/// directory the JVM may write the JSON dump into. Blocking for up to the listener start and
/// dump timeouts, so callers run it in `spawn_blocking`.
pub fn run_jvm_thread_dump(pid: u32, json_dir: Option<&Path>) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false, json_dir, &|| false)
}
pub(crate) async fn session_thread_dump(
session: Arc<Session>,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
until_located(&session).await;
let launched = histogram_pid(&session);
// Detached, so a caller that gives up cannot release the lock while the JVM is still
// answering and let a class-table request run next to it.
tokio::spawn(async move {
let target = session_target(&session, launched);
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
let stopped = session.clone();
let suspended = move || capture_suspended(&stopped);
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
/// is: a JVM the debugger holds suspended is never asked to open a listener.
pub(crate) async fn debugged_run_thread_dump(
session: Arc<Session>,
pid: u32,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
// Detached for the same reason as `session_thread_dump`.
tokio::spawn(async move {
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
known_pid_dump(&session, probe, pid, json_dir).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
/// The session's suspension decides the JSON dump too: it is read again before that request.
pub(super) async fn known_pid_dump(
session: &Arc<Session>,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
pid: u32,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
let target =
i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
let stopped = session.clone();
let suspended = move || capture_suspended(&stopped);
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
}
/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
/// session; `suspended_now` and then `probe` are read once it is held, and `suspended_now` again
/// before the JSON dump.
pub(super) async fn thread_dump(
state: &tokio::sync::Mutex<JvmMemoryState>,
suspended_now: impl Fn() -> bool + Send + Sync + 'static,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
target: JvmTarget<'_>,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
let _turn = state.lock().await;
let suspended = suspended_now();
let lookup = match lookup(target) {
Ok(lookup) => lookup,
Err(reason) => return Ok(jvm(reason)),
};
let probe = probe(suspended);
let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended, json_dir.as_deref(), &suspended_now)),
Err(reason) => (None, jvm(reason)),
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?;
keep_found(target, found);
Ok(outcome)
}
/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
/// first with a listener, else the first application JVM (the reported pid may be a shell or a
/// Gradle client), else the reported pid.
pub(super) fn dump_tree(
probe: &dyn AttachProbe,
tree: &[i32],
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> JvmThreadsResult {
let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
.or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
.or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
match jvm_pid {
Some(pid) => dump_threads(probe, pid, suspended, json_dir, suspended_now),
None => jvm(JvmMemoryUnavailable::NoJvmProcess),
}
}
/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
/// The JSON dump follows a text dump that succeeded; its failure only sets the note.
pub(crate) fn dump_threads(
probe: &dyn AttachProbe,
pid: u32,
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> JvmThreadsResult {
if suspended {
if !probe.has_listener(pid) {
return jvm(gone(probe, pid));
}
} else if let Err(e) = probe.ensure_listener(pid) {
return failure(probe, pid, e);
}
let version = probe.version(pid);
if suspended && !safe_while_suspended(version.as_ref()) {
return jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: version.map_or(0, |v| v.major) });
}
let started = std::time::Instant::now();
let text = match probe.thread_print(pid) {
Ok(text) => text,
Err(e) => return failure(probe, pid, e),
};
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
let (virtual_json, virtual_note) =
virtual_threads(probe, pid, version.as_ref(), suspended, json_dir, suspended_now);
JvmThreadsResult::Ready {
dump: JvmThreadDump {
text,
pid,
java_version: version.map(|v| v.text).unwrap_or_default(),
taken_while_suspended: suspended,
elapsed_ms,
virtual_json,
virtual_note,
},
}
}
/// The program may have stopped during the text dump, so the suspension is read again.
fn virtual_threads(
probe: &dyn AttachProbe,
pid: u32,
version: Option<&JavaVersion>,
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> (Option<String>, Option<VirtualThreadsNote>) {
if version.is_none_or(|v| v.major < VIRTUAL_THREADS_MAJOR) {
return (None, None);
}
if suspended || suspended_now() {
return (None, Some(VirtualThreadsNote::WhileSuspended));
}
let Some(dir) = json_dir else {
return (None, Some(VirtualThreadsNote::Failed));
};
match probe.thread_dump_json(pid, dir) {
Ok(json) => (Some(json), None),
Err(AttachError::TooLarge) => (None, Some(VirtualThreadsNote::TooLarge)),
Err(e) => {
tracing::warn!("JSON thread dump of JVM {pid}: {e}");
(None, Some(VirtualThreadsNote::Failed))
}
}
}
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
let reason = match error {
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
// A program that exited leaves no perf-data file, so it fails the HotSpot check too.
AttachError::NotAJvm if probe.alive(pid) => {
JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::NoJvmProcess }
}
AttachError::NotAJvm => JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ProgramExited },
e => match attach_failure(probe, pid, e, "thread dump") {
Ok(reason) => JvmThreadsUnavailable::Jvm { reason },
Err(e) => JvmThreadsUnavailable::Failed { message: e.message },
},
};
JvmThreadsResult::Unavailable { reason }
}
fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult {
JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::Jvm { reason } }
}
+16 -62
View File
@@ -27,7 +27,7 @@ use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
use futures::future::join_all;
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
@@ -460,15 +460,6 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
serde_json::from_value(run).ok()
}
/// Builds the `launch`/`attach` arguments: our fields first, then `extra_json` merged on top.
pub fn launch_arguments(config: &LaunchConfig) -> IdeResult<Value> {
// VS Code puts `type`, `request` and `name` in the arguments; js-debug picks launch
@@ -897,21 +888,6 @@ impl DebugManager {
if config.adapter == "rdbg" {
rdbg_command_line(&mut spec, &config, &cwd)?;
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`. Before
// `custom_command`, which picks the Flutter SDK setting's `flutter`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
@@ -927,6 +903,20 @@ impl DebugManager {
spec.command = python;
}
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
let id = DebugSessionId::next();
let debug_server = take_debug_server(&mut arguments)?;
if let Some(server) = &debug_server {
@@ -1057,7 +1047,7 @@ impl DebugManager {
adapter_name: String,
parent: Option<DebugSessionId>,
request: String,
mut arguments: Value,
arguments: Value,
spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
@@ -1077,7 +1067,6 @@ impl DebugManager {
.flatten();
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
session.exception_classes = exception_classes;
session.run = take_run_link(&mut arguments);
let session = Arc::new(session);
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
let _ = session.launch_type.set(launch_type.to_owned());
@@ -1978,41 +1967,6 @@ impl DebugManager {
jvm_memory::session_heap_dump(session, dir, cancel).await
}
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn, and on JDK
/// 21+ the JSON dump written into `json_dir`. A JVM the debugger holds suspended is asked
/// only when it is 17 or later and its listener already runs: otherwise the request would hang
/// until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId, json_dir: Option<PathBuf>) -> IdeResult<JvmThreadsResult> {
let session = self.session(s)?;
jvm_memory::session_thread_dump(session, json_dir).await
}
/// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
/// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
/// it, under that session's turn and suspension, so a suspended JVM is not asked for the JSON
/// dump either. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(
&self,
run: RunId,
pid: u32,
json_dir: Option<PathBuf>,
) -> Option<IdeResult<JvmThreadsResult>> {
let session = self.jvm_session_of(run, pid)?;
Some(jvm_memory::debugged_run_thread_dump(session, pid, json_dir).await)
}
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
/// found no listener) still holds `pid`.
fn jvm_session_of(&self, run: RunId, pid: u32) -> Option<Arc<Session>> {
let sessions = self.live_sessions();
let linked = || sessions.iter().filter(|s| jvm_memory::attached_to_run(s, run, pid));
linked()
.find(|s| jvm_memory::debugs_jvm(s, pid))
.or_else(|| linked().next())
.or_else(|| sessions.iter().find(|s| jvm_memory::debugs_jvm(s, pid)))
.cloned()
}
/// Gives the session the backend for [`Self::jvm_memory_instances`] and the debugger's class
/// counts; the UI is told to reload the session's capabilities.
pub fn set_jvm_inspector(
+2 -7
View File
@@ -8,7 +8,7 @@ use crate::{Breakpoint, BreakpointState, DataBreakpoint, DebugManager, FunctionB
use ide_core::event::DebugEvent;
#[cfg(unix)]
use ide_core::process::process_tree;
use ide_core::{DebugSessionId, IdeEvent, RunId, TaskId};
use ide_core::{DebugSessionId, IdeEvent, TaskId};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeSet, HashMap};
@@ -117,9 +117,6 @@ pub(crate) struct Session {
pub jvm_located: watch::Sender<bool>,
pub kotlin_mirror: Mutex<Option<crate::kotlin::SourceMirror>>,
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
/// The run whose JVM this session attached to (Debug of a build tool's run, Attach to
/// Process on a run): that run's thread dumps go through this session.
pub run: Option<RunId>,
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
/// Given at start: the class breakpoints must be armed before `configurationDone`.
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
@@ -336,7 +333,6 @@ impl Session {
jvm_located: watch::channel(false).0,
kotlin_mirror: Mutex::new(None),
jvm_memory: tokio::sync::Mutex::default(),
run: None,
stream_tracer: parking_lot::Mutex::new(None),
exception_classes: None,
exception_turn: tokio::sync::Mutex::default(),
@@ -1061,8 +1057,7 @@ fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: A
/// starts a launcher that gives the program its terminal, and the program reads input only from
/// a terminal), forwards its output to the console, and keeps the terminal for typed input.
pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, String> {
use ide_core::pty::native_pty_system;
use portable_pty::{CommandBuilder, PtySize};
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
let argv: Vec<String> = args
.get("args")
.and_then(Value::as_array)
-49
View File
@@ -3074,55 +3074,6 @@ async fn local_attach_finds_its_jvm_before_the_debugger_connects() {
assert_eq!(session.jvm_pid.load(Ordering::Acquire), 4242);
}
/// Gradle bootRun Debug: the JVM has no attach listener, so the session never learns its pid. The
/// run's dump still goes through the session and, the program being stopped, signals nothing.
#[cfg(unix)]
#[tokio::test]
async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
let h = harness(Script::default());
let project = tempfile::tempdir().unwrap();
let mut cfg = remote_attach("java-debug", project.path());
let mut extra: Value = serde_json::from_str(cfg.extra_json.as_deref().unwrap()).unwrap();
extra[RUN_LINK] = json!(7);
cfg.extra_json = Some(extra.to_string());
let id = h.start(cfg).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert!(h.request("attach")["arguments"].get(RUN_LINK).is_none(), "IDE-side only");
let session = h.manager.session(id).unwrap();
assert_eq!((session.run, session.jvm_pid.load(Ordering::Acquire)), (Some(RunId(7)), 0));
// `sleep` stands in for the JVM: a SIGQUIT would end it.
let mut jvm = std::process::Command::new("sleep").arg("30").spawn().unwrap();
let pid = jvm.id();
assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(8), pid).is_none());
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid, None).await.unwrap().unwrap();
let alive = jvm.try_wait().unwrap().is_none();
let _ = jvm.kill();
let _ = jvm.wait();
assert_eq!(
dump,
JvmThreadsResult::Unavailable {
reason: JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ListenerNotRunning }
}
);
assert!(alive, "the stopped JVM was signalled");
}
/// A run's Dump Threads reaches the session attached to the run's JVM, not the plain run path.
#[cfg(unix)]
#[tokio::test]
async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
let h = harness(Script::default());
h.manager.set_jvm_finder(Arc::new(|port, _| (port == 5005).then_some(4242)));
let mut cfg = java_config("attach");
cfg.extra_json = Some(json!({"hostName": "127.0.0.1", "port": 5005}).to_string());
let id = h.start(cfg).await.unwrap();
assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243, None).await.is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn local_attach_remembers_its_jdwp_port() {
+1 -14
View File
@@ -17,7 +17,7 @@ specta.workspace = true
toml.workspace = true
toml_edit.workspace = true
blake3.workspace = true
tokio = { workspace = true, features = ["net"] }
tokio.workspace = true
tracing.workspace = true
parking_lot.workspace = true
notify.workspace = true
@@ -38,19 +38,6 @@ rsa = { version = "0.10.0-rc.18", features = ["sha2", "pkcs5"] }
zeroize = "1"
open = "5"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Threading",
"Win32_System_JobObjects",
] }
[dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net"] }
ide-ssh = { workspace = true, features = ["testing"] }
-1
View File
@@ -316,7 +316,6 @@ impl ClickhousePool {
has_more,
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
execution_ms,
truncated: Vec::new(),
})
};
let result = tokio::select! {
+55 -349
View File
@@ -12,7 +12,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use sqlx::{
Column, ColumnIndex, ConnectOptions, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
Column, ColumnIndex, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
mysql::{MySqlConnectOptions, MySqlConnection, MySqlSslMode},
pool::PoolConnection,
postgres::{PgConnectOptions, PgConnection, PgSslMode},
@@ -48,65 +48,6 @@ pub struct QueryResult {
pub elapsed_ms: f64,
/// Until the server's first answer; the rest of `elapsed_ms` is fetching.
pub execution_ms: f64,
/// Cells of `rows` cut short by [`QueryResult::cap_cells`], in row order.
pub truncated: Vec<TruncatedCell>,
}
/// A cell of a [`QueryResult`] whose text was cut to a prefix.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTruncatedCell")]
pub struct TruncatedCell {
pub row: u32,
pub column: u32,
/// Length of the whole value in UTF-16 code units (what a JavaScript string counts).
pub length: u32,
/// FNV-1a (32 bits) of the whole value's UTF-16 code units, each taken as one 16-bit step,
/// so a client that reads the value again can tell whether it is the one that was cut.
pub hash: u32,
}
/// FNV-1a over UTF-16 code units, one step per unit (the same on the client: see `cutCells.ts`).
fn fnv1a_utf16(text: &str) -> u32 {
let mut hash: u32 = 0x811c_9dc5;
let mut pair = [0u16; 2];
for ch in text.chars() {
for unit in ch.encode_utf16(&mut pair) {
hash = (hash ^ u32::from(*unit)).wrapping_mul(0x0100_0193);
}
}
hash
}
impl QueryResult {
/// Cuts every cell longer than `limit` UTF-16 code units to its first `limit` (never inside a
/// surrogate pair) and lists it in `truncated`, so a page's size no longer depends on how
/// wide its values are. The full value is read again, one row at a time, when it is needed.
pub fn cap_cells(&mut self, limit: usize) {
for (r, row) in self.rows.iter_mut().enumerate() {
for (c, cell) in row.iter_mut().enumerate() {
let Some(text) = cell else { continue };
// A UTF-16 length never exceeds the UTF-8 one.
if text.len() <= limit {
continue;
}
let mut units = 0;
let mut cut = text.len();
for (at, ch) in text.char_indices() {
if units + ch.len_utf16() > limit && cut == text.len() {
cut = at;
}
units += ch.len_utf16();
}
if units <= limit {
continue;
}
let hash = fnv1a_utf16(text);
text.truncate(cut);
self.truncated.push(TruncatedCell { row: r as u32, column: c as u32, length: units as u32, hash });
}
}
}
}
/// Session context belongs to the physical connection, including across pool checkouts.
@@ -135,7 +76,7 @@ impl Context {
}
macro_rules! sqlx_pool {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr) => {
pub struct $manager {
options: $options,
init: Arc<Vec<String>>,
@@ -170,7 +111,7 @@ macro_rules! sqlx_pool {
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
tokio::time::timeout(self.timeout, async {
let mut conn = self.options.connect().await?;
let mut conn = <$connection>::connect_with(&self.options).await?;
let context_sql = |value: Option<String>| {
value.map(|v| {
if $driver == DbDriver::Postgres {
@@ -183,9 +124,6 @@ macro_rules! sqlx_pool {
for sql in self.init.iter() {
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
}
$(if !self.init.is_empty() {
self.options.$after_init(&mut conn).await?;
})?
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
let context = Context::new(context_sql(row.try_get(0)?));
Ok($handle {
@@ -212,88 +150,7 @@ macro_rules! sqlx_pool {
};
}
#[derive(Clone)]
struct PostgresOptions {
connection: PgConnectOptions,
read_only: bool,
}
const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
For PgBouncer, check track_extra_parameters.";
impl PostgresOptions {
async fn connect(&self) -> Result<PgConnection, sqlx::Error> {
let mut conn = self.connection.connect().await?;
// A pooler can silently discard startup options. Check before giving the startup script a connection.
self.verify_read_only(&mut conn).await?;
Ok(conn)
}
async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL did not enable the requested default_transaction_read_only setting. \
Check the Advanced properties and startup script. {PG_READ_ONLY_HINT}"
)
.into(),
));
}
Ok(())
}
async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
self.verify_read_only(conn).await?;
if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
"The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
));
}
Ok(())
}
}
async fn pg_setting_on(conn: &mut PgConnection, show: &'static str) -> Result<bool, sqlx::Error> {
let row = sqlx::raw_sql(show).fetch_one(conn).await?;
Ok(row.try_get::<&str, _>(0)? == "on")
}
fn postgres_read_only_hint(read_only: bool, code: Option<&str>, message: &str) -> Option<&'static str> {
match (read_only, code, message) {
(
true,
Some("08P01"),
"unsupported startup parameter in options: default_transaction_read_only"
| "unsupported startup parameter: default_transaction_read_only",
) => Some(PG_READ_ONLY_HINT),
(true, Some("08P01"), "unsupported startup parameter: options") => Some(
"This endpoint rejects PostgreSQL startup options. Use an endpoint that supports and tracks \
default_transaction_read_only for each client.",
),
_ => None,
}
}
fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
let hint =
error.as_database_error().and_then(|db| postgres_read_only_hint(read_only, db.code().as_deref(), db.message()));
let mut error = db_err(error);
if let Some(hint) = hint {
error.message.push_str(". ");
error.message.push_str(hint);
}
error
}
sqlx_pool!(
PgManager,
PgHandle,
PostgresOptions,
PgConnection,
DbDriver::Postgres,
"SHOW search_path",
verify_startup_script
);
sqlx_pool!(PgManager, PgHandle, PgConnectOptions, PgConnection, DbDriver::Postgres, "SHOW search_path");
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
pub struct ServerPool<M: ManageConnection> {
@@ -629,86 +486,6 @@ fn result_columns<R: Row>(row: &R) -> Vec<ResultColumn> {
.collect()
}
/// How far a statement's stream has been read: the columns seen so far, and the row that
/// showed more were coming, which the next read starts with.
pub(crate) struct Reader<R> {
columns: Vec<ResultColumn>,
carry: Option<R>,
}
impl<R> Default for Reader<R> {
fn default() -> Self {
Self { columns: Vec::new(), carry: None }
}
}
#[cfg(test)]
thread_local! {
/// Rows pulled from statement streams on this thread (tests count what paging reads).
pub(crate) static ROWS_PULLED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Reads on from `stream`: past the next `skip` rows without decoding them, then keeping at
/// most `max` rows with their cells read as `mode`. `rows_affected` reads a command's count.
async fn drain<S, D, R>(
stream: &mut S,
reader: &mut Reader<R>,
skip: usize,
max: usize,
mode: Cells,
rows_affected: impl Fn(&D) -> u64,
) -> IdeResult<Fetched>
where
S: futures::Stream<Item = Result<sqlx::Either<D, R>, sqlx::Error>> + Unpin,
R: Row,
usize: ColumnIndex<R>,
String: sqlx::Type<R::Database>,
for<'r> String: Decode<'r, R::Database>,
for<'r> Vec<u8>: Decode<'r, R::Database>,
{
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
let mut affected: Option<u64> = None;
let mut has_more = false;
let mut first: Option<Instant> = None;
let mut to_skip = skip;
loop {
let item = match reader.carry.take() {
Some(row) => Ok(sqlx::Either::Right(row)),
None => match stream.next().await {
Some(item) => {
#[cfg(test)]
if matches!(item, Ok(sqlx::Either::Right(_))) {
ROWS_PULLED.with(|n| n.set(n.get() + 1));
}
item
}
None => break,
},
};
first.get_or_insert_with(Instant::now);
match item {
Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + rows_affected(&done)),
Ok(sqlx::Either::Right(row)) => {
if reader.columns.is_empty() {
reader.columns = result_columns(&row);
}
if to_skip > 0 {
to_skip -= 1;
continue;
}
if rows.len() >= max {
reader.carry = Some(row);
has_more = true;
break;
}
rows.push((0..row.len()).map(|i| cell(&row, i, mode)).collect());
}
Err(e) => return Err(db_err(e)),
}
}
Ok((reader.columns.clone(), rows, affected, has_more, first))
}
/// Streams the results of `$sql` on executor `$exec`, reading past the first `$skip`
/// rows without decoding them, then keeping at most `$max` rows with their cells read as `$mode`.
macro_rules! fetch {
@@ -716,8 +493,44 @@ macro_rules! fetch {
fetch!($exec, $sql, 0usize, $max, $mode)
};
($exec:expr, $sql:expr, $skip:expr, $max:expr, $mode:expr) => {{
use futures::StreamExt;
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe($sql.to_owned())).fetch_many($exec);
drain(&mut stream, &mut Reader::default(), $skip, $max, $mode, |done| done.rows_affected()).await
let mut columns: Vec<ResultColumn> = Vec::new();
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
let mut affected: Option<u64> = None;
let mut has_more = false;
let mut failure = None;
let mut first: Option<Instant> = None;
let mut to_skip: usize = $skip;
while let Some(item) = stream.next().await {
first.get_or_insert_with(Instant::now);
match item {
Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + done.rows_affected()),
Ok(sqlx::Either::Right(row)) => {
if columns.is_empty() {
columns = result_columns(&row);
}
if to_skip > 0 {
to_skip -= 1;
continue;
}
if rows.len() >= $max {
has_more = true;
break;
}
rows.push((0..row.len()).map(|i| cell(&row, i, $mode)).collect());
}
Err(e) => {
failure = Some(db_err(e));
break;
}
}
}
drop(stream);
match failure {
Some(e) => Err(e),
None => Ok((columns, rows, affected, has_more, first)),
}
}};
}
@@ -773,31 +586,6 @@ macro_rules! backend_id {
}};
}
mod cursor;
pub(crate) use cursor::{Cursors, Key as CursorKey};
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
/// leaves the session as it was.
pub(crate) fn cursor_statement(sql: &str) -> bool {
looks_like_query(sql) && !context_may_change(sql)
}
/// A [`QueryResult`] of what `fetched` read of `sql`, run since `started`.
pub(crate) fn query_result(sql: &str, fetched: Fetched, started: Instant) -> QueryResult {
let (columns, rows, affected, has_more, first) = fetched;
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
QueryResult {
statement: sql.to_owned(),
affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None },
columns,
rows,
has_more,
elapsed_ms,
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
truncated: Vec::new(),
}
}
// Session control, scripts and PostgreSQL set_config can invalidate the tracked context.
fn context_may_change(sql: &str) -> bool {
let text = sql.trim().trim_end_matches(';');
@@ -1064,18 +852,17 @@ impl Pool {
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
}
let options = PostgresOptions { connection: opts, read_only: source.read_only };
let mut manager = PgManager { options, init: init.clone(), timeout };
let mut manager = PgManager { options: opts, init: init.clone(), timeout };
// Open once directly so authentication failures retain their database error.
let first = match manager.connect().await {
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
manager.options = manager.options.clone().ssl_mode(PgSslMode::Disable);
manager.connect().await
}
first => first,
}
.map_err(|e| postgres_connect_error(e, source.read_only))?;
.map_err(db_err)?;
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
let _ = pool.add(first);
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
@@ -1198,12 +985,6 @@ impl Pool {
}
}
/// Whether a later page of a result can be read from a cursor instead of by running the statement
/// again: the drivers whose rows stream from one connection that can wait for the next page.
pub(crate) fn keeps_cursors(&self) -> bool {
matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_))
}
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
if let Pool::Jdbc(p) = self {
@@ -1622,7 +1403,17 @@ impl Held {
Held::Clickhouse(_) | Held::Snowflake(..) => unreachable!(),
};
self.after_statement(sql);
Ok(query_result(sql, fetched, started))
let (columns, rows, affected, has_more, first) = fetched;
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
Ok(QueryResult {
statement: sql.to_owned(),
affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None },
columns,
rows,
has_more,
elapsed_ms,
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
})
}
}
@@ -1648,91 +1439,6 @@ mod tests {
use super::*;
use crate::source::{DbOptions, DbProperty};
fn rows(cells: Vec<Vec<Option<String>>>) -> QueryResult {
query_result("select", (Vec::new(), cells, None, false, None), Instant::now())
}
#[test]
fn capping_cells_bounds_a_page_and_reports_the_whole_length() {
let wide = "x".repeat(1_000_000);
let mut r = rows(vec![vec![Some("short".into()), Some(wide.clone()), None], vec![Some(wide), None, None]]);
r.cap_cells(100);
let size: usize = r.rows.iter().flatten().flatten().map(String::len).sum();
assert_eq!(size, 5 + 100 + 100);
assert_eq!(
r.truncated,
[
TruncatedCell { row: 0, column: 1, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) },
TruncatedCell { row: 1, column: 0, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) }
]
);
assert_eq!(r.rows[0][0].as_deref(), Some("short"));
assert_eq!(r.rows[0][2], None);
}
#[test]
fn a_cut_cell_is_hashed_by_its_utf16_units() {
// Fixed values: the client (`cutCells.ts`) computes the same hash to recognise a value it reads again.
assert_eq!(fnv1a_utf16(""), 2_166_136_261);
assert_eq!(fnv1a_utf16("a"), 3_826_002_220);
assert_eq!(fnv1a_utf16("a😀b"), 2_412_414_209);
assert_eq!(fnv1a_utf16("日本語日本語"), 2_778_669_755);
assert_ne!(fnv1a_utf16(&"x".repeat(100)), fnv1a_utf16(&format!("{}y", "x".repeat(99))));
let mut r = rows(vec![vec![Some("a😀b".into())]]);
r.cap_cells(2);
assert_eq!(r.truncated[0].hash, 2_412_414_209);
}
#[test]
fn capping_cells_keeps_values_at_or_under_the_limit_whole() {
let mut r = rows(vec![vec![Some("abcd".into()), Some("😀😀".into()), Some("ééé".into())]]);
// 4 units, 4 units (two pairs), 3 units in 6 bytes.
r.cap_cells(4);
assert!(r.truncated.is_empty());
assert_eq!(r.rows[0][1].as_deref(), Some("😀😀"));
r.cap_cells(3);
assert_eq!(
r.truncated,
[
TruncatedCell { row: 0, column: 0, length: 4, hash: fnv1a_utf16("abcd") },
TruncatedCell { row: 0, column: 1, length: 4, hash: fnv1a_utf16("😀😀") }
]
);
assert_eq!(r.rows[0][2].as_deref(), Some("ééé"));
}
#[test]
fn capping_cells_never_splits_a_character_or_a_surrogate_pair() {
// "a😀b": units a=1, 😀=2, b=1. A cut inside the pair falls back to before it.
let mut r = rows(vec![vec![Some("a😀b".into()), Some("日本語日本語".into())]]);
r.cap_cells(2);
assert_eq!(r.rows[0][0].as_deref(), Some("a"));
assert_eq!(r.rows[0][1].as_deref(), Some("日本"));
assert_eq!(r.truncated[0].length, 4);
assert_eq!(r.truncated[1].length, 6);
// What is kept is a prefix of the whole value, measured in UTF-16 units.
for (cut, whole) in [(&r.rows[0][0], "a😀b"), (&r.rows[0][1], "日本語日本語")] {
assert!(whole.starts_with(cut.as_deref().unwrap()));
assert!(cut.as_deref().unwrap().encode_utf16().count() <= 2);
}
}
#[test]
fn postgres_read_only_guidance_identifies_what_the_pooler_rejected() {
let rejected = "unsupported startup parameter in options: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), rejected), Some(PG_READ_ONLY_HINT));
let direct = "unsupported startup parameter: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), direct), Some(PG_READ_ONLY_HINT));
let options = postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: options").unwrap();
assert!(options.contains("rejects PostgreSQL startup options"));
assert_eq!(postgres_read_only_hint(false, Some("08P01"), rejected), None);
assert_eq!(postgres_read_only_hint(true, Some("28P01"), rejected), None);
assert_eq!(
postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: extra_float_digits"),
None
);
}
#[test]
fn prefer_retries_without_tls_only_after_a_failed_handshake() {
use std::io;
-474
View File
@@ -1,474 +0,0 @@
//! Result paging that reads on from where the previous page stopped.
//!
//! A statement has no way to start at row N: its server sends the rows before it, and a
//! page that re-runs the query reads and drops all of them. The page after another one
//! continues the same stream instead, so paging forward costs one page per click.
//!
//! A cursor keeps its statement's stream, and so its connection, open, which holds
//! server resources (locks, a snapshot) for as long as it lives. That is bounded:
//! one cursor per target, a few overall, each closed after [`IDLE`] without a page, when
//! its tab is closed or its target disconnects, and before a statement that is not a
//! query runs on its target. A page that finds no cursor at its position (jumping
//! to another page, going back, a closed cursor) starts a new one.
use super::{Cells, Fetched, Held, Pool, Reader, drain, looks_like_query, statement_columns};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::Mutex;
use sqlx::{Executor, SqlSafeStr};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
/// How long a cursor waits for its next page.
const IDLE: Duration = Duration::from_secs(30);
/// Cursors kept at once, over all targets (each holds a connection).
const MAX_CURSORS: usize = 4;
/// What a cursor reads the pages of: one statement of one target, in a schema context.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Key {
target: String,
statement: String,
schema: Option<String>,
}
impl Key {
pub(crate) fn new(target: &str, statement: &str, schema: Option<&str>) -> Self {
Self {
target: target.to_owned(),
statement: statement.to_owned(),
schema: schema.filter(|s| !s.is_empty()).map(str::to_owned),
}
}
}
/// A request for the next rows of a cursor's statement.
struct Read {
skip: usize,
max: usize,
cancel: CancellationToken,
reply: oneshot::Sender<IdeResult<Fetched>>,
}
/// A live cursor: where its stream stands, and the channel to the task that owns it.
struct Slot {
id: u64,
key: Key,
/// The number of rows read from the start of the statement (skipped or returned).
next: usize,
/// A page is being read from it: it stays registered meanwhile, so a release finds it.
busy: bool,
reads: mpsc::Sender<Read>,
}
/// Reads `max` rows after the first `skip` of a cursor's stream through `reads`; `None` when the cursor is gone.
async fn read(
reads: &mpsc::Sender<Read>,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> Option<IdeResult<Fetched>> {
let (reply, answer) = oneshot::channel();
reads.send(Read { skip, max, cancel: cancel.clone(), reply }).await.ok()?;
answer.await.ok()
}
#[derive(Default)]
struct Registry {
/// Oldest first.
slots: Vec<Slot>,
issued: u64,
}
#[derive(Default)]
pub(crate) struct Cursors {
registry: Mutex<Registry>,
}
impl Cursors {
/// The page at `skip` read from the cursor of `key` that stands there; `None` when
/// there is none (the caller starts one) or it failed (a lost connection: the caller
/// runs the statement again and reports whatever that returns).
pub(crate) async fn resume(
&self,
key: &Key,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> Option<IdeResult<Fetched>> {
let (id, reads) = {
let mut registry = self.registry.lock();
let slot = registry
.slots
.iter_mut()
.find(|s| s.key == *key && s.next == skip && !s.busy && !s.reads.is_closed())?;
slot.busy = true;
(slot.id, slot.reads.clone())
};
match read(&reads, 0, max, cancel).await {
Some(Ok(fetched)) => {
self.finish(id, &fetched);
Some(Ok(fetched))
}
Some(Err(e)) if e.kind == ErrorKind::Cancelled => {
self.close(id);
Some(Err(e))
}
_ => {
self.close(id);
None
}
}
}
/// Runs the statement of `key` on `held`, returns the page at `skip` and keeps the
/// statement's stream for the page after it. `held` is taken out of `pool` (its
/// context applied); `pool` stops the statement on the server when `cancel` fires.
pub(crate) async fn start(
&self,
held: Held,
pool: Arc<Pool>,
key: Key,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> IdeResult<Fetched> {
let (reads, requests) = mpsc::channel(1);
tokio::spawn(serve(held, pool, key.statement.clone(), requests));
let id = self.register(key, skip, reads.clone());
let fetched = match read(&reads, skip, max, cancel).await {
Some(Ok(fetched)) => fetched,
other => {
self.close(id);
return other.unwrap_or_else(|| Err(IdeError::internal("the statement stopped before it answered")));
}
};
self.finish(id, &fetched);
Ok(fetched)
}
/// Registers a cursor that is reading its first page. A target keeps one cursor (its
/// connection pool is small), and all together are bounded.
fn register(&self, key: Key, next: usize, reads: mpsc::Sender<Read>) -> u64 {
let mut registry = self.registry.lock();
registry.issued += 1;
let id = registry.issued;
registry.slots.retain(|s| s.key.target != key.target && !s.reads.is_closed());
registry.slots.push(Slot { id, key, next, busy: true, reads });
if registry.slots.len() > MAX_CURSORS {
registry.slots.remove(0);
}
id
}
/// Ready for the page after `fetched`, which cursor `id` just read, when more rows are waiting in its
/// stream; closed otherwise. A cursor released meanwhile is gone from the registry: the caller's
/// handle on its channel is the last, so the statement stops.
fn finish(&self, id: u64, fetched: &Fetched) {
let mut registry = self.registry.lock();
let Some(at) = registry.slots.iter().position(|s| s.id == id) else { return };
if fetched.3 {
let slot = &mut registry.slots[at];
slot.next += fetched.1.len();
slot.busy = false;
} else {
registry.slots.remove(at);
}
}
fn close(&self, id: u64) {
self.registry.lock().slots.retain(|s| s.id != id);
}
/// Closes the cursor of one statement of `target` (its result tab was closed), also when it is reading a page.
pub(crate) fn release(&self, key: &Key) {
self.registry.lock().slots.retain(|s| s.key != *key);
}
/// Closes the cursors of `target`: it disconnects, or a statement that changes
/// data or schema is about to run there.
pub(crate) fn release_target(&self, target: &str) {
self.registry.lock().slots.retain(|s| s.key.target != target);
}
}
/// Owns `held` and the stream of `sql` on it, answering reads until the stream ends,
/// nobody asks for [`IDLE`], or it is released (its channel closes).
async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Receiver<Read>) {
let Some(first) = reads.recv().await else { return held.discard().await };
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
// Evaluates to whether the connection can go back to its pool (the stream was read to
// its end); otherwise it is closed rather than left to be drained.
macro_rules! serve {
($conn:expr, $id:expr, $kill:expr) => {{
let backend = match $id {
Some(q) => backend_id!(&mut **$conn, q),
None => None,
};
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).fetch_many(&mut **$conn);
let mut reader = Reader::default();
let mut request = Some(first);
let mut last = None;
let mut reusable = false;
while let Some(Read { skip, max, cancel, reply }) = request.take() {
let read = tokio::select! {
r = drain(&mut stream, &mut reader, skip, max, Cells::Display, |done| done.rows_affected()) => r,
() = cancel.cancelled() => Err(IdeError::cancelled()),
};
if cancel.is_cancelled() {
if let Some(b) = backend {
let _ = pool.rows(&$kill(b), 1).await;
}
let _ = reply.send(Err(IdeError::cancelled()));
break;
}
match read {
Ok(fetched) if fetched.3 => {
if reply.send(Ok(fetched)).is_err() {
break;
}
request = tokio::time::timeout(IDLE, reads.recv()).await.unwrap_or(None);
}
Ok(fetched) => {
last = Some((reply, fetched));
reusable = true;
break;
}
Err(e) => {
let _ = reply.send(Err(e));
reusable = true;
break;
}
}
}
drop(stream);
if let Some((reply, mut fetched)) = last {
if fetched.0.is_empty() && looks_like_query(&sql) {
fetched.0 = (&mut **$conn)
.prepare(sqlx::AssertSqlSafe(sql.clone()).into_sql_str())
.await
.map(|s| statement_columns(&s))
.unwrap_or_default();
}
let _ = reply.send(Ok(fetched));
}
reusable
}};
}
let reusable = match &mut held {
Held::Sqlite(c) => serve!(c, None::<&str>, |_: String| String::new()),
Held::Postgres(c) => {
serve!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
}
Held::Mysql(c) => serve!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
_ => unreachable!("only the sqlx drivers keep cursors"),
};
if !reusable {
held.discard().await;
}
}
#[cfg(test)]
mod tests {
use super::super::ROWS_PULLED;
use crate::{DataSource, DbDriver, DbManager};
use ide_core::{CancellationToken, error::ErrorKind};
const PAGE: usize = 100;
const ROWS: usize = 1000;
/// A SQLite data source `s1` with a table `t` of `ROWS` rows (`id` 1..=ROWS).
async fn manager() -> (tempfile::TempDir, DbManager) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
std::fs::File::create(root.join("app.db")).unwrap();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![DataSource {
id: "s1".into(),
name: "app".into(),
driver: DbDriver::Sqlite,
file: Some("app.db".into()),
..Default::default()
}])
.await
.unwrap();
let cancel = CancellationToken::new();
db.execute("s1", "CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)", 0, &cancel).await.unwrap();
db.execute(
"s1",
&format!(
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < {ROWS}) \
INSERT INTO t SELECT i, 'row ' || i FROM n"
),
0,
&cancel,
)
.await
.unwrap();
(tmp, db)
}
const QUERY: &str = "SELECT id, name FROM t ORDER BY id";
/// The ids of page `page` of `QUERY`, and whether more rows follow.
async fn page(db: &DbManager, statement: &str, page: usize) -> (Vec<i64>, bool) {
let r = db.execute_from("s1", statement, page * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap();
(r.rows.iter().map(|row| row[0].as_deref().unwrap().parse().unwrap()).collect(), r.has_more)
}
fn ids(page: usize) -> Vec<i64> {
((page * PAGE + 1) as i64..=((page + 1) * PAGE) as i64).collect()
}
fn pulled() -> u64 {
ROWS_PULLED.with(std::cell::Cell::get)
}
#[tokio::test]
async fn paging_forward_reads_each_row_once() {
let (_tmp, db) = manager().await;
let before = pulled();
for p in 0..ROWS / PAGE {
let (rows, has_more) = page(&db, QUERY, p).await;
assert_eq!(rows, ids(p), "page {p}");
assert_eq!(has_more, p + 1 < ROWS / PAGE, "page {p} has_more");
}
// Running the query again for every page reads 1+2+…+10 pages (5500 rows); one pass reads ~1000.
assert!(pulled() - before < 2 * ROWS as u64, "read {} rows", pulled() - before);
}
#[tokio::test]
async fn jumping_and_going_back_return_the_right_pages() {
let (_tmp, db) = manager().await;
for p in [5, 6, 2, 3, 9, 0, 1, 7, 7, 8] {
assert_eq!(page(&db, QUERY, p).await.0, ids(p), "page {p}");
}
}
#[tokio::test]
async fn reading_a_row_leaves_the_cursor_of_the_pages_alone() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
let row = db.read_row("s1", QUERY, 350, &CancellationToken::new(), None).await.unwrap();
assert_eq!(row.rows, [[Some("351".to_owned()), Some("row 351".to_owned())]]);
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
// The next page still continues the cursor: it reads one page, not 200 rows again.
let before = pulled();
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
assert!(pulled() - before <= PAGE as u64 + 1, "read {} rows", pulled() - before);
}
#[tokio::test]
async fn pages_past_the_end_are_empty() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 8).await;
let r = db.execute_from("s1", QUERY, 2 * ROWS, PAGE, &CancellationToken::new(), None).await.unwrap();
assert!(r.rows.is_empty() && !r.has_more);
// The columns of an empty page still come from the statement.
assert_eq!(r.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "name"]);
}
#[tokio::test]
async fn another_statement_does_not_continue_a_cursor() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
let other = "SELECT id, name FROM t ORDER BY id DESC";
let r = db.execute_from("s1", other, 2 * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap();
let first: i64 = r.rows[0][0].as_deref().unwrap().parse().unwrap();
assert_eq!(first, (ROWS - 2 * PAGE) as i64);
}
#[tokio::test]
async fn a_statement_that_changes_data_closes_the_cursor() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
db.execute("s1", "DELETE FROM t WHERE id = 150", 0, &CancellationToken::new()).await.unwrap();
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
// The next page shows the change: row 150 is gone, so page 2 starts at 202.
assert_eq!(page(&db, QUERY, 2).await.0[0], 202);
}
#[tokio::test]
async fn releasing_and_abandoning_cursors_gives_their_connections_back() {
let (_tmp, db) = manager().await;
// The pool has 4 connections: a leak would starve `execute` after a few rounds.
for _ in 0..8 {
page(&db, QUERY, 1).await;
db.release_result("s1", QUERY, None);
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
assert_eq!(page(&db, "SELECT count(*) FROM t", 0).await.0, [ROWS as i64]);
}
// Finishing a result also frees its connection.
for _ in 0..8 {
for p in 1..ROWS / PAGE {
page(&db, QUERY, p).await;
}
}
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
}
#[tokio::test]
async fn a_cancelled_page_closes_its_cursor() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
let cancel = CancellationToken::new();
cancel.cancel();
let e = db.execute_from("s1", QUERY, 2 * PAGE, PAGE, &cancel, None).await.unwrap_err();
assert_eq!(e.kind, ErrorKind::Cancelled);
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
}
/// A closed result tab releases its cursor even when a page is being read from it: the
/// cursor is not put back afterwards and its statement stops.
#[tokio::test]
async fn releasing_a_cursor_in_the_middle_of_a_page_read_closes_it() {
use super::{Cursors, Key, Read};
use std::sync::Arc;
use tokio::sync::{Notify, mpsc};
let cursors = Arc::new(Cursors::default());
let key = Key::new("s1", QUERY, None);
let (reads, mut requests) = mpsc::channel::<Read>(1);
cursors.register(key.clone(), 0, reads.clone());
let page = || (Vec::new(), vec![vec![Some("1".to_owned())]], None, true, None);
cursors.finish(1, &page());
drop(reads);
let in_read = Arc::new(Notify::new());
let (release, announced) = (Arc::new(Notify::new()), in_read.clone());
let server = tokio::spawn({
let release = release.clone();
async move {
let read = requests.recv().await.unwrap();
announced.notify_one();
release.notified().await;
let _ = read.reply.send(Ok(page()));
// The channel closes once nobody holds a handle on it.
requests.recv().await.is_none()
}
});
let resumed = tokio::spawn({
let (cursors, key) = (cursors.clone(), key.clone());
async move { cursors.resume(&key, 1, 1, &CancellationToken::new()).await.is_some() }
});
in_read.notified().await;
cursors.release(&key);
release.notify_one();
assert!(resumed.await.unwrap(), "the page that was being read is still returned");
assert!(cursors.registry.lock().slots.is_empty(), "the released cursor is not put back");
assert!(server.await.unwrap(), "the statement's task sees its channel close");
}
#[tokio::test]
async fn a_target_keeps_one_cursor_and_all_are_bounded() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
page(&db, "SELECT id, name FROM t WHERE id > 0 ORDER BY id", 1).await;
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
// The first statement's cursor is gone: its next page is read again, and still right.
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
}
}
-436
View File
@@ -1,436 +0,0 @@
//! An approved foreground helper behind a loopback relay owned by the IDE.
use crate::DbExternalTunnel;
use ide_core::{IdeError, IdeResult, error::ErrorKind, process};
use parking_lot::Mutex;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::net::{TcpListener, TcpSocket, TcpStream};
use tokio::sync::Semaphore;
use tokio::task::{JoinHandle, JoinSet};
#[cfg(target_os = "linux")]
#[path = "external_tunnel/linux.rs"]
mod platform;
#[cfg(target_os = "macos")]
#[path = "external_tunnel/macos.rs"]
mod platform;
#[cfg(windows)]
#[path = "external_tunnel/windows.rs"]
mod platform;
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
mod platform {
use super::*;
pub(super) async fn owns_socket(_: &Arc<Helper>, _: SocketAddr, _: Option<SocketAddr>) -> io::Result<bool> {
Err(io::Error::new(io::ErrorKind::Unsupported, "socket ownership cannot be verified on this OS"))
}
}
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(3);
const POLL_INTERVAL: Duration = Duration::from_millis(100);
const MAX_CONNECTIONS: usize = 128;
static VERIFICATION_SLOTS: Semaphore = Semaphore::const_new(8);
static HELPERS: Mutex<ActiveHelpers> = Mutex::new(ActiveHelpers { stopping: false, children: Vec::new() });
struct ActiveHelpers {
stopping: bool,
children: Vec<Weak<Helper>>,
}
/// Stop the IDE's external TCP tunnel processes before desktop exit or restart.
pub fn stop_external_tunnels_on_exit() {
let children = {
let mut active = HELPERS.lock();
active.stopping = true;
std::mem::take(&mut active.children)
};
for helper in children.into_iter().filter_map(|child| child.upgrade()) {
helper.stop();
}
}
pub(super) struct ExternalTunnel {
port: u16,
// Keep the address reserved even after the helper exits, until the last route reference drops.
_listener: Arc<TcpListener>,
helper: Weak<Helper>,
task: JoinHandle<()>,
}
impl ExternalTunnel {
pub(super) fn validate(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<()> {
helper_target(config, target).map(|_| ())
}
pub(super) async fn open(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<Self> {
if !cfg!(any(target_os = "linux", target_os = "macos", windows)) {
return Err(IdeError::unavailable("External TCP tunnel socket ownership cannot be verified on this OS"));
}
let listener = Arc::new(loopback_socket()?.listen(128)?);
let port = listener.local_addr()?.port();
let reservation = loopback_socket()?;
let endpoint = reservation.local_addr()?;
let arguments = helper_arguments(config, target, endpoint.port())?;
drop(reservation);
let helper = launch_helper(Path::new(&config.executable), &arguments)?;
let ready = tokio::time::timeout(STARTUP_TIMEOUT, async {
loop {
if !helper.is_alive() {
return Err(IdeError::new(
ErrorKind::Io,
"The external TCP tunnel helper exited before opening its loopback listener. \
Check the helper command in a terminal.",
));
}
if verify_socket(&helper, endpoint, None).await.map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not verify the external TCP tunnel listener: {error}"))
})? {
return Ok(());
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await;
ready.map_err(|_| {
IdeError::new(
ErrorKind::Io,
format!(
"The external TCP tunnel helper did not open an owned listener at {endpoint} before the startup timeout. \
Check that the command binds to 127.0.0.1 and uses {{localPort}}."
),
)
})??;
let watched_helper = Arc::downgrade(&helper);
let task = tokio::spawn(relay(Arc::clone(&listener), endpoint, helper));
Ok(Self { port, _listener: listener, helper: watched_helper, task })
}
pub(super) fn port(&self) -> u16 {
self.port
}
pub(super) fn is_closed(&self) -> bool {
self.task.is_finished() || self.helper.upgrade().is_none_or(|helper| !helper.is_alive())
}
}
impl Drop for ExternalTunnel {
fn drop(&mut self) {
self.task.abort();
}
}
fn loopback_socket() -> io::Result<TcpSocket> {
let socket = TcpSocket::new_v4()?;
#[cfg(windows)]
platform::make_exclusive(&socket)?;
socket.bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into())?;
Ok(socket)
}
fn helper_target<'a>(config: &DbExternalTunnel, (host, port): (&'a str, u16)) -> IdeResult<(&'a str, u16)> {
let executable = Path::new(&config.executable);
if !executable.is_absolute() || executable.file_name().is_none() || config.executable.contains('\0') {
return Err(IdeError::invalid("Choose an absolute path to the external TCP tunnel executable"));
}
#[cfg(windows)]
if !executable.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) {
return Err(IdeError::invalid("Choose an .exe file for the external TCP tunnel"));
}
let host = host.trim();
let host = host
.strip_prefix('[')
.and_then(|host| host.strip_suffix(']'))
.filter(|host| host.parse::<std::net::Ipv6Addr>().is_ok())
.unwrap_or(host);
let dns = host.strip_suffix('.').unwrap_or(host);
if host.parse::<IpAddr>().is_err()
&& (dns.len() > 253
|| !dns.split('.').all(|label| {
let bytes = label.as_bytes();
bytes.len() <= 63
&& bytes.first().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.last().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.iter().all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
}))
{
return Err(IdeError::invalid("Enter a DNS name or IP address for the external TCP tunnel"));
}
if port == 0 {
return Err(IdeError::invalid("Enter a valid destination port for the external TCP tunnel"));
}
if !config.arguments.iter().any(|arg| arg.contains("{localPort}")) {
return Err(IdeError::invalid("Include {localPort} in the external TCP tunnel arguments"));
}
if config.arguments.iter().any(|arg| arg.contains('\0')) {
return Err(IdeError::invalid("External TCP tunnel arguments cannot contain NUL characters"));
}
Ok((host, port))
}
fn helper_arguments(config: &DbExternalTunnel, target: (&str, u16), local_port: u16) -> IdeResult<Vec<String>> {
let (host, port) = helper_target(config, target)?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let (local_port, port) = (local_port.to_string(), port.to_string());
let placeholders =
[("{host}:{port}", target.as_str()), ("{localPort}", &local_port), ("{host}", host), ("{port}", &port)];
Ok(config
.arguments
.iter()
.map(|arg| {
let mut remaining = arg.as_str();
let mut expanded = String::with_capacity(arg.len());
while let Some(start) = remaining.find('{') {
expanded.push_str(&remaining[..start]);
remaining = &remaining[start..];
if let Some((value, tail)) = placeholders
.into_iter()
.find_map(|(key, value)| remaining.strip_prefix(key).map(|tail| (value, tail)))
{
expanded.push_str(value);
remaining = tail;
} else {
expanded.push('{');
remaining = &remaining[1..];
}
}
expanded.push_str(remaining);
expanded
})
.collect())
}
fn launch_helper(executable: &Path, arguments: &[String]) -> IdeResult<Arc<Helper>> {
let mut active = HELPERS.lock();
if active.stopping {
return Err(IdeError::cancelled());
}
let helper = Arc::new(Helper::spawn(executable, arguments).map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not start the external TCP tunnel helper: {error}"))
})?);
active.children.retain(|child| child.strong_count() > 0);
active.children.push(Arc::downgrade(&helper));
Ok(helper)
}
struct Helper {
child: Option<Child>,
#[cfg(windows)]
job: process::Job,
}
impl Helper {
fn spawn(executable: &Path, arguments: &[String]) -> io::Result<Self> {
let mut command = Command::new(executable);
command
.args(arguments)
.current_dir(executable.parent().expect("validated absolute executable path"))
.env_clear()
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
// Keep user config discovery available without inheriting database or project variables.
for key in [
"PATH",
"HOME",
"XDG_CONFIG_HOME",
"XDG_CACHE_HOME",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"SYSTEMROOT",
"WINDIR",
"TMPDIR",
"TEMP",
"TMP",
"SSH_AUTH_SOCK",
"NO_PROXY",
"no_proxy",
] {
if let Some(value) = process::host_var_os(key) {
command.env(key, value);
}
}
for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"] {
if let Some(value) = process::host_var_os(key)
&& value.to_str().is_some_and(credential_free_proxy)
{
command.env(key, value);
}
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// Membership of this group is an authorization check. A separate session limits
// membership to this child and its descendants; the leader also owns the group.
// SAFETY: setsid is async-signal-safe and does not access Rust state after fork.
unsafe {
command.pre_exec(|| if libc::setsid() == -1 { Err(io::Error::last_os_error()) } else { Ok(()) });
}
}
#[cfg(windows)]
{
platform::spawn_suspended(command)
}
#[cfg(not(windows))]
{
Ok(Self { child: Some(command.spawn()?) })
}
}
fn child(&self) -> &Child {
self.child.as_ref().expect("the live helper owns its child handle")
}
#[cfg(unix)]
fn pid(&self) -> u32 {
self.child().id()
}
fn is_alive(&self) -> bool {
#[cfg(unix)]
{
loop {
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
// Keep the group leader unreaped so its id cannot be reused before group cleanup.
// SAFETY: valid output buffer and the id of the child owned by `self`.
let result = unsafe {
libc::waitid(
libc::P_PID,
self.pid(),
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if result == 0 {
// SAFETY: the buffer was zeroed and waitid returned successfully.
return unsafe { info.assume_init().si_pid() == 0 };
}
if io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
return false;
}
}
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
// SAFETY: the owned child handle stays open through this non-blocking check.
unsafe { WaitForSingleObject(self.child().as_raw_handle(), 0) == WAIT_TIMEOUT }
}
#[cfg(not(any(unix, windows)))]
{
false
}
}
fn stop(&self) {
#[cfg(windows)]
let _ = self.job.terminate();
#[cfg(unix)]
process::kill_tree_of(self.pid());
}
}
fn credential_free_proxy(value: &str) -> bool {
let url = if value.contains("://") {
reqwest::Url::parse(value)
} else {
reqwest::Url::parse(&format!("http://{value}"))
};
url.is_ok_and(|url| {
matches!(url.scheme(), "http" | "https" | "socks4" | "socks4a" | "socks5" | "socks5h")
&& url.host().is_some()
&& url.username().is_empty()
&& url.password().is_none()
&& matches!(url.path(), "" | "/")
&& url.query().is_none()
&& url.fragment().is_none()
})
}
impl Drop for Helper {
fn drop(&mut self) {
self.stop();
#[cfg(unix)]
if let Some(mut child) = self.child.take() {
// A helper blocked in the kernel must not hold up the async caller during cleanup.
if !matches!(child.try_wait(), Ok(Some(_))) {
let _ = std::thread::Builder::new().spawn(move || child.wait());
}
}
}
}
async fn relay(listener: Arc<TcpListener>, endpoint: SocketAddr, helper: Arc<Helper>) {
let mut connections = JoinSet::new();
let mut liveness = tokio::time::interval(Duration::from_secs(1));
liveness.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = liveness.tick() => {
if !helper.is_alive() { break; }
}
accepted = listener.accept(), if connections.len() < MAX_CONNECTIONS => {
let Ok((mut client, _)) = accepted else {
// Transient errors such as descriptor exhaustion affect new sockets only.
tokio::time::sleep(POLL_INTERVAL).await;
continue;
};
let helper = Arc::clone(&helper);
connections.spawn(async move {
if let Ok(Ok(mut upstream)) = tokio::time::timeout(CONNECTION_TIMEOUT, connect_verified(&helper, endpoint)).await {
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
true
} else {
false
}
});
}
finished = connections.join_next(), if !connections.is_empty() => {
if matches!(finished, Some(Ok(false)))
// A slow ownership probe must not interrupt already verified connections.
&& matches!(tokio::time::timeout(CONNECTION_TIMEOUT, verify_socket(&helper, endpoint, None)).await, Ok(Ok(false)))
{
break;
}
}
}
}
}
async fn connect_verified(helper: &Arc<Helper>, endpoint: SocketAddr) -> io::Result<TcpStream> {
let upstream = TcpStream::connect(endpoint).await?;
let peer = upstream.local_addr()?;
// TCP connect can complete before the helper accepts. Check the server's half of this
// exact connection, keeping all client bytes in the IDE until that socket has an owner.
loop {
if !helper.is_alive() {
return Err(io::Error::new(io::ErrorKind::BrokenPipe, "external TCP tunnel helper exited"));
}
if verify_socket(helper, endpoint, Some(peer)).await? && helper.is_alive() {
return Ok(upstream);
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
async fn verify_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let _slot = VERIFICATION_SLOTS.acquire().await.map_err(io::Error::other)?;
platform::owns_socket(helper, local, peer).await
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos", windows)))]
mod tests;
@@ -1,92 +0,0 @@
use super::{Helper, io};
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read};
use std::net::{SocketAddr, SocketAddrV4};
use std::sync::Arc;
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let helper = Arc::clone(helper);
tokio::task::spawn_blocking(move || {
let (SocketAddr::V4(local), peer) = (local, peer) else { return Ok(false) };
let peer = match peer {
Some(SocketAddr::V4(peer)) => Some(peer),
None => None,
_ => return Ok(false),
};
let state = if peer.is_some() { "01" } else { "0A" };
for (table, ipv6) in [("/proc/net/tcp", false), ("/proc/net/tcp6", true)] {
let file = match File::open(table) {
Ok(file) => file,
Err(error) if ipv6 && error.kind() == io::ErrorKind::NotFound => continue,
Err(error) => return Err(error),
};
let local = address(local, ipv6);
let peer = peer.map(|peer| address(peer, ipv6));
// Kernel rows are small, but bound the time spent scanning a busy host's table.
for line in BufReader::new(file.take(8 * 1024 * 1024)).lines().skip(1) {
let line = line?;
let mut fields = line.split_ascii_whitespace().skip(1);
let (Some(left), Some(right), Some(current_state)) = (fields.next(), fields.next(), fields.next())
else {
continue;
};
if left != local || current_state != state || peer.as_deref().is_some_and(|peer| peer != right) {
continue;
}
let Some(inode) = fields.nth(5).and_then(|inode| inode.parse::<u64>().ok()).filter(|inode| *inode != 0)
else {
continue;
};
if group_holds_socket(helper.pid(), inode)? {
return Ok(true);
}
}
}
Ok(false)
})
.await
.map_err(io::Error::other)?
}
fn address(address: SocketAddrV4, ipv6: bool) -> String {
let ip = address.ip();
let port = address.port();
if !ipv6 {
return format!("{:08X}:{port:04X}", u32::from_ne_bytes(ip.octets()));
}
let octets = ip.to_ipv6_mapped().octets();
let [a, b, c, d] = octets.as_chunks::<4>().0 else { unreachable!() };
format!(
"{:08X}{:08X}{:08X}{:08X}:{port:04X}",
u32::from_ne_bytes(*a),
u32::from_ne_bytes(*b),
u32::from_ne_bytes(*c),
u32::from_ne_bytes(*d)
)
}
fn group_holds_socket(group: u32, inode: u64) -> io::Result<bool> {
let group = i32::try_from(group).map_err(io::Error::other)?;
let target = format!("socket:[{inode}]");
for process in fs::read_dir("/proc")? {
let Ok(process) = process else { continue };
let name = process.file_name();
let Some(pid) = name.to_str().and_then(|name| name.parse::<libc::pid_t>().ok()).filter(|pid| *pid > 0) else {
continue;
};
// SAFETY: this only queries the process group of the enumerated pid.
if unsafe { libc::getpgid(pid) } != group {
continue;
}
let Ok(descriptors) = fs::read_dir(process.path().join("fd")) else { continue };
for descriptor in descriptors.flatten() {
if fs::read_link(descriptor.path()).is_ok_and(|link| link.as_os_str() == target.as_str()) {
// SAFETY: check membership again after examining the fd directory.
if unsafe { libc::getpgid(pid) } == group {
return Ok(true);
}
}
}
}
Ok(false)
}
@@ -1,61 +0,0 @@
use super::{Helper, io};
use std::net::{IpAddr, SocketAddr};
use std::process::Stdio;
use std::sync::Arc;
use tokio::io::AsyncReadExt;
const MAX_OUTPUT: u64 = 64 * 1024;
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let group = helper.pid().to_string();
let sockets = format!("-iTCP:{}", local.port());
let state = if peer.is_some() { "-sTCP:ESTABLISHED" } else { "-sTCP:LISTEN" };
let mut probe = tokio::process::Command::new("/usr/sbin/lsof")
.args(["-nP", "-a", "-g", &group, &sockets, state, "-Fgn"])
.env_clear()
.stdin(Stdio::null())
.stderr(Stdio::null())
.stdout(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let mut output = Vec::new();
probe.stdout.take().expect("stdout is piped").take(MAX_OUTPUT + 1).read_to_end(&mut output).await?;
if output.len() as u64 > MAX_OUTPUT {
return Err(io::Error::other("loopback socket ownership output exceeded its limit"));
}
let status = probe.wait().await?;
if !status.success() {
// lsof uses exit 1 for a successful scan with no matching descriptors.
return if status.code() == Some(1) && output.is_empty() {
Ok(false)
} else {
Err(io::Error::other("loopback socket ownership query failed"))
};
}
let mut owned = false;
for line in String::from_utf8_lossy(&output).lines() {
match line.as_bytes().first() {
Some(b'p') => owned = false,
Some(b'g') => owned = line[1..] == group,
Some(b'n') if owned => {
let (left, right) =
line[1..].split_once("->").map_or((&line[1..], None), |(left, right)| (left, Some(right)));
if address(left) == Some(local) && right.and_then(address) == peer && right.is_some() == peer.is_some()
{
return Ok(true);
}
}
_ => {}
}
}
Ok(false)
}
fn address(value: &str) -> Option<SocketAddr> {
let address = value.parse::<SocketAddr>().ok()?;
let ip = match address.ip() {
IpAddr::V6(ip) => ip.to_ipv4_mapped().map_or(IpAddr::V6(ip), IpAddr::V4),
ip => ip,
};
Some(SocketAddr::new(ip, address.port()))
}
-188
View File
@@ -1,188 +0,0 @@
use super::*;
use std::io::{Read, Write};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const EXAMPLE: &[u8; 4] = b"test";
const FIXTURE: &str = "external_tunnel::tests::fixture_entry";
fn config(mode: &str) -> crate::DbExternalTunnel {
crate::DbExternalTunnel {
executable: std::env::current_exe().unwrap().to_str().unwrap().to_owned(),
arguments: vec!["--exact".into(), FIXTURE.into(), "--skip".into(), format!("wire-{mode}-{{localPort}}")],
}
}
const TARGET: (&str, u16) = ("db.example", 5432);
// The test binary doubles as a foreground helper without an external interpreter.
#[test]
fn fixture_entry() {
let Some(fixture) = std::env::args().find(|arg| arg.starts_with("wire-")) else { return };
#[cfg(unix)]
// SAFETY: these calls only inspect the current process's session and group.
assert_eq!(unsafe { libc::getsid(0) }, unsafe { libc::getpgrp() });
let (mode, port) = fixture.strip_prefix("wire-").unwrap().split_once('-').unwrap();
let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port.parse().unwrap());
match mode {
"exit" => (),
"idle" => std::thread::sleep(Duration::from_secs(60)),
"waiting" => {
let observer = std::env::args()
.find_map(|arg| arg.strip_prefix("observer-port-").and_then(|port| port.parse::<u16>().ok()))
.unwrap();
let _observer = std::net::TcpStream::connect((Ipv4Addr::LOCALHOST, observer)).unwrap();
std::thread::sleep(Duration::from_secs(60));
}
"tree" => {
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["--exact", FIXTURE, "--skip", &format!("wire-echo-{port}")])
.spawn()
.unwrap();
assert!(child.wait().unwrap().success());
}
"echo" | "once" => {
let socket = std::net::TcpListener::bind(endpoint).unwrap();
std::thread::sleep(Duration::from_millis(150));
for stream in socket.incoming() {
let mut stream = stream.unwrap();
let mut bytes = [0; EXAMPLE.len()];
if stream.read_exact(&mut bytes).is_ok() {
stream.write_all(&bytes).unwrap();
stream.write_all(&endpoint.port().to_be_bytes()).unwrap();
if mode == "once" {
let _ = stream.read(&mut [0]);
break;
}
}
}
}
_ => unreachable!(),
}
}
#[tokio::test]
async fn forwards_multiple_connections_to_the_helpers_child_and_cleans_up() {
let tunnel = ExternalTunnel::open(&config("tree"), TARGET).await.unwrap();
let mut helper_port = 0;
for _ in 0..2 {
let result = tokio::time::timeout(Duration::from_secs(5), async {
let mut db = TcpStream::connect((Ipv4Addr::LOCALHOST, tunnel.port())).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let mut bytes = [0; EXAMPLE.len()];
db.read_exact(&mut bytes).await.unwrap();
assert_eq!(&bytes, EXAMPLE);
db.read_u16().await.unwrap()
});
helper_port = result.await.unwrap();
}
assert_ne!(helper_port, tunnel.port());
assert!(!tunnel.is_closed());
drop(tunnel);
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if TcpStream::connect((Ipv4Addr::LOCALHOST, helper_port)).await.is_err() {
break;
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await
.unwrap();
}
#[tokio::test]
async fn reports_a_helper_that_exits_without_listening() {
let result = ExternalTunnel::open(&config("exit"), TARGET).await;
assert!(result.err().unwrap().message.contains("exited"));
}
#[tokio::test]
async fn dropping_startup_stops_the_helper_before_it_listens() {
let observer = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let mut settings = config("waiting");
settings.arguments.extend(["--skip".into(), format!("observer-port-{}", observer.local_addr().unwrap().port())]);
let startup = tokio::spawn(async move { ExternalTunnel::open(&settings, TARGET).await });
let (mut helper_socket, _) =
tokio::time::timeout(Duration::from_secs(10), observer.accept()).await.unwrap().unwrap();
assert!(!startup.is_finished());
startup.abort();
assert!(startup.await.err().unwrap().is_cancelled());
let error = tokio::time::timeout(Duration::from_secs(5), helper_socket.read_u8()).await.unwrap().unwrap_err();
// Terminating the helper can reset its observer socket on Windows.
assert!(matches!(error.kind(), io::ErrorKind::UnexpectedEof | io::ErrorKind::ConnectionReset), "{error}");
}
#[tokio::test]
async fn refuses_an_unrelated_established_loopback_socket() {
let unrelated = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let endpoint = unrelated.local_addr().unwrap();
let settings = config("idle");
let arguments = helper_arguments(&settings, TARGET, endpoint.port()).unwrap();
let helper = Arc::new(Helper::spawn(Path::new(&settings.executable), &arguments).unwrap());
assert!(helper.is_alive());
assert!(!verify_socket(&helper, endpoint, None).await.unwrap());
let listener = loopback_socket().unwrap().listen(128).unwrap();
let relay_endpoint = listener.local_addr().unwrap();
let task = tokio::spawn(relay(Arc::new(listener), endpoint, helper));
tokio::time::timeout(Duration::from_secs(10), async {
let mut db = TcpStream::connect(relay_endpoint).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let (mut accepted, _) = unrelated.accept().await.unwrap();
assert_eq!(accepted.read_u8().await.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
task.await.unwrap();
})
.await
.unwrap();
}
#[tokio::test]
async fn a_dead_helper_keeps_its_relay_port_reserved_until_the_route_drops() {
let tunnel = ExternalTunnel::open(&config("once"), TARGET).await.unwrap();
let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, tunnel.port());
tokio::time::timeout(Duration::from_secs(5), async {
let mut db = TcpStream::connect(endpoint).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let mut bytes = [0; EXAMPLE.len()];
db.read_exact(&mut bytes).await.unwrap();
assert_eq!(&bytes, EXAMPLE);
db.read_u16().await.unwrap();
drop(db);
while !tunnel.is_closed() {
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await
.unwrap();
assert!(std::net::TcpListener::bind(endpoint).is_err());
}
#[test]
fn only_credential_free_proxy_addresses_reach_the_helper() {
assert!(credential_free_proxy("proxy.example:3128"));
assert!(credential_free_proxy("socks5h://proxy.example:1080"));
assert!(!credential_free_proxy("https://user:[email protected]:3128"));
assert!(!credential_free_proxy("https://proxy.example:3128/?secret=value"));
}
#[test]
fn expands_only_literal_arguments_and_validates_the_target() {
let settings = crate::DbExternalTunnel {
executable: config("echo").executable,
arguments: vec!["--port={localPort}".into(), "{host}:{port}".into(), "a b \"quotes\"".into()],
};
let arguments = helper_arguments(&settings, TARGET, 12345).unwrap();
assert_eq!(arguments, ["--port=12345", "db.example:5432", "a b \"quotes\""]);
assert!(helper_arguments(&settings, ("--some-option", 5432), 12345).is_err());
}
#[test]
fn brackets_an_ipv6_host_port_pair_but_preserves_the_raw_host_argument() {
let settings = crate::DbExternalTunnel {
executable: config("echo").executable,
arguments: vec!["{localPort}".into(), "{host}:{port}".into(), "{host}".into(), "[{host}]:{port}".into()],
};
let arguments = helper_arguments(&settings, ("[2001:db8::a]", 6432), 12345).unwrap();
assert_eq!(arguments, ["12345", "[2001:db8::a]:6432", "2001:db8::a", "[2001:db8::a]:6432"]);
}
@@ -1,161 +0,0 @@
use super::{Helper, io, process};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4};
use std::os::windows::io::{AsRawHandle, AsRawSocket, FromRawHandle, OwnedHandle};
use std::os::windows::process::CommandExt;
use std::process::Command;
use std::sync::Arc;
use tokio::net::TcpSocket;
use windows_sys::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, INVALID_HANDLE_VALUE, NO_ERROR};
use windows_sys::Win32::NetworkManagement::IpHelper::{
GetExtendedTcpTable, MIB_TCP_STATE_ESTAB, MIB_TCP_STATE_LISTEN, MIB_TCP6ROW_OWNER_PID, MIB_TCPROW_OWNER_PID,
TCP_TABLE_OWNER_PID_ALL,
};
use windows_sys::Win32::Networking::WinSock::{
AF_INET, AF_INET6, SO_EXCLUSIVEADDRUSE, SOCKET_ERROR, SOL_SOCKET, WSAGetLastError, setsockopt,
};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
pub(super) fn make_exclusive(socket: &TcpSocket) -> io::Result<()> {
let enabled = 1i32;
// SAFETY: the socket is open and the option value remains valid for this call.
let result = unsafe {
setsockopt(
socket.as_raw_socket() as usize,
SOL_SOCKET,
SO_EXCLUSIVEADDRUSE,
(&raw const enabled).cast(),
size_of::<i32>() as i32,
)
};
if result == SOCKET_ERROR {
// SAFETY: reads the last Winsock error on the calling thread.
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }));
}
Ok(())
}
pub(super) fn spawn_suspended(mut command: Command) -> io::Result<Helper> {
let mut child = command.creation_flags(CREATE_SUSPENDED | process::CREATE_NO_WINDOW).spawn()?;
let Some(job) = process::Job::for_child(&child) else {
// The child has never executed, so there are no descendants to terminate.
let _ = child.kill();
return Err(io::Error::other("could not contain the external tunnel helper in a Windows job"));
};
let helper = Helper { child: Some(child), job };
resume_initial_thread(helper.child().id())?;
Ok(helper)
}
fn resume_initial_thread(pid: u32) -> io::Result<()> {
// SAFETY: the snapshot handle is owned here, and each enumeration call writes a sized entry.
unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if snapshot == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
let snapshot = OwnedHandle::from_raw_handle(snapshot);
let mut entry = THREADENTRY32 { dwSize: size_of::<THREADENTRY32>() as u32, ..Default::default() };
let mut has_entry = Thread32First(snapshot.as_raw_handle(), &mut entry);
while has_entry != 0 {
if entry.th32OwnerProcessID == pid {
let thread = OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID);
if thread.is_null() {
return Err(io::Error::last_os_error());
}
let thread = OwnedHandle::from_raw_handle(thread);
return match ResumeThread(thread.as_raw_handle()) {
1 => Ok(()),
u32::MAX => Err(io::Error::last_os_error()),
_ => Err(io::Error::other("external tunnel helper was not in its initial suspended state")),
};
}
entry.dwSize = size_of::<THREADENTRY32>() as u32;
has_entry = Thread32Next(snapshot.as_raw_handle(), &mut entry);
}
}
Err(io::Error::other("could not find the external tunnel helper's suspended thread"))
}
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let helper = Arc::clone(helper);
tokio::task::spawn_blocking(move || {
let state = if peer.is_some() { MIB_TCP_STATE_ESTAB as u32 } else { MIB_TCP_STATE_LISTEN as u32 };
let table = tcp_table(u32::from(AF_INET))?;
// SAFETY: this is the AF_INET owner-PID table, whose rows contain only integers.
for row in unsafe { rows::<MIB_TCPROW_OWNER_PID>(&table)? } {
if row.dwState == state
&& v4_address(row.dwLocalAddr, row.dwLocalPort) == local
&& peer.is_none_or(|peer| v4_address(row.dwRemoteAddr, row.dwRemotePort) == peer)
&& helper.job.contains_pid(row.dwOwningPid)
{
return Ok(true);
}
}
let table = tcp_table(u32::from(AF_INET6))?;
// SAFETY: this is the AF_INET6 owner-PID table, whose rows contain only integers.
for row in unsafe { rows::<MIB_TCP6ROW_OWNER_PID>(&table)? } {
if row.dwState == state
&& mapped_address(row.ucLocalAddr, row.dwLocalPort) == Some(local)
&& peer.is_none_or(|peer| mapped_address(row.ucRemoteAddr, row.dwRemotePort) == Some(peer))
&& helper.job.contains_pid(row.dwOwningPid)
{
return Ok(true);
}
}
Ok(false)
})
.await
.map_err(io::Error::other)?
}
fn v4_address(address: u32, port: u32) -> SocketAddr {
SocketAddrV4::new(Ipv4Addr::from(address.to_ne_bytes()), u16::from_be(port as u16)).into()
}
fn mapped_address(address: [u8; 16], port: u32) -> Option<SocketAddr> {
let address = Ipv6Addr::from(address).to_ipv4_mapped()?;
Some(SocketAddrV4::new(address, u16::from_be(port as u16)).into())
}
fn tcp_table(family: u32) -> io::Result<Vec<u32>> {
const MAX_TABLE: u32 = 8 * 1024 * 1024;
let mut size = 0;
let mut buffer = Vec::<u32>::new();
for _ in 0..3 {
// SAFETY: the buffer has the supplied capacity and u32 alignment for the owner-PID table.
let result = unsafe {
GetExtendedTcpTable(
if buffer.is_empty() { std::ptr::null_mut() } else { buffer.as_mut_ptr().cast() },
&mut size,
0,
family,
TCP_TABLE_OWNER_PID_ALL,
0,
)
};
match result {
NO_ERROR => return Ok(buffer),
ERROR_INSUFFICIENT_BUFFER if size <= MAX_TABLE => {
buffer.resize(size.div_ceil(size_of::<u32>() as u32) as usize, 0);
size = (buffer.len() * size_of::<u32>()) as u32;
}
_ => return Err(io::Error::from_raw_os_error(result as i32)),
}
}
Err(io::Error::other("the TCP socket ownership table did not stabilize"))
}
// `T` must be the matching Windows owner-PID row for this table, with no invalid bit patterns.
unsafe fn rows<T>(table: &[u32]) -> io::Result<&[T]> {
let Some((&count, data)) = table.split_first() else {
return Err(io::Error::other("missing TCP socket ownership table header"));
};
if align_of::<T>() > align_of::<u32>() || count as usize > std::mem::size_of_val(data) / size_of::<T>() {
return Err(io::Error::other("invalid TCP socket ownership table size"));
}
// SAFETY: the caller supplies the matching row layout; alignment and length are checked above.
Ok(unsafe { std::slice::from_raw_parts(data.as_ptr().cast(), count as usize) })
}
+9 -2
View File
@@ -1,7 +1,6 @@
//! A trusted local driver profile is shared by data sources. JDBC URLs and properties
//! can run driver-specific initialization. A project source may connect only with the
//! settings its user last accepted in the dialog; the approval lives outside the project.
use crate::local_settings::persist_local;
use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
@@ -31,6 +30,15 @@ pub struct DbJdbcDriver {
pub url_template: String,
}
fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> {
let dir = path.parent().expect("registry paths have a parent");
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
std::io::Write::write_all(&mut tmp, data)?;
tmp.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
fn local_jar(jar: &str) -> IdeResult<&Path> {
if jar.contains(if cfg!(windows) { ';' } else { ':' }) {
return Err(IdeError::invalid("A JDBC JAR path contains the system classpath separator"));
@@ -598,7 +606,6 @@ fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult<QueryResult> {
affected: (affected >= 0).then_some(affected as f64),
elapsed_ms,
execution_ms: elapsed_ms,
truncated: Vec::new(),
})
}
+153 -188
View File
@@ -4,12 +4,7 @@
pub mod catalog;
mod clickhouse;
mod external_tunnel;
pub use external_tunnel::stop_external_tunnels_on_exit;
mod jdbc;
mod local_settings;
mod route;
mod tunnel_approval;
pub use jdbc::{DbJdbcDriver, jdbc_driver_classes};
pub mod conn;
pub mod history;
@@ -26,12 +21,12 @@ mod watch;
pub use watch::SourcesWatch;
pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog};
pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
pub use conn::{Held, Pool, QueryResult, ResultColumn};
pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection, DbSnowflake,
DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
@@ -257,14 +252,17 @@ pub struct Databases {
/// Connections of one project's data sources, keyed by connection target (see [`split_target`]).
pub struct DbManager {
root: PathBuf,
pools: Mutex<HashMap<String, Arc<route::ConnectionSlot>>>,
routes: route::Routes,
local_external_tunnels: bool,
pools: Mutex<HashMap<String, Arc<Pool>>>,
/// SSH tunnels by data source id, shared by the pools of its databases
/// (closed with the last of them).
tunnels: Mutex<HashMap<String, Arc<Tunnel>>>,
/// Serialises opening tunnels so concurrent connects share one.
tunnel_open: tokio::sync::Mutex<()>,
/// App-wide SSH connections and host-key trust.
ssh: Arc<SshManager>,
saved_passwords: Arc<SecretStore>,
saved_passwords: SecretStore,
/// Directory of the global data sources and their saved passwords ([`DbManager::with_global_sources`]).
global: Option<(PathBuf, Arc<SecretStore>)>,
global: Option<(PathBuf, SecretStore)>,
history: Arc<HistoryStore>,
/// What introspection read of each data source, kept between runs.
catalogs: catalog::CatalogStore,
@@ -275,8 +273,6 @@ pub struct DbManager {
/// Manual-commit data sources, each with the connection of its open
/// transaction (taken by the first statement after a commit / rollback).
sessions: Mutex<HashMap<String, Session>>,
/// Result pages read on from where the previous page stopped, not by running the statement again.
cursors: conn::Cursors,
/// The data sources as last read from disk, for [`DbManager::reconcile_sources`]
/// (`None` until [`DbManager::watch_sources`]).
on_disk: Mutex<Option<Vec<DataSource>>>,
@@ -423,27 +419,26 @@ impl DbManager {
}
}
Self {
saved_passwords: Arc::new(SecretStore::new(passwords, &root)),
saved_passwords: SecretStore::new(passwords, &root),
global: None,
history,
catalogs,
recorder,
root,
pools: Mutex::default(),
routes: Mutex::default(),
local_external_tunnels: false,
tunnels: Mutex::default(),
tunnel_open: tokio::sync::Mutex::new(()),
ssh,
session_passwords: Mutex::default(),
on_disk: Mutex::default(),
sessions: Mutex::default(),
cursors: conn::Cursors::default(),
}
}
/// Also lists the global data sources stored in `dir` (the app data directory).
pub fn with_global_sources(mut self, dir: PathBuf) -> Self {
let passwords = self.saved_passwords.scoped(&dir);
self.global = Some((dir, Arc::new(passwords)));
self.global = Some((dir, passwords));
self
}
@@ -473,7 +468,7 @@ impl DbManager {
}
}
fn store_of(&self, source: &DataSource) -> &Arc<SecretStore> {
fn store_of(&self, source: &DataSource) -> &SecretStore {
match &self.global {
Some((_, store)) if source.global => store,
_ => &self.saved_passwords,
@@ -513,7 +508,13 @@ impl DbManager {
.find(|s| s.id == id)
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?
.resolved()?;
source.select_database(database);
if let Some(db) = database {
// The configured schema belongs to the configured database.
if source.driver == DbDriver::Snowflake && !source.database.eq_ignore_ascii_case(db) {
source.options.default_schema.clear();
}
source.database = db.to_owned();
}
Ok(source)
}
@@ -658,7 +659,8 @@ impl DbManager {
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
return self.ssh.set_secret(&c, secret, save);
self.ssh.set_secret(&c, secret, save);
return Ok(());
}
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
}
@@ -693,10 +695,7 @@ impl DbManager {
if !saved {
return None;
}
// The OS may wait for the user to unlock the credential store. A cancelled connection
// must be able to stop waiting without starting its helper when the prompt is answered.
let store = Arc::clone(self.store_of(source));
tokio::task::spawn_blocking(move || store.get(&key)).await.ok().flatten()
self.store_of(source).get(&key)
}
async fn password(&self, source: &DataSource) -> Option<String> {
@@ -734,6 +733,36 @@ impl DbManager {
}
}
/// Opens the SSH tunnel of `source` when it has one, returning the settings to
/// connect with (the tunnel's local end instead of the database host).
/// `shared` reuses (or registers) the data source's tunnel for its pools; Test
/// Connection opens a private one.
async fn endpoint(
&self,
source: &DataSource,
ssh_secret: Option<String>,
shared: bool,
) -> IdeResult<(DataSource, Option<Arc<Tunnel>>)> {
let Some(ssh) = source.ssh.as_ref().filter(|s| s.enabled && tunneled(source.driver)) else {
return Ok((source.clone(), None));
};
let local = |t: &Tunnel| DataSource { host: "127.0.0.1".into(), port: Some(t.port()), ..source.clone() };
let _opening = if shared { Some(self.tunnel_open.lock().await) } else { None };
if shared {
let existing = self.tunnels.lock().get(&source.id).filter(|t| !t.is_closed()).cloned();
if let Some(t) = existing {
return Ok((local(&t), Some(t)));
}
}
let session = self.ssh_session(source, ssh, ssh_secret).await?;
let (target_host, target_port) = tunnel_target(source);
let t = Arc::new(Tunnel::open(session, target_host, target_port).await?);
if shared {
self.tunnels.lock().insert(source.id.clone(), t.clone());
}
Ok((local(&t), Some(t)))
}
/// The SSH session the tunnel of `source` goes through: its shared SSH configuration's, or one
/// opened with the settings typed in the data source.
async fn ssh_session(
@@ -759,9 +788,7 @@ impl DbManager {
} else {
if let Some(s) = ssh_secret {
let save = self.ssh.config(config)?.save_secret;
if let Err(e) = self.ssh.set_secret(config, Some(s), save) {
tracing::warn!("could not save the SSH credential: {}", e.message);
}
self.ssh.set_secret(config, Some(s), save);
}
self.ssh.session(config).await?
})
@@ -788,35 +815,23 @@ impl DbManager {
source: &DataSource,
password: Option<String>,
ssh_secret: Option<String>,
) -> IdeResult<String> {
if source.external_tunnel.is_some() {
return Err(IdeError::invalid("Review the external tunnel in the local Test Connection dialog"));
}
self.test_connection(source, password, ssh_secret, route::RouteUse::Test).await
}
pub async fn test_external_tunnel(&self, source: &DataSource, password: Option<String>) -> IdeResult<String> {
self.external_config(source)?;
self.test_connection(source, password, None, route::RouteUse::ReviewedExternalTest).await
}
async fn test_connection(
&self,
source: &DataSource,
password: Option<String>,
ssh_secret: Option<String>,
purpose: route::RouteUse,
) -> IdeResult<String> {
let source = &source.resolved()?;
let password = match password {
Some(p) => Some(p),
None => self.password(source).await,
};
let (target, _tunnel) = self.endpoint(source, ssh_secret, purpose).await?;
let (target, tunnel) = self.endpoint(source, ssh_secret, false).await?;
self.restore_sso(source).await;
let connected = self.open_pool(&target, password.as_deref(), true).await;
self.keep_sso(source).await;
let pool = connected.map_err(|e| self.connection_error(e, source))?;
let pool = connected.map_err(|e| {
through_tunnel(
e,
source,
tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(),
)
})?;
if let Pool::Jdbc(p) = &pool {
let version = p.version.clone();
pool.close().await;
@@ -837,8 +852,7 @@ impl DbManager {
_ => pool.rows(version, 1).await,
};
pool.close().await;
let strict =
source.external_tunnel.is_some() || matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let strict = matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let rows = if strict { result? } else { result.unwrap_or_default() };
let v = rows.into_iter().next().and_then(|r| r.into_iter().next().flatten());
Ok(v.unwrap_or_else(|| "Connected".into()))
@@ -864,15 +878,11 @@ impl DbManager {
if source.driver != tool.driver() {
return Err(IdeError::invalid(format!("{} cannot connect to {}", tool.program(), source.name)));
}
// Keep the same route as the connected pool for the entire tool invocation.
let connection = self.connection(id).await?;
let target = connection.target(&source);
self.pool(id).await?;
let password = self.password(&source).await;
let mut prepared = tools::prepare(job, executable, &target, password.as_deref())?;
if source.external_tunnel.is_some() {
// libpq gives PGHOSTADDR precedence over --host when choosing the TCP peer.
prepared.env.push(("PGHOSTADDR".into(), target.host.clone()));
}
// Holding the tunnel keeps it open while the tool runs, even if the tree disconnects.
let (target, _tunnel) = self.endpoint(&source, None, true).await?;
let prepared = tools::prepare(job, executable, &target, password.as_deref())?;
tools::run(executable, &prepared.args, &prepared.env, prepared.input.as_deref(), cancel, on_output).await
}
@@ -898,6 +908,89 @@ impl DbManager {
.ok_or_else(|| IdeError::internal("no server version"))
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
}
/// Connected targets (data source ids, `<id>:<database>`).
pub fn connected(&self) -> Vec<String> {
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
}
/// The pool of target `id`, connecting first if needed.
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
let (source_id, _) = split_target(id);
// A dropped SSH session leaves every pool through it unusable: start over.
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
self.disconnect_source(source_id).await;
}
let cached = self.pools.lock().get(id).cloned();
if let Some(p) = cached {
if !p.is_closed() {
return Ok(p);
}
// The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect.
self.disconnect(id).await;
}
let source = self.source(id)?;
let password = self.password(&source).await;
let (target, tunnel) = self.endpoint(&source, None, true).await?;
self.restore_sso(&source).await;
let connected = self.open_pool(&target, password.as_deref(), false).await;
self.keep_sso(&source).await;
let pool = match connected {
Ok(p) => Arc::new(p),
Err(e) => {
self.drop_unused_tunnel(source_id);
return Err(through_tunnel(
e,
&source,
tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(),
));
}
};
// Another caller may have connected meanwhile; keep theirs.
let kept = self.pools.lock().entry(id.to_owned()).or_insert_with(|| pool.clone()).clone();
if !Arc::ptr_eq(&kept, &pool) {
// Ours lost the race: close it rather than leave its session open on the server.
pool.close().await;
} else if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(kept)
}
/// Closes the tunnel of `source_id` once none of its targets is connected.
fn drop_unused_tunnel(&self, source_id: &str) {
let in_use = self.pools.lock().keys().any(|k| split_target(k).0 == source_id);
if !in_use {
self.tunnels.lock().remove(source_id);
}
}
/// Disconnects target `id` (one database of a data source).
pub async fn disconnect(&self, id: &str) {
// A held connection would keep the pool from closing; manual mode stays on.
let session = self.sessions.lock().get(id).cloned();
if let Some(s) = session {
end_session(&s).await;
}
let pool = self.pools.lock().remove(id);
if let Some(p) = pool {
p.close().await;
}
self.drop_unused_tunnel(split_target(id).0);
}
/// Disconnects every database of data source `id`.
pub async fn disconnect_source(&self, id: &str) {
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
for t in targets {
self.disconnect(&t).await;
}
self.tunnels.lock().remove(id);
}
/// Creates a database on the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `template`, the database
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
@@ -1479,25 +1572,6 @@ impl DbManager {
r
}
/// Row number `row` (from 0) of the result of `statement`, whole: what a page shows cut
/// short. It leaves the cursor of the result's pages where it stands, and is not recorded
/// in the history (the statement already was).
pub async fn read_row(
&self,
id: &str,
statement: &str,
row: usize,
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, row, 1, cancel, schema, false).await
}
/// Closes the cursor that reads the pages of `statement` on `id` (its result tab was closed).
pub fn release_result(&self, id: &str, statement: &str, schema: Option<&str>) {
self.cursors.release(&conn::CursorKey::new(id, statement, schema));
}
fn remember_statement(&self, id: &str, statement: &str) {
let time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -1569,44 +1643,12 @@ impl DbManager {
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, skip, max_rows, cancel, schema, true).await
}
/// `paging`: whether the page may continue a cursor of `statement` (see `conn::cursor`).
#[allow(clippy::too_many_arguments)]
async fn run_paged(
&self,
id: &str,
statement: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
paging: bool,
) -> IdeResult<QueryResult> {
let pool = self.pool(id).await?;
if let Pool::Jdbc(p) = &*pool {
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
}
let session = self.sessions.lock().get(id).cloned();
if !conn::cursor_statement(statement) {
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
self.cursors.release_target(id);
}
if paging && session.is_none() && skip > 0 && pool.keeps_cursors() && conn::cursor_statement(statement) {
let key = conn::CursorKey::new(id, statement, schema);
let started = std::time::Instant::now();
let page = match self.cursors.resume(&key, skip, max_rows, cancel).await {
Some(page) => page,
None => {
let mut held = Held::acquire(&pool).await?;
held.apply_context(schema).await?;
self.cursors.start(held, pool.clone(), key, skip, max_rows, cancel).await
}
};
return page.map(|fetched| conn::query_result(statement, fetched, started));
}
let Some(session) = session else {
if schema.is_none() {
return pool.execute_from(statement, skip, max_rows, cancel).await;
@@ -1768,83 +1810,6 @@ mod tests {
DbManager::new(dir.join("project"), data.join("db-passwords.json"), data.join("db-history.json"), ssh)
}
#[tokio::test]
async fn external_tunnel_approval_binds_the_command_destination_and_local_scope() {
let tmp = tempfile::tempdir().unwrap();
#[cfg(windows)]
let name = "forward.exe";
#[cfg(not(windows))]
let name = "forward";
let program = tmp.path().join(name);
std::fs::write(&program, b"fixture version 1").unwrap();
let app = tmp.path().join("app");
let desktop = |root: &Path| manager(root).with_global_sources(app.clone()).with_local_external_tunnels(true);
let db = desktop(tmp.path());
let other = desktop(&tmp.path().join("other"));
let mut source = DataSource {
id: "pg".into(),
name: "Example PostgreSQL".into(),
driver: DbDriver::Postgres,
host: "db.example".into(),
external_tunnel: Some(DbExternalTunnel {
executable: program.to_str().unwrap().into(),
arguments: vec!["--listen={localPort}".into(), "{host}:{port}".into()],
}),
..Default::default()
};
assert!(db.check_external_approval(&source).await.is_err());
db.approve_external_tunnel(&source).await.unwrap();
db.save_sources(vec![source.clone()]).await.unwrap();
db.check_external_approval(&db.source("pg").unwrap()).await.unwrap();
db.check_external_approval(&source).await.unwrap();
assert!(other.check_external_approval(&source).await.is_err());
for changed in [
DataSource { host: "other.example".into(), ..source.clone() },
DataSource { user: "other".into(), ..source.clone() },
DataSource { ssl: DbSslMode::Require, ..source.clone() },
] {
assert!(db.check_external_approval(&changed).await.is_err());
}
let mut changed = source.clone();
changed.external_tunnel.as_mut().unwrap().arguments.push("--changed".into());
assert!(db.check_external_approval(&changed).await.is_err());
source.global = true;
assert!(db.check_external_approval(&source).await.is_err());
db.approve_external_tunnel(&source).await.unwrap();
db.save_sources(vec![source.clone()]).await.unwrap();
db.check_external_approval(&db.source("pg").unwrap()).await.unwrap();
other.check_external_approval(&source).await.unwrap();
std::fs::write(&program, b"fixture version 2").unwrap();
assert!(db.check_external_approval(&source).await.is_err());
}
#[tokio::test]
async fn external_tunnel_rejects_incompatible_modes_and_implicit_test() {
let tmp = tempfile::tempdir().unwrap();
let source = DataSource {
id: "pg".into(),
driver: DbDriver::Postgres,
external_tunnel: Some(DbExternalTunnel {
executable: std::env::current_exe().unwrap().to_str().unwrap().into(),
arguments: vec!["{localPort}".into()],
}),
..Default::default()
};
let remote = manager(tmp.path()).with_global_sources(tmp.path().join("app"));
assert!(remote.test_external_tunnel(&source, None).await.is_err());
let db = remote.with_local_external_tunnels(true);
assert!(db.test(&source, None, None).await.is_err());
for bad in [
DataSource { ssl: DbSslMode::VerifyFull, ..source.clone() },
DataSource { url_only: true, ..source.clone() },
DataSource { plugin_owner: Some("sample".into()), ..source.clone() },
DataSource { driver: DbDriver::Jdbc, ..source.clone() },
DataSource { ssh: Some(DbSsh { enabled: true, ..Default::default() }), ..source.clone() },
] {
assert!(db.approve_external_tunnel(&bad).await.is_err());
}
}
#[tokio::test]
async fn saved_passwords_stay_off_disk() {
let tmp = tempfile::tempdir().unwrap();
-11
View File
@@ -1,11 +0,0 @@
use ide_core::{IdeError, IdeResult};
use std::path::Path;
pub(super) fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> {
let dir = path.parent().expect("registry paths have a parent");
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
std::io::Write::write_all(&mut tmp, data)?;
tmp.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
-1
View File
@@ -283,7 +283,6 @@ mod tests {
has_more: false,
elapsed_ms: 0.0,
execution_ms: 0.0,
truncated: Vec::new(),
}
}
-251
View File
@@ -1,251 +0,0 @@
//! A connection target owns its pool and keeps its data source's forwarding route alive.
//! Concurrent opens of sibling databases share a helper, but unrelated sources never wait on it.
use super::*;
use external_tunnel::ExternalTunnel;
use std::sync::Weak;
use tokio::sync::OnceCell;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RouteUse {
Connect,
Test,
ReviewedExternalTest,
}
pub(super) enum Route {
Ssh(Tunnel),
External(ExternalTunnel),
}
impl Route {
fn port(&self) -> u16 {
match self {
Self::Ssh(t) => t.port(),
Self::External(t) => t.port(),
}
}
fn is_closed(&self) -> bool {
match self {
Self::Ssh(t) => t.is_closed(),
Self::External(t) => t.is_closed(),
}
}
}
type RouteSlot = Arc<OnceCell<Route>>;
// The file watcher may observe a source edit after a new caller already read it.
pub(super) struct CachedRoute {
host: String,
port: u16,
ssh: Option<DbSsh>,
helper: Option<DbExternalTunnel>,
slot: Weak<OnceCell<Route>>,
}
impl CachedRoute {
fn matches(&self, source: &DataSource) -> bool {
let (host, port) = tunnel_target(source);
self.host == host && self.port == port && self.ssh == source.ssh && self.helper == source.external_tunnel
}
}
pub(super) type Routes = Mutex<HashMap<String, CachedRoute>>;
#[derive(Clone)]
pub(super) struct Connection {
pub(super) pool: Arc<Pool>,
route: Option<RouteSlot>,
}
impl Connection {
pub(super) fn target(&self, source: &DataSource) -> DataSource {
routed_target(source, self.route.as_ref())
}
fn is_closed(&self) -> bool {
self.pool.is_closed() || self.route.as_ref().and_then(|s| s.get()).is_some_and(Route::is_closed)
}
}
#[derive(Default)]
pub(super) struct ConnectionSlot {
pub(super) value: OnceCell<Connection>,
pub(super) cancel: CancellationToken,
}
fn routed_target(source: &DataSource, slot: Option<&RouteSlot>) -> DataSource {
match slot.and_then(|s| s.get()) {
Some(route) => DataSource { host: "127.0.0.1".into(), port: Some(route.port()), ..source.clone() },
None => source.clone(),
}
}
impl DbManager {
pub(super) async fn endpoint(
&self,
source: &DataSource,
ssh_secret: Option<String>,
purpose: RouteUse,
) -> IdeResult<(DataSource, Option<RouteSlot>)> {
let external = source.external_tunnel.as_ref();
let ssh = source.ssh.as_ref().filter(|ssh| ssh.enabled && tunneled(source.driver));
if external.is_none() && ssh.is_none() {
return Ok((source.clone(), None));
}
if external.is_some() {
match purpose {
RouteUse::Connect => self.check_external_approval(source).await?,
RouteUse::ReviewedExternalTest => {
self.external_config(source)?;
}
RouteUse::Test => {
return Err(IdeError::invalid("Review the external tunnel in the local Test Connection dialog"));
}
}
}
let slot = if purpose == RouteUse::Connect {
let mut routes = self.routes.lock();
if let Some(slot) = routes.get(&source.id).filter(|r| r.matches(source)).and_then(|r| r.slot.upgrade())
&& !slot.get().is_some_and(Route::is_closed)
{
slot
} else {
routes.retain(|_, r| r.slot.strong_count() > 0);
let slot = Arc::new(OnceCell::new());
let (host, port) = tunnel_target(source);
routes.insert(
source.id.clone(),
CachedRoute {
host: host.to_owned(),
port,
ssh: source.ssh.clone(),
helper: source.external_tunnel.clone(),
slot: Arc::downgrade(&slot),
},
);
slot
}
} else {
Arc::new(OnceCell::new())
};
slot.get_or_try_init(|| async {
if let Some(config) = external {
ExternalTunnel::open(config, tunnel_target(source)).await.map(Route::External)
} else {
let ssh = ssh.expect("enabled SSH transport");
let session = self.ssh_session(source, ssh, ssh_secret).await?;
let (host, port) = tunnel_target(source);
Tunnel::open(session, host, port).await.map(Route::Ssh)
}
})
.await?;
Ok((routed_target(source, Some(&slot)), Some(slot)))
}
pub(super) fn connection_error(&self, error: IdeError, source: &DataSource) -> IdeError {
if source.external_tunnel.is_some() && error.kind == ErrorKind::Io {
return IdeError::new(error.kind, format!("{} through the external database tunnel", error.message));
}
let via = source.ssh.as_ref().filter(|s| s.enabled && tunneled(source.driver)).map(|ssh| self.ssh_label(ssh));
through_tunnel(error, source, via.as_deref())
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().get(id).and_then(|slot| slot.value.get()).is_some_and(|c| !c.is_closed())
}
pub fn connected(&self) -> Vec<String> {
self.pools
.lock()
.iter()
.filter(|(_, s)| s.value.get().is_some_and(|c| !c.is_closed()))
.map(|(id, _)| id.clone())
.collect()
}
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
Ok(self.connection(id).await?.pool)
}
pub(super) async fn connection(&self, id: &str) -> IdeResult<Connection> {
let (slot, stale) = {
let mut pools = self.pools.lock();
let stale = if pools.get(id).and_then(|s| s.value.get()).is_some_and(Connection::is_closed) {
pools.remove(id)
} else {
None
};
(pools.entry(id.into()).or_default().clone(), stale)
};
if let Some(stale) = stale {
self.close_target(id, stale).await;
}
let result = tokio::select! {
biased;
_ = slot.cancel.cancelled() => Err(IdeError::cancelled()),
result = slot.value.get_or_try_init(|| self.open_connection(id)) => result.cloned(),
};
if result.is_err() {
let mut pools = self.pools.lock();
if Arc::strong_count(&slot) == 2 && pools.get(id).is_some_and(|s| Arc::ptr_eq(s, &slot)) {
pools.remove(id);
}
}
result
}
async fn open_connection(&self, id: &str) -> IdeResult<Connection> {
let (source_id, database) = split_target(id);
let mut source = self.source(source_id)?;
let password = self.password(&source).await;
// The approval belongs to the configured source, including its login database.
// Sibling database selection changes only the driver's target after routing.
let (mut target, route) = self.endpoint(&source, None, RouteUse::Connect).await?;
target.select_database(database);
source.select_database(database);
self.restore_sso(&source).await;
let result = self.open_pool(&target, password.as_deref(), false).await;
self.keep_sso(&source).await;
let pool = Arc::new(result.map_err(|e| self.connection_error(e, &source))?);
if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(Connection { pool, route })
}
async fn close_target(&self, id: &str, slot: Arc<ConnectionSlot>) {
slot.cancel.cancel();
// A held transaction or result cursor keeps the pool from closing.
let session = self.sessions.lock().get(id).cloned();
if let Some(s) = session {
end_session(&s).await;
}
self.cursors.release_target(id);
if let Some(c) = slot.value.get() {
c.pool.close().await;
}
}
pub async fn disconnect(&self, id: &str) {
let slot = self.pools.lock().remove(id);
if let Some(slot) = slot {
self.close_target(id, slot).await;
}
}
pub async fn disconnect_source(&self, id: &str) {
let closing: Vec<_> = {
let mut pools = self.pools.lock();
let mut routes = self.routes.lock();
routes.remove(id);
pools.extract_if(|key, _| split_target(key).0 == id).collect()
};
for (_, slot) in &closing {
slot.cancel.cancel();
}
for (target, slot) in closing {
self.close_target(&target, slot).await;
}
}
}
-1
View File
@@ -892,7 +892,6 @@ impl SnowflakePool {
has_more,
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
execution_ms,
truncated: Vec::new(),
})))
}
-21
View File
@@ -296,14 +296,6 @@ pub struct DbSsh {
pub save_secret: bool,
}
/// A foreground program that forwards an IDE-assigned loopback port to the database.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbExternalTunnel {
pub executable: String,
pub arguments: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct DataSource {
@@ -326,8 +318,6 @@ pub struct DataSource {
pub read_only: bool,
/// SSH tunnel settings (`None`: never configured; kept but unused when not `enabled`).
pub ssh: Option<DbSsh>,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_tunnel: Option<DbExternalTunnel>,
/// Wire-compatible product preset (`cockroachdb`, `tidb`…; empty: the driver itself).
pub vendor: String,
pub color: Option<DbColor>,
@@ -371,7 +361,6 @@ impl Default for DataSource {
save_password: false,
read_only: false,
ssh: None,
external_tunnel: None,
vendor: String::new(),
color: None,
comment: String::new(),
@@ -512,16 +501,6 @@ pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
}
impl DataSource {
pub(crate) fn select_database(&mut self, database: Option<&str>) {
if let Some(db) = database {
// The configured schema belongs to the configured database.
if self.driver == DbDriver::Snowflake && !self.database.eq_ignore_ascii_case(db) {
self.options.default_schema.clear();
}
self.database = db.to_owned();
}
}
pub(crate) fn same_except_visibility(&self, other: &Self) -> bool {
if self == other {
return true;
+40 -93
View File
@@ -67,7 +67,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
AND has_schema_privilege(nspname, 'USAGE') ORDER BY 1"
}
DbDriver::Mysql if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::SqlServer if system => "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1",
DbDriver::SqlServer if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::Snowflake if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::Snowflake => {
"SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'INFORMATION_SCHEMA' ORDER BY 1"
@@ -89,8 +89,8 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') ORDER BY 1"
}
DbDriver::SqlServer => {
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA \
WHERE SCHEMA_NAME NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest') ORDER BY 1"
"SELECT schema_name FROM information_schema.schemata \
WHERE schema_name NOT IN ('sys', 'information_schema', 'guest') ORDER BY 1"
}
}
}
@@ -133,8 +133,8 @@ pub fn tables(driver: DbDriver, schema: &str) -> String {
quote_literal(driver, schema)
),
DbDriver::SqlServer => format!(
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
quote_literal(driver, schema)
),
}
@@ -177,14 +177,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
ORDER BY ordinal_position"
),
DbDriver::SqlServer => format!(
"SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, \
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = {s} \
AND tc.TABLE_NAME = {t} AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END \
FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_SCHEMA = {s} AND c.TABLE_NAME = {t} \
ORDER BY c.ORDINAL_POSITION"
"SELECT column_name, data_type, is_nullable, column_default, \
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = {s} \
AND tc.table_name = {t} AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
ORDER BY c.ordinal_position"
),
DbDriver::Snowflake => format!(
"SELECT column_name, {SNOWFLAKE_TYPE}, is_nullable, column_default, 0 \
@@ -300,18 +300,18 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
}
DbDriver::SqlServer => {
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.column_name, c.data_type, c.is_nullable, \
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema NOT IN ('sys', 'information_schema') \
ORDER BY c.table_schema, c.table_name, c.ordinal_position"
}
DbDriver::Snowflake => {
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
@@ -372,12 +372,11 @@ pub fn foreign_keys(driver: DbDriver) -> &'static str {
ORDER BY table_schema, table_name, constraint_name, ordinal_position LIMIT 20000"
}
DbDriver::SqlServer => {
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
WHERE fk.is_ms_shipped = 0 ORDER BY 1, 2, 3, fkc.constraint_column_id"
"SELECT table_schema, table_name, constraint_name, column_name, \
referenced_table_schema, referenced_table_name, referenced_column_name \
FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL \
AND table_schema NOT IN ('sys', 'information_schema') \
ORDER BY table_schema, table_name, constraint_name, ordinal_position"
}
DbDriver::Oracle => {
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, \
@@ -411,13 +410,7 @@ pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
),
DbDriver::SqlServer => format!(
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
WHERE fk.parent_object_id = OBJECT_ID(N{}) ORDER BY 3, fkc.constraint_column_id",
quote_literal(driver, &qualified(driver, schema, table))
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
),
DbDriver::Oracle => format!(
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, rcon.owner, rcon.table_name, rcol.column_name FROM all_constraints con JOIN all_cons_columns col ON col.owner = con.owner AND col.table_name = con.table_name AND col.constraint_name = con.constraint_name JOIN all_constraints rcon ON rcon.owner = con.r_owner AND rcon.constraint_name = con.r_constraint_name JOIN all_cons_columns rcol ON rcol.owner = rcon.owner AND rcol.table_name = rcon.table_name AND rcol.constraint_name = rcon.constraint_name WHERE con.constraint_type = 'R' AND con.owner = {s} AND con.table_name = {t} ORDER BY con.constraint_name, col.position"
@@ -719,8 +712,8 @@ pub fn routines(driver: DbDriver, schema: &str) -> Option<String> {
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
)),
DbDriver::SqlServer => Some(format!(
"SELECT r.ROUTINE_NAME, lower(r.ROUTINE_TYPE), '', r.DATA_TYPE \
FROM INFORMATION_SCHEMA.ROUTINES r WHERE r.ROUTINE_SCHEMA = {s} ORDER BY 1"
"SELECT r.routine_name, lower(r.routine_type), '', r.data_type \
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
)),
DbDriver::Snowflake => Some(format!(
"SELECT function_name, 'function', argument_signature, data_type FROM information_schema.functions \
@@ -1026,65 +1019,19 @@ mod tests {
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
assert_eq!(
schemas(DbDriver::SqlServer, true),
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1"
"SELECT schema_name FROM information_schema.schemata ORDER BY 1"
);
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest')"));
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'information_schema', 'guest')"));
}
#[test]
fn sqlserver_introspection_queries() {
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
assert!(tables(DbDriver::SqlServer, "dbo").contains("information_schema.tables"));
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("information_schema.columns"));
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
}
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
/// `INFORMATION_SCHEMA` views and their columns in upper case, `sys` views in lower case.
#[test]
fn sqlserver_catalog_names_keep_their_declared_case() {
let d = DbDriver::SqlServer;
let queries = [
schemas(d, true).to_owned(),
schemas(d, false).to_owned(),
tables(d, "dbo"),
columns(d, "dbo", "t"),
indexes(d, "dbo", "t"),
completion_columns(d).to_owned(),
foreign_keys(d).to_owned(),
table_foreign_keys(d, "dbo", "t"),
routines(d, "dbo").unwrap(),
];
const COLUMNS: [&str; 15] = [
"information_schema",
"schema_name",
"table_name",
"table_schema",
"table_type",
"column_name",
"data_type",
"is_nullable",
"column_default",
"constraint_name",
"constraint_type",
"ordinal_position",
"routine_name",
"routine_type",
"routine_schema",
];
for q in queries {
let words: Vec<&str> = q.split(|c: char| !c.is_alphanumeric() && c != '_').collect();
for (i, word) in words.iter().enumerate() {
let catalog = COLUMNS.contains(&word.to_lowercase().as_str())
|| i > 0 && words[i - 1] == "INFORMATION_SCHEMA" && !word.is_empty();
if catalog {
assert_eq!(*word, word.to_uppercase(), "{word} in {q}");
}
}
assert!(!q.contains("referenced_table_name"), "SQL Server has no referenced_* columns: {q}");
}
assert!(foreign_keys(DbDriver::SqlServer).contains("referenced_table_name IS NOT NULL"));
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("table_schema = 'dbo'"));
assert!(completion_columns(DbDriver::SqlServer).contains("information_schema.columns"));
}
#[test]
-103
View File
@@ -1,103 +0,0 @@
//! Only an explicit desktop action can trust a helper. The project file is portable;
//! the authorization belongs to this machine and to the reviewed destination.
use crate::{DataSource, DbDriver, DbExternalTunnel, DbManager, DbSslMode, local_settings::persist_local};
use ide_core::{IdeError, IdeResult};
use std::path::{Path, PathBuf};
impl DbManager {
pub fn with_local_external_tunnels(mut self, enabled: bool) -> Self {
self.local_external_tunnels = enabled;
self
}
pub(super) fn external_config<'a>(&self, source: &'a DataSource) -> IdeResult<&'a DbExternalTunnel> {
if !self.local_external_tunnels {
return Err(IdeError::invalid("External database tunnels require a local desktop project"));
}
if source.driver != DbDriver::Postgres || source.plugin_owner.is_some() || source.url_only {
return Err(IdeError::invalid(
"Use a user-managed PostgreSQL source with host and port for an external tunnel",
));
}
if source.ssh.as_ref().is_some_and(|ssh| ssh.enabled) {
return Err(IdeError::invalid("Choose either SSH or an external tunnel"));
}
if source.ssl == DbSslMode::VerifyFull {
return Err(IdeError::invalid(
"Verify Full needs the remote TLS hostname, which this tunnel transport cannot supply",
));
}
let config =
source.external_tunnel.as_ref().ok_or_else(|| IdeError::invalid("Choose an external tunnel helper"))?;
crate::external_tunnel::ExternalTunnel::validate(config, crate::tunnel_target(source))?;
Ok(config)
}
fn external_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
let config = self.external_config(source)?;
let dir = &self.global.as_ref().ok_or_else(|| IdeError::invalid("Local database settings unavailable"))?.0;
let key = serde_json::to_vec(&((!source.global).then_some(&self.root), &source.id))
.map_err(|e| IdeError::internal(e.to_string()))?;
let settings = serde_json::to_vec(&(
config,
crate::tunnel_target(source),
&source.user,
&source.database,
&source.ssl,
&source.ssl_ca_file,
&source.ssl_cert_file,
&source.ssl_key_file,
source.read_only,
&source.properties,
&source.options,
))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok((
dir.join("database-tunnel-approvals").join(blake3::hash(&key).to_hex().as_str()),
blake3::hash(&settings).to_string(),
))
}
/// Called only after the local connection dialog shows the executable, arguments and destination.
pub async fn approve_external_tunnel(&self, source: &DataSource) -> IdeResult<()> {
let (path, settings) = self.external_approval(source)?;
let program = self.external_config(source)?.executable.clone();
tokio::task::spawn_blocking(move || {
let identity = executable_identity(Path::new(&program))?;
persist_local(&path, format!("{settings}\n{identity}").as_bytes())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
pub(super) async fn check_external_approval(&self, source: &DataSource) -> IdeResult<()> {
let (path, settings) = self.external_approval(source)?;
let program = self.external_config(source)?.executable.clone();
tokio::task::spawn_blocking(move || {
let review = || {
IdeError::invalid("Review the external tunnel in SSH/SSL and save the data source before connecting")
};
let approval = std::fs::read_to_string(path).map_err(|_| review())?;
let (saved, identity) = approval.split_once('\n').ok_or_else(review)?;
// Avoid touching a program named by an unapproved project file.
if saved != settings || identity != executable_identity(Path::new(&program))? {
return Err(review());
}
Ok(())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
}
fn executable_identity(program: &Path) -> IdeResult<String> {
let path = std::fs::canonicalize(program)?;
if !path.is_file() {
return Err(IdeError::invalid("The external tunnel helper must be an executable file"));
}
let mut hash = blake3::Hasher::new();
hash.update(path.as_os_str().as_encoded_bytes());
hash.update(&[0]);
hash.update_reader(std::fs::File::open(path)?)?;
Ok(hash.finalize().to_string())
}
-24
View File
@@ -298,27 +298,3 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
}
Ok(())
}
#[tokio::test]
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
let c = CancellationToken::new();
let query = "WITH RECURSIVE n(id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM n WHERE id < 1000) \
SELECT id, REPEAT('x', 10) AS pad FROM n ORDER BY id";
// Forward, back, and jumping: every page holds its own rows whichever cursor served it.
for page in [0, 1, 2, 3, 1, 7, 8, 9, 4, 0] {
let r = db.execute_from("m", query, page * 100, 100, &c, None).await?;
let ids: Vec<_> = r.rows.iter().map(|row| row[0].clone().unwrap()).collect();
let want: Vec<_> = (page * 100 + 1..=page * 100 + 100).map(|n| n.to_string()).collect();
assert_eq!(ids, want, "page {page}");
assert_eq!(r.has_more, page < 9, "page {page}");
}
// A pool of 4 connections: cursors that were left open must not exhaust it.
for _ in 0..8 {
db.execute_from("m", query, 100, 100, &c, None).await?;
db.release_result("m", query, None);
assert_eq!(db.execute("m", "SELECT 1", 1, &c).await?.rows[0][0].as_deref(), Some("1"));
}
Ok(())
}
-230
View File
@@ -44,33 +44,6 @@ async fn create_schemas(db: &DbManager) {
}
}
#[tokio::test]
async fn postgres_read_only_is_checked_before_and_after_startup_sql() -> IdeResult<()> {
use ide_db::{DbProperty, Pool};
let Some((host, port, user, password)) = server() else { return Ok(()) };
let mut source =
DataSource { driver: DbDriver::Postgres, host, port: Some(port), user, read_only: true, ..Default::default() };
let pool = Pool::connect(&source, Some(&password), None).await?;
assert_eq!(pool.rows("SHOW transaction_read_only", 1).await?, [[Some("on".into())]]);
pool.close().await;
// Exercise the same server response as a pooler that ignored the startup option.
source.properties.push(DbProperty { name: "default_transaction_read_only".into(), value: "off".into() });
source.options.startup_script = "SELECT 1/0".into();
let err = Pool::connect(&source, Some(&password), None).await.err().expect("writable connection");
assert!(err.message.contains("did not enable the requested default_transaction_read_only"), "{}", err.message);
source.properties.clear();
source.options.startup_script = "SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE".into();
let err = Pool::connect(&source, Some(&password), None).await.err().expect("startup script disabled read-only");
assert!(err.message.contains("did not enable the requested default_transaction_read_only"), "{}", err.message);
source.options.startup_script = "BEGIN READ WRITE".into();
let err = Pool::connect(&source, Some(&password), None).await.err().expect("writable startup transaction");
assert!(err.message.contains("writable transaction"), "{}", err.message);
source.options.startup_script = "BEGIN READ ONLY".into();
Pool::connect(&source, Some(&password), None).await?.close().await;
Ok(())
}
#[tokio::test]
async fn active_schema_context_drives_the_executing_connection() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
@@ -369,206 +342,3 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
db.execute("p", "DROP DATABASE oi_restore", 1, &c).await?;
Ok(())
}
#[tokio::test]
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
let query = "SELECT g AS id, repeat('x', 10) AS pad FROM generate_series(1, 1000) g ORDER BY g";
// Forward, back, and jumping: every page holds its own rows whichever cursor served it.
for page in [0, 1, 2, 3, 1, 7, 8, 9, 4, 0] {
let r = db.execute_from("p", query, page * 100, 100, &c, None).await?;
let ids: Vec<_> = r.rows.iter().map(|row| row[0].clone().unwrap()).collect();
let want: Vec<_> = (page * 100 + 1..=page * 100 + 100).map(|n| n.to_string()).collect();
assert_eq!(ids, want, "page {page}");
assert_eq!(r.has_more, page < 9, "page {page}");
}
// A pool of 4 connections: cursors that were left open must not exhaust it.
for _ in 0..8 {
db.execute_from("p", query, 100, 100, &c, None).await?;
db.release_result("p", query, None);
assert_eq!(db.execute("p", "SELECT 1", 1, &c).await?.rows[0][0].as_deref(), Some("1"));
}
Ok(())
}
#[tokio::test]
async fn cancelling_a_later_page_stops_its_statement_on_the_server() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let marker = "oi_cursor_cancel_marker";
let slow = format!("SELECT g, pg_sleep(0.05) AS {marker} FROM generate_series(1, 100000) g");
let cancel = CancellationToken::new();
let stop = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
stop.cancel();
});
let started = std::time::Instant::now();
let e = db.execute_from("p", &slow, 5, 10, &cancel, None).await.unwrap_err();
assert_eq!(e.kind, ide_core::error::ErrorKind::Cancelled);
assert!(started.elapsed() < std::time::Duration::from_secs(5));
let c = CancellationToken::new();
let active = format!(
"SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND query LIKE '%{marker}%' \
AND query NOT LIKE '%pg_stat_activity%'"
);
let mut running = 1;
for _ in 0..20 {
running = db.execute("p", &active, 1, &c).await?.rows[0][0].as_deref().unwrap().parse().unwrap();
if running == 0 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
assert_eq!(running, 0, "the cancelled statement still runs on the server");
Ok(())
}
// The same test executable serves as a foreground TCP forwarder for the managed-route test.
#[test]
fn postgres_tunnel_fixture() {
use std::io::{Write, copy};
use std::net::{Ipv4Addr, Shutdown, TcpListener, TcpStream};
let flag = |prefix: &str| std::env::args().find_map(|s| s.strip_prefix(prefix).map(String::from));
let Some(port) = flag("listen=") else { return };
if let Some(file) = flag("waiting=") {
std::fs::write(file, port.as_bytes()).unwrap();
std::thread::sleep(std::time::Duration::from_secs(60));
return;
}
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port.parse::<u16>().unwrap())).unwrap();
let log = flag("start-log=").unwrap();
let mut file = std::fs::OpenOptions::new().append(true).create(true).open(log).unwrap();
writeln!(file, "{port}").unwrap();
let destination = flag("forward=").unwrap();
for stream in listener.incoming() {
let mut client = stream.unwrap();
let dest = destination.clone();
std::thread::spawn(move || {
let mut remote = TcpStream::connect(dest).unwrap();
let mut input = client.try_clone().unwrap();
let mut output = remote.try_clone().unwrap();
std::thread::spawn(move || {
let _ = copy(&mut input, &mut output);
let _ = output.shutdown(Shutdown::Write);
});
let _ = copy(&mut remote, &mut client);
let _ = client.shutdown(Shutdown::Write);
});
}
}
#[tokio::test]
async fn managed_tunnel_shares_the_forwarder_and_closes_it_after_the_last_target() -> IdeResult<()> {
let Some((host, port, user, password)) = server() else { return Ok(()) };
let tmp = tempfile::tempdir()?;
let root = tmp.path();
let log = root.join("starts");
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-secrets")));
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh)
.with_global_sources(root.join("app"))
.with_local_external_tunnels(true);
let source = DataSource {
id: "tunnel".into(),
name: "Tunnel fixture".into(),
driver: DbDriver::Postgres,
host,
port: Some(port),
user,
database: "postgres".into(),
read_only: true,
external_tunnel: Some(ide_db::DbExternalTunnel {
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
arguments: vec![
"--exact".into(),
"postgres_tunnel_fixture".into(),
"--skip".into(),
"listen={localPort}".into(),
"--skip".into(),
"forward={host}:{port}".into(),
"--skip".into(),
format!("start-log={}", log.display()),
],
}),
..Default::default()
};
db.save_sources(vec![source.clone()]).await?;
db.set_password("tunnel", Some(password), false).await?;
assert!(db.pool("tunnel").await.is_err());
assert!(!log.exists());
assert!(db.test_external_tunnel(&source, None).await?.contains("PostgreSQL"));
assert!(db.pool("tunnel").await.is_err(), "Test must not persist launch approval");
db.approve_external_tunnel(&source).await?;
let (a, b) = tokio::try_join!(db.pool("tunnel"), db.pool("tunnel:postgres"))?;
assert_eq!(std::fs::read_to_string(&log)?.lines().count(), 2, "one test helper and one pooled helper");
assert!(db.is_connected("tunnel") && db.is_connected("tunnel:postgres"));
drop((a, b));
db.disconnect("tunnel").await;
let result = db.execute("tunnel:postgres", "SELECT 1", 1, &CancellationToken::new()).await?;
assert_eq!(result.rows, vec![vec![Some("1".to_owned())]]);
db.disconnect_source("tunnel").await;
let ports: Vec<u16> = std::fs::read_to_string(log)?.lines().map(|p| p.parse().unwrap()).collect();
tokio::time::timeout(std::time::Duration::from_secs(5), async {
for port in ports {
while tokio::net::TcpStream::connect(("127.0.0.1", port)).await.is_ok() {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
}
})
.await
.expect("both helpers must stop");
Ok(())
}
#[tokio::test]
async fn external_startup_does_not_block_another_source_and_disconnect_cancels_it() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let dir = tmp.path();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(dir.join("ssh-secrets")));
let db = DbManager::new(dir.into(), dir.join("passwords.json"), dir.join("history.json"), ssh)
.with_global_sources(dir.join("app"))
.with_local_external_tunnels(true);
let waiting = dir.join("starting");
let pending = DataSource {
id: "pending".into(),
name: "Starting helper".into(),
driver: DbDriver::Postgres,
host: "db.example".into(),
external_tunnel: Some(ide_db::DbExternalTunnel {
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
arguments: vec![
"--exact".into(),
"postgres_tunnel_fixture".into(),
"--skip".into(),
"listen={localPort}".into(),
"--skip".into(),
format!("waiting={}", waiting.display()),
],
}),
..Default::default()
};
let file = dir.join("local.db");
std::fs::File::create(&file)?;
let sqlite =
DataSource { id: "local".into(), name: "SQLite fixture".into(), file: Some(file.into()), ..Default::default() };
db.approve_external_tunnel(&pending).await?;
db.save_sources(vec![pending, sqlite]).await?;
let connect = db.pool("pending");
let edit = async {
while !waiting.exists() {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
db.pool("local").await?;
assert!(db.is_connected("local"));
db.disconnect_source("pending").await;
Ok::<_, ide_core::IdeError>(())
};
let (result, edit) = tokio::time::timeout(std::time::Duration::from_secs(8), async { tokio::join!(connect, edit) })
.await
.expect("the pending PostgreSQL helper must not block SQLite or disconnect");
edit?;
assert!(matches!(result, Err(error) if error.kind == ide_core::error::ErrorKind::Cancelled));
Ok(())
}
-59
View File
@@ -136,62 +136,3 @@ async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
assert!(!db.databases("s").await.unwrap().names.contains(&name));
drop(held);
}
/// #5772: a case-sensitive collation resolves catalog names only in their declared case.
#[tokio::test]
async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
use ide_db::sql;
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
let parts = server.splitn(4, ':');
let source = |database: &str| DataSource {
driver: DbDriver::SqlServer,
host: parts.clone().next().unwrap().into(),
port: Some(parts.clone().nth(1).unwrap().parse().unwrap()),
user: parts.clone().nth(2).unwrap().into(),
database: database.into(),
ssl: DbSslMode::Disable,
..Default::default()
};
let password = parts.clone().nth(3);
let name = format!("oi_cs_catalog_{}", std::process::id());
let master = Pool::connect(&source("master"), password, None).await.unwrap();
master.rows(&format!("CREATE DATABASE {name} COLLATE Latin1_General_CS_AS"), 1).await.unwrap();
let pool = Pool::connect(&source(&name), password, None).await.unwrap();
pool.rows("CREATE TABLE dbo.Parent (Id int PRIMARY KEY)", 1).await.unwrap();
pool.rows("CREATE TABLE dbo.Child (Id int PRIMARY KEY, ParentId int CONSTRAINT FK_Child_Parent REFERENCES dbo.Parent (Id))", 1)
.await
.unwrap();
pool.rows("CREATE VIEW dbo.Kids AS SELECT Id FROM dbo.Child", 1).await.unwrap();
pool.rows("CREATE PROCEDURE dbo.Touch AS SELECT 1", 1).await.unwrap();
let d = DbDriver::SqlServer;
let cells = |rows: Vec<Vec<Option<String>>>| -> Vec<Vec<String>> {
rows.into_iter().map(|r| r.into_iter().map(Option::unwrap_or_default).collect()).collect()
};
let schemas = cells(pool.rows(sql::schemas(d, false), 100).await.unwrap());
assert!(schemas.contains(&vec!["dbo".to_owned()]));
assert!(!schemas.iter().any(|s| s[0] == "INFORMATION_SCHEMA" || s[0] == "sys"));
assert!(
cells(pool.rows(sql::schemas(d, true), 100).await.unwrap()).contains(&vec!["INFORMATION_SCHEMA".to_owned()])
);
assert_eq!(
cells(pool.rows(&sql::tables(d, "dbo"), 100).await.unwrap()),
[["Child", "table"], ["Kids", "view"], ["Parent", "table"]]
);
assert_eq!(
cells(pool.rows(&sql::columns(d, "dbo", "Child"), 100).await.unwrap())
.iter()
.map(|c| (c[0].as_str(), c[4].as_str()))
.collect::<Vec<_>>(),
[("Id", "1"), ("ParentId", "0")]
);
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
drop(pool);
master
.rows(&format!("ALTER DATABASE {name} SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE {name}"), 1)
.await
.unwrap();
}
-56
View File
@@ -557,53 +557,6 @@ fn map_layers(layers: Vec<ApiLayer>, now: i64) -> Vec<DockerImageLayer> {
.collect()
}
/// Per-volume disk usage (`GET /system/df?type=volume`).
pub(crate) fn volume_sizes(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<BTreeMap<String, String>>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", "/system/df?type=volume", timeout)?)?;
map_volume_sizes(&body)
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiDiskUsage {
volumes: Option<Vec<ApiVolumeUsage>>,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiVolumeUsage {
name: String,
usage_data: Option<ApiVolumeUsageData>,
}
const fn unknown_volume_size() -> i64 {
-1
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiVolumeUsageData {
#[serde(default = "unknown_volume_size")]
size: i64,
}
fn map_volume_sizes(body: &str) -> IdeResult<BTreeMap<String, String>> {
let parsed = serde_json::from_str::<ApiDiskUsage>(body)
.map_err(|e| IdeError::internal(format!("the Docker daemon's disk usage is not JSON: {e}")))?;
Ok(parsed
.volumes
.unwrap_or_default()
.into_iter()
.filter_map(|v| {
let size = v.usage_data?.size;
(!v.name.is_empty() && size >= 0).then(|| (v.name, human_size(size)))
})
.collect())
}
fn unix_now() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}
@@ -1205,15 +1158,6 @@ mod tests {
(top.titles, top.processes),
(vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]])
);
let sizes = map_volume_sizes(
r#"{"Volumes":[{"Name":"shop_pgdata","UsageData":{"RefCount":1,"Size":145442}},{"Name":"empty","UsageData":{"RefCount":0,"Size":0}},{"Name":"remote","UsageData":{"RefCount":1,"Size":-1}},{"Name":"missing","UsageData":null}]}"#,
)
.unwrap();
assert_eq!(sizes.get("shop_pgdata").map(String::as_str), Some("145.442kB"));
assert_eq!(sizes.get("empty").map(String::as_str), Some("0B"));
assert!(!sizes.contains_key("remote"));
assert!(!sizes.contains_key("missing"));
assert!(map_volume_sizes(r#"{"Volumes":null}"#).unwrap().is_empty());
}
#[test]
-11
View File
@@ -315,17 +315,6 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
}
/// Per-volume disk usage (`docker system df -v --format '{{json .Volumes}}'`).
pub fn volume_sizes(ep: &DockerEndpoint) -> IdeResult<std::collections::BTreeMap<String, String>> {
if docker_executable().is_none()
&& let Some(sizes) = engine::volume_sizes(ep, QUICK)
{
return sizes;
}
let out = run(ep, &["system", "df", "-v", "--format", "{{json .Volumes}}"], QUICK)?;
Ok(parse_volume_sizes(&out))
}
/// How long log lines collect before they are handed on together.
const LOG_BATCH: Duration = Duration::from_millis(30);
-27
View File
@@ -473,33 +473,6 @@ pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
})
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawVolumeUsage {
name: String,
size: String,
}
/// `docker system df -v --format '{{json .Volumes}}'` volume name → human size.
pub fn parse_volume_sizes(text: &str) -> BTreeMap<String, String> {
let trimmed = text.trim();
let items: Vec<RawVolumeUsage> = if trimmed.is_empty() || trimmed == "null" {
Vec::new()
} else if let Ok(parsed) = serde_json::from_str::<Option<Vec<RawVolumeUsage>>>(trimmed) {
parsed.unwrap_or_default()
} else {
lines::<RawVolumeUsage>(text).collect()
};
items
.into_iter()
.filter(|v| {
let size = v.size.trim();
!v.name.is_empty() && !size.is_empty() && !size.eq_ignore_ascii_case("n/a")
})
.map(|v| (v.name, v.size.trim().to_owned()))
.collect()
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct RawVersion {
+1 -9
View File
@@ -2,7 +2,7 @@
use ide_docker::{
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
parse_networks, parse_volume_sizes, parse_volumes,
parse_networks, parse_volumes,
};
const PS: &str = include_str!("fixtures/ps.jsonl");
@@ -113,12 +113,4 @@ fn image_history_top_and_stats() {
assert_eq!(stats.net_io, "12kB / 8kB");
assert_eq!(stats.block_io, "1.2MB / 0B");
assert_eq!(stats.pids, "14");
let df_volumes = r#"[{"Availability":"N/A","Driver":"local","Links":"4","Mountpoint":"/var/lib/docker/volumes/selfhost_runner-persist/_data","Name":"selfhost_runner-persist","Scope":"local","Size":"145.4kB"},{"Name":"unused_anon","Size":"0B"},{"Name":"remote_nfs","Size":"N/A"}]"#;
let volume_sizes = parse_volume_sizes(df_volumes);
assert_eq!(volume_sizes.get("selfhost_runner-persist").map(String::as_str), Some("145.4kB"));
assert_eq!(volume_sizes.get("unused_anon").map(String::as_str), Some("0B"));
assert!(!volume_sizes.contains_key("remote_nfs"));
assert!(parse_volume_sizes("null\n").is_empty());
assert!(parse_volume_sizes("").is_empty());
}
+1 -1
View File
@@ -34,7 +34,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.16.0";
pub const ENGINE_VERSION: &str = "1.15.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.
+194 -43
View File
@@ -1,34 +1,23 @@
//! One `dart devtools` server per project window. In `--machine` mode it reports its port as a
//! `server.started` line on stdout.
//! One `dart devtools` server per project window, started when first asked for. In `--machine`
//! mode it reports its port as a `server.started` line on stdout. A server that fails or exits
//! is not restarted on its own: the next request starts a new one.
use crate::flutter_executable;
use crate::server::{Line, Spec, ToolServer};
use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched};
use ide_core::process::{kill_tree, terminate_tree};
use ide_core::tool_path::{find_command, search_path_in};
use parking_lot::{Condvar, Mutex};
use serde_json::Value;
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::process::Child;
use std::sync::Arc;
use std::time::{Duration, Instant};
const START_TIMEOUT: Duration = Duration::from_secs(60);
/// The address embedded pages are allowed to come from, so never `localhost`.
pub(crate) const HOST: &str = "127.0.0.1";
const HOST: &str = "127.0.0.1";
const ARGS: [&str; 7] = ["devtools", "--machine", "--allow-embedding", "--host", HOST, "--port", "0"];
pub(crate) static DEVTOOLS: Spec = Spec {
name: "Flutter DevTools",
args: &ARGS,
timeout: Duration::from_secs(60),
executable: dart_executable,
not_found: "Dart SDK not found: install Flutter or add it to PATH",
line,
failed: |message| if message.is_empty() { "dart devtools exited".into() } else { message },
};
impl ToolServer {
/// `dart` is the configured one, else the one of the `flutter` on the search path.
pub fn devtools(root: PathBuf, dart: crate::Configured) -> Self {
Self::new(root, &DEVTOOLS, dart)
}
}
fn started_port(line: &str) -> Option<u16> {
let message: Value = serde_json::from_str(line.trim()).ok()?;
if message.get("event")?.as_str()? != "server.started" {
@@ -37,23 +26,186 @@ fn started_port(line: &str) -> Option<u16> {
u16::try_from(message.get("params")?.get("port")?.as_u64()?).ok()
}
fn line(line: &str) -> Line {
match started_port(line) {
Some(port) => Line::Url(format!("http://{HOST}:{port}")),
None => Line::Output(line.to_owned()),
}
}
/// The `dart` of the SDK `flutter` belongs to, so that DevTools matches the debugged app.
fn dart_executable(root: &Path) -> Option<PathBuf> {
flutter_executable(root)
let path = search_path_in(root);
find_command("flutter", &path, root)
.and_then(|flutter| {
// On the search path `flutter` is often a link into the SDK.
let flutter = if cfg!(unix) { std::fs::canonicalize(&flutter).unwrap_or(flutter) } else { flutter };
let dart = flutter.with_file_name(if cfg!(windows) { "dart.bat" } else { "dart" });
dart.is_file().then_some(dart)
})
.or_else(|| find_command("dart", &search_path_in(root), root))
.or_else(|| find_command("dart", &path, root))
}
#[derive(Default)]
enum Status {
#[default]
Stopped,
Starting,
Ready(String),
Failed(String),
}
#[derive(Default)]
struct State {
/// Bumped by every start and stop: a reader of an older process no longer has a say.
generation: u64,
child: Option<Child>,
status: Status,
}
impl State {
fn shut_down(&mut self) {
self.generation += 1;
if let Some(mut child) = self.child.take() {
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
}
}
}
struct Shared {
root: PathBuf,
/// Replaces the lookup on the search path (tests).
executable: Option<PathBuf>,
timeout: Duration,
state: Mutex<State>,
changed: Condvar,
}
impl Shared {
/// Applies `status` unless this process was replaced or stopped; false if it was.
fn set(&self, generation: u64, status: Status) -> bool {
let mut state = self.state.lock();
if state.generation != generation {
return false;
}
state.status = status;
self.changed.notify_all();
true
}
}
pub struct DevToolsServer(Arc<Shared>);
impl DevToolsServer {
pub fn new(root: PathBuf) -> Self {
Self::with_executable(root, None, START_TIMEOUT)
}
fn with_executable(root: PathBuf, executable: Option<PathBuf>, timeout: Duration) -> Self {
Self(Arc::new(Shared { root, executable, timeout, state: Mutex::default(), changed: Condvar::new() }))
}
/// The server's address, starting it if none runs. Blocks until it is known.
pub fn url(&self) -> Result<String, String> {
let shared = &self.0;
let deadline = Instant::now() + shared.timeout;
let mut state = shared.state.lock();
if matches!(state.status, Status::Stopped | Status::Failed(_)) {
state.generation += 1;
state.status = Status::Starting;
let (shared, generation) = (shared.clone(), state.generation);
std::thread::spawn(move || run(&shared, generation));
}
loop {
match &state.status {
Status::Ready(url) => return Ok(url.clone()),
Status::Failed(message) => return Err(message.clone()),
Status::Stopped => return Err("Flutter DevTools was stopped".into()),
Status::Starting => {}
}
if shared.changed.wait_until(&mut state, deadline).timed_out() {
state.shut_down();
let message = "Flutter DevTools did not start in time".to_owned();
state.status = Status::Failed(message.clone());
shared.changed.notify_all();
return Err(message);
}
}
}
/// Ends the server (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
state.shut_down();
state.status = Status::Stopped;
self.0.changed.notify_all();
}
/// Ends the server before returning, for a process about to exit.
pub fn kill(&self) {
let mut state = self.0.state.lock();
state.generation += 1;
state.status = Status::Stopped;
if let Some(mut child) = state.child.take() {
kill_tree(&mut child);
}
self.0.changed.notify_all();
}
}
/// One server's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64) {
let fail = |message: String| {
shared.set(generation, Status::Failed(message));
};
let Some(executable) = shared.executable.clone().or_else(|| dart_executable(&shared.root)) else {
return fail("Dart SDK not found: install Flutter or add it to PATH".into());
};
let mut child = match spawn_watched(&executable, &ARGS, &shared.root) {
Ok(child) => child,
Err(e) => return fail(format!("could not run {}: {e}", executable.display())),
};
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
terminate_tree(&mut child, Duration::ZERO);
return fail("no output pipe".into());
};
{
let mut state = shared.state.lock();
if state.generation != generation {
drop(state);
terminate_tree(&mut child, KILL_GRACE);
return;
}
state.child = Some(child);
}
let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL)));
let errors = {
let tail = tail.clone();
std::thread::spawn(move || {
read_lines(stderr, |line| {
keep_output(&tail, line);
true
});
})
};
read_lines(stdout, |line| match started_port(line) {
Some(port) => shared.set(generation, Status::Ready(format!("http://{HOST}:{port}"))),
None => {
keep_output(&tail, line);
true
}
});
let _ = errors.join();
let mut state = shared.state.lock();
if state.generation != generation {
return;
}
let child = state.child.take();
state.status = if matches!(state.status, Status::Ready(_)) {
Status::Stopped
} else {
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
Status::Failed(if message.is_empty() { "dart devtools exited".into() } else { message })
};
shared.changed.notify_all();
drop(state);
if let Some(mut child) = child {
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
}
}
#[cfg(test)]
@@ -73,15 +225,14 @@ mod tests {
mod process {
use super::*;
use std::os::unix::fs::PermissionsExt;
use std::time::Instant;
const STARTED: &str = r#"echo '{"event":"server.started","params":{"port":4242}}'"#;
fn server(dir: &Path, script: &str, timeout: Duration) -> ToolServer {
fn server(dir: &Path, script: &str, timeout: Duration) -> DevToolsServer {
let path = dir.join("dart");
std::fs::write(&path, format!("#!/bin/sh\necho run >> runs\n{script}")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
ToolServer::with_executable(dir.to_owned(), &DEVTOOLS, Box::new(move || Some(path.clone())), timeout)
DevToolsServer::with_executable(dir.to_owned(), Some(path), timeout)
}
fn runs(dir: &Path) -> usize {
@@ -101,8 +252,8 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let script = format!("echo \"$*\" > args\necho $$ > pid\n{STARTED}\nexec sleep 30");
let devtools = server(dir.path(), &script, Duration::from_secs(10));
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
assert_eq!(runs(dir.path()), 1);
let args = std::fs::read_to_string(dir.path().join("args")).unwrap();
assert_eq!(args.trim(), ARGS.join(" "));
@@ -120,10 +271,10 @@ mod tests {
fn a_failure_is_reported_and_only_a_new_request_retries() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), "echo boom >&2\nexit 3", Duration::from_secs(10));
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
assert_eq!(devtools.url().unwrap_err(), "boom");
std::thread::sleep(Duration::from_millis(100));
assert_eq!(runs(dir.path()), 1);
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
assert_eq!(devtools.url().unwrap_err(), "boom");
assert_eq!(runs(dir.path()), 2);
}
@@ -131,10 +282,10 @@ mod tests {
fn a_server_that_exits_is_not_restarted_until_asked() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), STARTED, Duration::from_secs(10));
devtools.url(&[]).unwrap();
wait_for("the exit to be noticed", || devtools.is_stopped());
devtools.url().unwrap();
wait_for("the exit to be noticed", || matches!(devtools.0.state.lock().status, Status::Stopped));
assert_eq!(runs(dir.path()), 1);
devtools.url(&[]).unwrap();
devtools.url().unwrap();
assert_eq!(runs(dir.path()), 2);
}
@@ -142,7 +293,7 @@ mod tests {
fn a_server_that_never_reports_times_out() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), "exec sleep 30", Duration::from_millis(200));
assert_eq!(devtools.url(&[]).unwrap_err(), "Flutter DevTools did not start in time");
assert_eq!(devtools.url().unwrap_err(), "Flutter DevTools did not start in time");
}
}
}
+21 -201
View File
@@ -3,38 +3,31 @@
//! The daemon speaks JSON-RPC over stdio, one bracketed message per line. After
//! `daemon.connected` it is asked for `device.enable`, which makes it report `device.added` /
//! `device.removed`, and once for `device.getDevices`, whose answer ends the "discovering" state.
//! `emulator.getEmulators` lists what can be started, then and whenever the chooser opens.
//!
//! The daemon keeps running after its stdin closes, so closing the pipe does not end it: on Unix
//! a watcher in its process group ends the group once the IDE is gone, even after a crash. A
//! daemon that fails stays failed until the user restarts it.
mod devtools;
mod server;
mod widget_preview;
pub use server::ToolServer;
pub use devtools::DevToolsServer;
use ide_android::AndroidDevice;
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList, FlutterEmulator};
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList};
use ide_core::process::{kill_tree, own_group, prepare, terminate_tree};
use ide_core::tool_path::{find_command, search_path_in};
use ide_core::{IdeEvent, SharedSink};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::collections::{BTreeMap, VecDeque};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use std::sync::mpsc;
use std::time::Duration;
const ENABLE: u64 = 1;
const GET_DEVICES: u64 = 2;
const GET_EMULATORS: u64 = 3;
/// `emulator.launch` waits for `xcrun simctl` or similar; past this the daemon is stuck.
const LAUNCH_TIMEOUT: Duration = Duration::from_secs(60);
/// How long the daemon gets to exit on `SIGTERM`.
const KILL_GRACE: Duration = Duration::from_millis(200);
/// Lines of unrecognised output kept to explain a failure.
@@ -46,9 +39,6 @@ enum Message {
Added(FlutterDevice),
Removed(String),
Devices(Vec<FlutterDevice>),
Emulators(Vec<FlutterEmulator>),
/// The answer to a request of ours other than the ones above.
Response(u64, Result<(), String>),
Other,
}
@@ -61,15 +51,9 @@ fn device(value: &Value) -> Option<FlutterDevice> {
category: text("category"),
emulator: value.get("emulator").and_then(Value::as_bool).unwrap_or(false),
unavailable: None,
emulator_id: text("emulatorId"),
})
}
fn emulator(value: &Value) -> Option<FlutterEmulator> {
let text = |key| value.get(key).and_then(Value::as_str).map(str::to_owned);
Some(FlutterEmulator { id: text("id")?, name: text("name")?, platform_type: text("platformType") })
}
/// The messages of one stdout line; `None` for anything outside the protocol (the tool's own
/// chatter, such as waiting for the startup lock).
fn parse_line(line: &str) -> Option<Vec<Message>> {
@@ -90,23 +74,11 @@ fn parse_message(message: &Value) -> Message {
params.get("id").and_then(Value::as_str).map_or(Message::Other, |id| Message::Removed(id.to_owned()))
}
Some(_) => Message::Other,
None => {
let result = message.get("result").and_then(Value::as_array).into_iter().flatten();
match message.get("id").and_then(Value::as_u64) {
Some(ENABLE) | None => Message::Other,
Some(GET_DEVICES) => Message::Devices(result.filter_map(device).collect()),
// A failure (no Android SDK, no Xcode) lists none.
Some(GET_EMULATORS) => Message::Emulators(result.filter_map(emulator).collect()),
Some(id) => Message::Response(
id,
match message.get("error") {
None | Some(Value::Null) => Ok(()),
Some(Value::String(error)) => Err(error.clone()),
Some(error) => Err(error.to_string()),
},
),
}
None if message.get("id").and_then(Value::as_u64) == Some(GET_DEVICES) => {
let result = message.get("result").and_then(Value::as_array);
Message::Devices(result.into_iter().flatten().filter_map(device).collect())
}
None => Message::Other,
}
}
@@ -114,12 +86,6 @@ fn request(id: u64, method: &str) -> String {
format!("{}\n", json!([{ "id": id, "method": method }]))
}
/// The emulators no device runs on.
fn idle_emulators(emulators: &[FlutterEmulator], devices: &BTreeMap<String, FlutterDevice>) -> Vec<FlutterEmulator> {
let running = |e: &FlutterEmulator| devices.values().any(|d| d.emulator_id.as_ref() == Some(&e.id));
emulators.iter().filter(|e| !running(e)).cloned().collect()
}
/// The daemon's devices, plus the Android devices adb sees that Flutter leaves out until they
/// are usable. A daemon Android device's id is its adb serial.
fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Vec<FlutterDevice> {
@@ -131,7 +97,6 @@ fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Ve
category: Some("mobile".into()),
emulator: d.serial.starts_with("emulator-"),
unavailable: Some(d.state.clone()),
emulator_id: None,
}));
let rank = |d: &FlutterDevice| match d.category.as_deref() {
Some("mobile") => 0,
@@ -156,30 +121,15 @@ struct State {
status: FlutterDaemonStatus,
devices: BTreeMap<String, FlutterDevice>,
adb: Vec<AndroidDevice>,
emulators: Vec<FlutterEmulator>,
/// Requests awaiting their answer; dropped with the daemon, which fails them.
pending: HashMap<u64, mpsc::Sender<Result<(), String>>>,
next_id: u64,
}
impl State {
fn list(&self) -> FlutterDeviceList {
FlutterDeviceList {
status: self.status.clone(),
devices: merged(&self.devices, &self.adb),
emulators: idle_emulators(&self.emulators, &self.devices),
}
}
/// Writes `requests` to the daemon; false without one.
fn send(&mut self, requests: &str) -> bool {
let Some(stdin) = self.running.as_mut().and_then(|r| r.stdin.as_mut()) else { return false };
stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush()).is_ok()
FlutterDeviceList { status: self.status.clone(), devices: merged(&self.devices, &self.adb) }
}
fn shut_down(&mut self) {
self.generation += 1;
self.pending.clear();
if let Some(Running { mut child, stdin }) = self.running.take() {
drop(stdin);
// Off the caller's thread: closing a window must not wait for the grace period.
@@ -191,7 +141,8 @@ impl State {
struct Shared {
root: PathBuf,
sink: SharedSink,
executable: Configured,
/// Replaces the lookup on the search path (tests).
executable: Option<PathBuf>,
state: Mutex<State>,
}
@@ -201,21 +152,16 @@ impl Shared {
}
}
/// The configured `flutter` / `dart` (the Flutter SDK setting), asked at each start; `None`
/// looks it up on the search path.
pub type Configured = Box<dyn Fn() -> Option<PathBuf> + Send + Sync>;
/// One project window's `flutter daemon`, started on first use.
pub struct FlutterDaemon(Arc<Shared>);
impl FlutterDaemon {
pub fn new(root: PathBuf, sink: SharedSink, executable: Configured) -> Self {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
pub fn new(root: PathBuf, sink: SharedSink) -> Self {
Self::with_executable(root, sink, None)
}
#[cfg(all(test, unix))]
fn with_executable(root: PathBuf, sink: SharedSink, executable: Option<PathBuf>) -> Self {
Self::new(root, sink, Box::new(move || executable.clone()))
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
}
/// The current list; starts the daemon unless it already ran. Never blocks on the process.
@@ -235,57 +181,12 @@ impl FlutterDaemon {
state.list()
}
/// Reads adb again (a device awaiting authorization changes no daemon event) and asks the
/// daemon for its emulators again (one may have been created since).
/// Reads adb again: a device awaiting authorization changes no daemon event.
pub fn refresh(&self) {
let mut state = self.0.state.lock();
if state.status == FlutterDaemonStatus::Ready {
state.send(&request(GET_EMULATORS, "emulator.getEmulators"));
}
let generation = state.generation;
drop(state);
let generation = self.0.state.lock().generation;
refresh_adb(&self.0, generation);
}
/// Starts an emulator the list offers; it shows up as a device once booted. Blocks until the
/// launch is under way. An AVD is started by `ide-android` rather than the daemon, which
/// would make it a child of its process group and end it with the daemon.
pub fn launch_emulator(&self, id: &str) -> Result<(), String> {
let mut state = self.0.state.lock();
let android = state.emulators.iter().any(|e| e.id == id && e.platform_type.as_deref() == Some("android"));
if android {
drop(state);
return ide_android::launch_emulator(id).map_err(|e| e.message);
}
state.next_id = state.next_id.max(GET_EMULATORS) + 1;
let request_id = state.next_id;
let (tx, rx) = mpsc::channel();
state.pending.insert(request_id, tx);
let params = json!({ "emulatorId": id });
let line = format!("{}\n", json!([{ "id": request_id, "method": "emulator.launch", "params": params }]));
if !state.send(&line) {
state.pending.remove(&request_id);
return Err("the Flutter daemon is not running".into());
}
drop(state);
let answer = rx.recv_timeout(LAUNCH_TIMEOUT);
self.0.state.lock().pending.remove(&request_id);
match answer {
Ok(result) => result,
Err(mpsc::RecvTimeoutError::Timeout) => Err("the Flutter daemon did not answer".into()),
Err(mpsc::RecvTimeoutError::Disconnected) => Err("the Flutter daemon exited".into()),
}
}
/// Starts a running daemon again, with the SDK the settings now choose.
pub fn sdk_changed(&self) {
let mut state = self.0.state.lock();
if state.status != FlutterDaemonStatus::Stopped {
state.shut_down();
start(&self.0, &mut state);
}
}
/// Ends the daemon (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
@@ -293,7 +194,6 @@ impl FlutterDaemon {
state.status = FlutterDaemonStatus::Stopped;
state.devices.clear();
state.adb.clear();
state.emulators.clear();
}
/// Ends the daemon before returning, for a process about to exit.
@@ -311,7 +211,6 @@ fn start(shared: &Arc<Shared>, state: &mut State) {
state.status = FlutterDaemonStatus::Starting;
state.devices.clear();
state.adb.clear();
state.emulators.clear();
let (shared, generation) = (shared.clone(), state.generation);
std::thread::spawn(move || run(&shared, generation));
}
@@ -366,7 +265,6 @@ fn finish(shared: &Shared, generation: u64, status: FlutterDaemonStatus) {
return;
}
let running = state.running.take();
state.pending.clear();
state.status = status;
let list = state.list();
drop(state);
@@ -400,14 +298,10 @@ fn read_lines(pipe: impl Read, mut on_line: impl FnMut(&str) -> bool) {
}
}
/// The `flutter` that commands run in `root` use.
fn flutter_executable(root: &Path) -> Option<PathBuf> {
find_command("flutter", &search_path_in(root), root)
}
/// One daemon's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64) {
let executable = (shared.executable)().or_else(|| flutter_executable(&shared.root));
let executable =
shared.executable.clone().or_else(|| find_command("flutter", &search_path_in(&shared.root), &shared.root));
let Some(executable) = executable else {
return finish(shared, generation, FlutterDaemonStatus::NotInstalled);
};
@@ -464,25 +358,12 @@ fn handle(shared: &Arc<Shared>, generation: u64, message: Message) -> bool {
match message {
Message::Other => return true,
Message::Connected => {
state.send(
&(request(ENABLE, "device.enable")
+ &request(GET_DEVICES, "device.getDevices")
+ &request(GET_EMULATORS, "emulator.getEmulators")),
);
return true;
}
Message::Response(id, result) => {
if let Some(tx) = state.pending.remove(&id) {
let _ = tx.send(result);
if let Some(stdin) = state.running.as_mut().and_then(|r| r.stdin.as_mut()) {
let requests = request(ENABLE, "device.enable") + &request(GET_DEVICES, "device.getDevices");
let _ = stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush());
}
return true;
}
Message::Emulators(emulators) => {
if state.emulators == emulators {
return true;
}
state.emulators = emulators;
}
Message::Added(device) => {
state.devices.insert(device.id.clone(), device);
}
@@ -514,7 +395,6 @@ mod tests {
category: Some(category.into()),
emulator,
unavailable: None,
emulator_id: None,
}
}
@@ -553,33 +433,6 @@ mod tests {
let Some([Message::Devices(devices)]) = answer.as_deref() else { panic!("{answer:?}") };
assert_eq!((devices[0].id.as_str(), devices[0].category.as_deref()), ("chrome", None));
assert_eq!(parse_line(r#"[{"id":1,"result":null}]"#), Some(vec![Message::Other]));
let emulators = parse_line(
r#"[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]"#,
);
let Some([Message::Emulators(emulators)]) = emulators.as_deref() else { panic!("{emulators:?}") };
assert_eq!(
(emulators[0].id.as_str(), emulators[0].platform_type.as_deref()),
("apple_ios_simulator", Some("ios"))
);
assert_eq!(
parse_line(r#"[{"id":3,"error":"Unable to find Android SDK","trace":""}]"#),
Some(vec![Message::Emulators(vec![])])
);
assert_eq!(parse_line(r#"[{"id":7,"result":null}]"#), Some(vec![Message::Response(7, Ok(()))]));
assert_eq!(
parse_line(r#"[{"id":7,"error":"emulator 'x' not found","trace":"..."}]"#),
Some(vec![Message::Response(7, Err("emulator 'x' not found".into()))])
);
}
#[test]
fn offers_only_the_emulators_no_device_runs_on() {
let emulator = |id: &str| FlutterEmulator { id: id.into(), name: id.into(), platform_type: None };
let mut pixel = dev("emulator-5554", "Pixel", "mobile", true);
pixel.emulator_id = Some("Pixel_9".into());
let devices: BTreeMap<_, _> = [(pixel.id.clone(), pixel)].into_iter().collect();
let idle = idle_emulators(&[emulator("Pixel_9"), emulator("apple_ios_simulator")], &devices);
assert_eq!(idle, [emulator("apple_ios_simulator")]);
}
#[test]
@@ -645,9 +498,8 @@ mod tests {
echo $$ > pid
echo 'Waiting for another flutter command to release the startup lock...'
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
read enable; read get; read emulators; echo "$enable$get$emulators" > requests
read enable; read get; echo "$enable$get" > requests
echo '[{"id":1,"result":null}]'
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]'
echo '[{"id":2,"result":[{"id":"macos","name":"macOS","category":"desktop","emulator":false}]}]'
echo '[{"event":"device.added","params":{"id":"chrome","name":"Chrome","category":"web","emulator":false}}]'
echo '[{"event":"device.removed","params":{"id":"macos","name":"macOS"}}]'
@@ -666,8 +518,6 @@ cat > /dev/null
});
let requests = std::fs::read_to_string(dir.path().join("requests")).unwrap();
assert!(requests.contains("device.enable") && requests.contains("device.getDevices"), "{requests}");
assert!(requests.contains("emulator.getEmulators"), "{requests}");
assert_eq!(daemon.devices().emulators[0].name, "iOS Simulator");
assert!(lists.0.lock().iter().any(|l| l.devices.iter().any(|d| d.id == "macos")));
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
@@ -679,36 +529,6 @@ cat > /dev/null
assert_eq!(daemon.0.state.lock().status, FlutterDaemonStatus::Stopped);
}
#[test]
fn launches_an_emulator_through_the_daemon_and_reports_its_error() {
let dir = tempfile::tempdir().unwrap();
let script = r#"
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
read enable; read get; read emulators
echo '[{"id":2,"result":[]}]'
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","platformType":"ios"}]}]'
read launch; echo "$launch" > launch
echo '[{"id":4,"result":null}]'
read launch
echo '[{"id":5,"error":"Unable to run Simulator: xcrun not found","trace":""}]'
cat > /dev/null
"#;
let (daemon, _lists) = daemon(dir.path(), script);
daemon.devices();
wait_for("the emulators", || !daemon.devices().emulators.is_empty());
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Ok(()));
let launch = std::fs::read_to_string(dir.path().join("launch")).unwrap();
let launch: Value = serde_json::from_str(&launch).unwrap();
assert_eq!(launch[0]["method"], "emulator.launch");
assert_eq!(launch[0]["params"], json!({ "emulatorId": "apple_ios_simulator" }));
assert_eq!(
daemon.launch_emulator("apple_ios_simulator"),
Err("Unable to run Simulator: xcrun not found".into())
);
daemon.stop();
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Err("the Flutter daemon is not running".into()));
}
#[test]
fn the_daemon_does_not_outlive_the_ide() {
let dir = tempfile::tempdir().unwrap();
Loaded 100 of 1349 files, more files were not shown because too many files have changed in this diff. Show more