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

...
51 Коміти
Автор SHA1 Повідомлення Дата
l0ng-ai a971483162 fix(ci): Drop a stale Chinese catalog entry and unix-only imports on Windows
The Solarized dark variant's description no longer appears in the source, so the
catalog check failed on its leftover translation. LaunchError and Launcher are
only used by the unix-only tcp_server tests and were unused imports on Windows.
2026-10-27 18:17:06 +08:00
l0ng-ai 2616e3fe6d fix(i18n): Translate missing Chinese UI text and guard the text catalog (#93)
The source-text catalog (locales/text/zh.json) is keyed by the English text, so reworded or new UI strings silently fell back to English (e.g. the language server JDK hint on the Java settings page). Adds the 321 missing Chinese translations, updates the 3 reworded keys, removes 45 stale keys, and makes the file-refactoring failure titles translatable.

New guard test (src/platform/locales/textCatalog.test.ts) parses src/ for literals that reach the translation layer and fails on missing or stale catalog entries, with an explicit allowlist for untranslated text.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 18:04:35 +08:00
l0ng-ai b5bd8e3935 chore: v0.1.17 2026-10-27 17:58:55 +08:00
l0ng-aiтаbghtyu 24330192c0 feat(themes): Solarized and One theme plugins (#92)
Solarized Light/Dark and One Light/Dark ship as theme plugins (plugins/theme-solarized, plugins/theme-one) with complete UI tokens, editor schemes and terminal colours, and the original palettes' MIT notices. Installing a plugin now also copies its LICENSE/NOTICE/COPYING.

Theme handling that benefits every plugin theme:
- The last plugin theme is restored before first paint (splash, workbench); the native window background follows the theme.
- HSL / color-mix() / var() colours are resolved to RGB for native windows, the Settings window and Mermaid.
- Mermaid, the terminal and editor schemes follow switches between two themes of the same kind.
- An explicitly chosen editor scheme wins over a plugin theme's editor colours.

Supersedes #85.

Co-authored-by: bghtyu <[email protected]>
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 17:53:07 +08:00
l0ng-ai 9d8280104f fix(agents): Run Codex through @agentclientprotocol/codex-acp
@zed-industries/codex-acp is archived; its last release (0.16.0) bundles an
older Codex core that doesn't know newer models, so a config.toml model such as
gpt-6.1-sol fell back to generic metadata with a warning. The maintained adapter,
@agentclientprotocol/codex-acp, runs the Codex App Server from a current
@openai/codex and lists the account's models.
2026-10-27 17:44:04 +08:00
l0ng-ai 8ec35c94ec fix(lsp): Find usages in unopened files outside the language server's scope (#89)
Reference-based features only asked the language server, which analyses its configured scope (e.g. Pyright's `include`) plus open files, so usages in unopened files outside that scope were silently missing.

Find Usages, Show Usages, usage counts, Safe Delete of a symbol, Rename and incoming calls now also search project files that contain the symbol's name (whole word, same language, .gitignore/excludes respected, unsaved edits included, up to 300 files, cancellable). Candidates the first answer didn't cover are opened in the server temporarily, queried and closed again. Files the user has open are never touched, and diagnostics for the temporary files are dropped. An empty result while the server is still indexing is retried once indexing ends. When results may still be incomplete (indexing, file cap), the usages UI says so. `lsp_references` takes a RequestId and is cancelled by newer searches. Not covered yet: the Safe Delete scan when deleting a file or directory.

Fixes #83

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 17:41:20 +08:00
l0ng-ai 482f391fd1 fix(splash): Draw the wordmark as outlines so it can't swap fonts
The splash set its wordmark in Inter, a web font with font-display: swap. When
the font arrived late (on a cold dev start the dev server took up to seconds to
serve it), the splash showed the system font first and switched to Inter just
before fading, so the word grew and shifted. It is now an inline SVG of the same
text in Inter 500, so it renders identically from the first frame. This replaces
the previous attempt, which only moved where the font faces load.
2026-10-27 17:35:37 +08:00
l0ng-ai 866af3d9cb fix(agents): Give child processes the login shell's environment
An app started from Finder or the Dock took only PATH from the login shell, so
variables exported in rc files never reached agents, language servers, run
configurations or debug targets. Claude Code configured for Bedrock through
CLAUDE_CODE_USE_BEDROCK / AWS_REGION in ~/.zshrc fell back to the Anthropic API
and failed with 403.

The shell's environment is read once at startup (in the background when PATH
comes from the cache) and kept in memory only, since it may hold secrets. Spawns
add the variables this process lacks before their own.
2026-10-27 17:16:47 +08:00
l0ng-ai 145f168525 fix(agents): Composer input-method Enter, autocorrect and task header layout
- Enter that commits an input-method candidate no longer sends the message.
- The composer turns off autocorrect, autocapitalisation and spellcheck, which
  popped up correction bubbles over prompts.
- The provider icon in the task header sits inline with the details instead of
  on its own line above them.
2026-10-27 17:16:46 +08:00
l0ng-ai f73c0a6b1d fix(keymap): Don't run the Enter that commits an input-method candidate
WebKit sends the Enter (or Space) that commits a candidate after compositionend,
with isComposing already false and keyCode 229. Handlers that checked isComposing
alone ran it: dialogs confirmed and shortcuts fired while typing Chinese or
Japanese. isImeKey() checks both, and every keydown handler that skipped
composition uses it.
2026-10-27 17:16:46 +08:00
l0ng-ai 2c576418cb fix(splash): Keep the wordmark still until the splash fades
The splash named Inter, but the font faces and antialiasing came with the app CSS,
which the dev server injects only once the bundle runs: the wordmark switched from
the system font to Inter, moving up and changing weight, just before the fade. The
font faces are now linked from index.html and the splash sets its own smoothing.
The splash also stays on one compositing layer, so the fade-out doesn't re-snap
the centred text.
2026-10-27 17:16:46 +08:00
l0ng-ai b70d487a92 fix(ui): Don't draw a second focus box inside framed text fields
The global focus ring listed input and textarea. :is() takes its most specific
argument, so the rule tied with the components' own :focus-visible resets and won
whenever it loaded later: the Settings search field and the agent composer showed
an inner square box inside their focus frame. Text fields show focus with their
frame; the ring stays on checkboxes, radios and other input controls.
2026-10-27 17:16:46 +08:00
胡翀таzzxzz12345 413564efcf feat(editor): Increase / Decrease Font Size, followed by the Markdown preview (#81)
Adds Increase Font Size / Decrease Font Size (⌥⇧. / ⌥⇧, in the IntelliJ keymaps) for the active editor, sharing the ±1px step and limits with ⌘/Ctrl + mouse wheel. The Markdown preview, including code blocks, follows its editor's zoom, and Reset Font Size in All Editors resets it too.

Editor zoom had no effect once a font size was configured in settings: the configured size was applied with higher precedence than the zoom. The zoom now wins.

Co-authored-by: zzxzz12345 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 16:52:25 +08:00
l0ng-ai f675dd2730 feat(vcs): Repository list in the Branches popup for multi-repository projects (#84)
In projects with several repositories the Branches popup began with a wrapping row of repository chips and listed only the selected repository's branches, and the widget always read "repo / branch".

The popup now lists one row per repository (colour, name, current branch) whose submenu holds that repository's branches. When all repositories are on the same branch the widget shows just the branch and the popup offers Common Local / Remote Branches whose actions apply to every repository; otherwise it shows the current repository's Recent / Local / Remote Branches and Tags. The widget and the popup use the same current repository: the one owning the active file, else the selected one. Search covers actions, repositories and branches across repositories. New Branch… creates the branch in all repositories. Single-repository projects are unchanged. `vcs_roots` now returns each repository's branch and HEAD.

Fixes #78

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 16:51:50 +08:00
l0ng-ai 4100ab3341 feat(markdown): Render Mermaid diagrams in the preview (#82)
Fenced ```mermaid blocks in the Markdown preview render as diagrams. mermaid (12.1.0) is loaded lazily, only when a preview contains a diagram, with securityLevel "strict"; colours come from the theme tokens and diagrams re-render on theme changes. Syntax errors show inline under the source. Rendered diagrams are cached by theme + source, so editing elsewhere in the file doesn't redraw them.

Fixes #79

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 16:23:35 +08:00
胡翀таzzxzz12345 fdd98fbfe4 feat(editor): Navigate inferred type inlay hints (#77)
Some language servers (basedpyright) send inferred type hints as plain text without a label-part location, so ⌘/Ctrl-clicking `: Series` did nothing. For a type hint right after an identifier, ⌘/Ctrl-click now goes to that identifier's type declaration; hints with locations keep direct navigation. Navigable hints show the link underline and pointer only while ⌘/Ctrl is held, including when it is pressed before hovering.

Co-authored-by: zzxzz12345 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 16:10:19 +08:00
l0ng-ai 5d2c89b0dd chore: v0.1.16 (#80)
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 15:36:39 +08:00
l0ng-ai d3f68ed180 fix(keymap): Navigate Back / Forward with the mouse side buttons (#76)
Keymaps only understood keystrokes, so the mouse back / forward side buttons did nothing. Keymaps now accept mouse shortcuts (Button4, Shift+Button5, …); every preset binds Button4 / Button5 to Navigate Back / Forward. The dispatcher handles side-button presses in the capture phase, so they work over the editor, tool windows and empty space, never change the editor selection and don't trigger the webview's own history navigation. Menus and tooltips keep showing the keyboard shortcut.

Fixes #75

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 15:34:54 +08:00
l0ng-ai e3dae02de7 feat(languages): Add Godot / GDScript support (#73)
Adds GDScript, Godot resource and shader file types with tree-sitter highlighting, the GDScript language server over TCP (a headless Godot editor started on demand), "Godot Project" / current-scene run configurations, and debugging through Godot's debug adapter.

Breakpoints set through symlinked paths (/tmp, /var on macOS) were reported verified but never hit; the adapter now sends resolved paths and maps stack frames back to the paths the IDE opened. The duplicate exit event Godot sends after disconnect is ignored.

Fixes #68

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 15:31:25 +08:00
l0ng-ai 2eaa6cb0c7 feat(agents): Dispatch and supervise coding agents over ACP (#72)
## What

An Agents feature: hand a task to a coding agent and follow it from the IDE. Agents speak the [Agent Client Protocol](https://agentclientprotocol.com). Built in: Claude Code, Codex, Gemini CLI, GitHub Copilot, Cursor, OpenCode, Qwen Code, Kimi CLI, Goose, Auggie, Kiro, Mistral Vibe. You can add your own in `<config>/agents/<id>.toml` (`name`, `command`, `args`, `[env]`). An agent whose command isn't on `PATH` is listed under "Not installed".

- **New Task page.** An editor page with a prompt box. You pick the agent, model, mode and thinking effort, and whether it runs in a new worktree (from a chosen branch) or in the checkout.
- **Agents tool window.** Tasks are grouped by what they need: Needs Input, Failed, Running, Ready to Review, Archived. It also shows a stripe badge, a status bar item and notifications.
- **Session tab.**
  - The conversation: Markdown, thinking, tool calls with diff stats, the plan.
  - Permission requests appear as an editor banner.
  - The changed files are compared against the task's base commit and open in the diff viewer.
  - A context-usage meter.
- **Composer.**
  - `@` references files from the project index. A referenced file's text is sent when the agent accepts embedded context, otherwise a `resource_link`.
  - `/` lists the agent's commands; ↑/↓ recall earlier messages.
  - Images can be pasted, dropped or picked; Shift+Tab cycles the mode.
  - While the agent works, Enter queues the message and ⌘↵ interrupts the turn and sends it now. Queued messages can be sent now, edited or removed.
- **Send to Agent.** In the editor and Project view context menus. It adds `@file:10-20` references to the message you typed last.
- Landing the work is left to the existing Git features: the worktree is a normal branch.

## How

- **`crates/ide-agent`**: one ACP agent process per task, running in the task's directory.
  - It folds `session/update` into a timeline and answers `session/request_permission`.
  - It tracks the session's settings: `configOptions`, falling back to the older `modes` / `models` fields. The user's choices are applied again on every new or reloaded session.
  - Tasks are saved as JSON per task. Sessions resume with `session/load` without duplicating history, and old task files are upgraded when read.
- **`ide-jsonrpc`**: adds newline-delimited framing (ACP) next to Content-Length (LSP).
- **`ide-vcs`**: adds `numstat_with_worktree` for the changes list.
- **Editor**:
  - The Switcher (⌃⇥) lists every open editor, as IDEA does, not just files.
  - `EditorKindContribution.restorable` lets a kind's tabs be saved with the editor session, so agent tabs survive reloads.
- **UI**: `Select` popups now size to fit short option details (they used to cut them off).

## Testing

- `cargo test -p ide-agent` (14 tests). They use an in-memory ACP agent and cover permissions, restart with `session/load`, settings, the queue with send-now and stop, and prompt blocks.
- There is also an ignored end-to-end test against the real Claude Code adapter: `OPENIDEA_AGENT_E2E=1 cargo test -p ide-agent real_claude -- --ignored`.
- `pnpm vitest run`: 2052 tests.
- `cargo clippy -p ide-agent -p openidea --all-targets -- -D warnings` and typecheck are clean.
- Driven in the running app with Claude Code:
  - A task in a worktree, with permission answers, changes listed and the diff opened.
  - A follow-up after restarting the IDE.
  - `@` reference with embedded content, `/` commands, Shift+Tab mode changes.
  - A queued message and send-now, an image prompt, Send to Agent from a selection.
  - The Switcher and restored tabs after a reload.

Not covered yet: only Claude Code was driven end to end. The other agents go through the same ACP path but weren't run here.


Merged on the maintainer's go-ahead. Merge with main: kept both sides in Cargo.toml (ide-agent + ide-clipboard), the feature registry (agents + vim) and zh.json (no duplicate keys). After the merge: typecheck clean, full vitest 268 files / 2247 tests passed, ide-agent/ide-jsonrpc/ide-vcs 144 passed, bindings unchanged after regeneration.
2026-10-27 14:44:28 +08:00
胡翀 b4742b730b Support custom editor font weights in steps of 50 (#74)
JetBrains Mono at 500 looks heavier than PyCharm's rendering, and 450 was rounded up to 500. Adds a Custom option with an input to the Main and Bold font weight rows; weights are clamped to 100–900 and rounded to the nearest 50 (the terminal, which follows the editor weights, gets the same steps).

Verified in the app: Custom → 450 shows the input and the preview renders at 450. Maintainer follow-up: formatted the dialog test.

Related: #32

https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 14:38:42 +08:00
胡翀 566b4fdeb1 Make static symbol italics configurable (#70)
Python language servers mark class attributes `static`, so their declarations and `self.` references rendered italic, unlike PyCharm. Adds Color Scheme attributes for static symbols: Language Defaults › Identifiers › Static symbol (italic by default, as IDEA's static members) and Python › Static symbol (upright by default), applied to semantic tokens with the `static` modifier.

Verified in the app with basedpyright: a class attribute renders upright by default and italic when Python › Static symbol › Italic is on, applied live. Maintainer follow-up: formatted colorScheme.tsx.

https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 14:27:24 +08:00
l0ng-ai 12418e0184 fix(editor): Show the ⌘/Ctrl-hover link without waiting for documentation (#71)
## Problem
When you hold ⌘ (Ctrl on Windows/Linux) and hover a symbol, the navigation link had three problems:
- **Slow to appear.** The underline and pointer cursor only showed after the hover (documentation) request came back. A slow or stuck documentation request held the link back.
- **Errors were remembered.** If the definition request was cancelled or the server returned an error, the word was cached as having no target. Hovering it again never retried.
- **Stuck requests blocked the word.** A definition request that never answered blocked any new request for that word.

## Changes (`src/editor/lsp/navigation.ts`)
- The link is underlined as soon as a definition is found. The short summary is filled in when the hover request returns.
- Cancellation and server errors count as temporary failures. They are no longer cached, so the next hover retries.
- A definition request expires after 3 seconds and can be retried. If its response arrives later, it is ignored.
- Responses for a word the pointer has already left, or that arrive after the editor plugin is destroyed, are dropped.

## Tests
- Four new tests in `src/editor/lsp/syntaxFallback.test.ts`: the link shows without waiting for documentation, a temporary error is retried, a stuck request is retried and its late answer ignored, and a late answer for the previous word is ignored. The first three fail without this change.
- `pnpm vitest run src/editor/lsp`: 179 passed. `pnpm typecheck` and eslint report no errors.
- Checked in the running app (`fixtures/ts-app`, `cart.ts`): ⌘-hover over `Cents` showed the underline and pointer cursor after 312 ms and the type summary after 356 ms. ⌘-click opened `money.ts` at the definition.
2026-10-27 14:23:23 +08:00
l0ng-ai 7f0fd870e8 fix(themes): Define the chart token in the high-contrast dark theme (#69)
contrast.test.ts requires every plain colour token in high-contrast dark; #63 added
--chart-series to the dark and light themes only.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 13:46:12 +08:00
l0ng-ai 575749f2ac feat(database): Add query plans, history, data tools and schema objects (#63)
New query, data and schema tools for the Database feature (SQLite, PostgreSQL, MySQL).

## Query console
- **Explain Plan** tab: SQLite `EXPLAIN QUERY PLAN`, PostgreSQL `EXPLAIN (FORMAT JSON)`, MySQL `EXPLAIN`, parsed in `ide-db::plan` into an operation tree (Full Scan / Index Scan / Group By / Order By …) under a statement root, with a properties panel.
- **Query history**: `ide-db::history` keeps executed statements per project and source in `db-history.json` (deduplicated, newest first, 500 max). The Browse Query History dialog has search, a highlighted preview, Paste and Delete.
- Output reports `(execution: X ms, fetching: Y ms)`.

## Results and table editor
- Local column filter (value list with counts) and local sort.
- Record / Value / Aggregates side panel.
- Chart view (bar / line) with X / Y / aggregation settings.
- Export Data dialog: extractor, Transpose, headers, preview, file or clipboard. An extractor drop-down sits on the data toolbars.
- Import Data from a CSV / TSV file.
- Table editor gets a WHERE | ORDER BY row. Column headers fit their names, with filter and sort indicators. Whole SQLite REALs display as `3108`, not `3108.0`.

## Database tree
- Triggers under tables. Routines, sequences and materialized views under schemas, with DDL, Quick Documentation and Drop.
- Data source options: object filter, show template databases, single database mode (PostgreSQL).
- New ▸ Import from Clipboard (connection URLs).

## IPC
New commands: `db_schema_objects`, `db_object_ddl`, `db_explain`, `db_history`, `db_remove_history`. Bindings are regenerated.

## Testing
- `cargo test -p ide-db`: plan parsing, history store, trigger listing and DDL, explain without executing.
- `cargo clippy -p ide-db -p openidea --all-targets -- -D warnings` is clean.
- `pnpm typecheck` and eslint pass. `pnpm vitest run src/features/database src/ui`: 226 passed.
- Checked in the running app against a SQLite database:
  - tree with triggers
  - result grid, local filter, side panel
  - chart
  - Explain Plan
  - history dialog
  - Export Data dialog
  - table editor ORDER BY
  - CSV import




Merge follow-up: grouped the new `--chart-series` token under a section comment and added it to the theme plugin template (theme.test.ts on main), regenerated docs/plugins/themes.md. Re-verified after merging main on macOS with a SQLite source: query + result grid with filter/sort headers, Explain Plan tab (Full Scan / Index Scan / Group By / Order By), Query History dialog; `cargo nextest run -p ide-db` 45 passed, bindings unchanged after regeneration.

https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 13:31:29 +08:00
l0ng-ai 580f0efc28 fix(ui): Keep the Select chevron at the right edge with a custom value (#67)
Select only wrapped its default label in the flex-filling value span, so a
renderValue (the data source Color picker's swatch + name) left the chevron
right after the text, short of the field's edge.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 13:20:43 +08:00
l0ng-ai dcdb0e48e4 fix(ui): Draw focus rings on controls only, not on focusable containers (#66)
The global :focus-visible outline loads after the module CSS with the same
specificity, so every focusable container without its own override (the
Intentions list, other list/tree/menu popups) got a square blue frame. ee99b36
patched the Select popup only. Like IDEA, rings now mark controls (buttons,
links, fields, checkboxes, tabs…); lists, trees, tables and popups show focus
through their selected row, and the few rows that drew frames use the hover
background instead.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 13:09:29 +08:00
l0ng-ai 17400ade3d test(e2e): Reach later Settings groups in the virtualized page tree (#65)
The Settings page tree only renders rows near the viewport. Editor › Vim (#55) pushed
Version Control past the rendered rows on CI's Linux runner, so the e2e failed on main.
Collapse Editor before checking the later groups.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 13:00:37 +08:00
l0ng-ai b91402ef7d chore: v0.1.15
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 12:10:30 +08:00
l0ng-ai 56fdc005a8 feat(java): Download JDK, and one-click "Download JDK N" where a JDK is missing (#61)
Root cause: the IDE only detected installed JDKs and had no way to get one, so any launch needing a newer JDK than the machine has (latest jdtls needs JDK 25) dead-ended in an error.

Fix: IDEA-style Download JDK (Eclipse Temurin via the Adoptium API, sha256-verified, reusing ide-tools' download/verify code; Windows zip, Linux tar.gz, macOS Contents/Home) into <app-data>/tools/jdks, registered with JDK discovery and rescanned after each download. "Download JDK…" in the Project SDK and Language Server JDK pickers; a one-click `java.downloadJdk` "Download JDK N" on "needs JDK N" errors, which also repoints a too-old language server JDK and restarts jdtls.

Siblings: language server status popup, jdtls launch notification, run console classpath error, debug launch, run configurations without a JDK ≥ the module's Java version, Maven/Gradle sync failures, single-file Java run without `java` on PATH.

Verified in the app on macOS: vendor/version/location queries, the Download JDK dialog from the Language Server JDK picker, a real Temurin 25.0.5 download that runs. Not verified on Windows/Linux.

Fixes #49

https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 12:09:51 +08:00
l0ng-ai beab7992f9 feat(editor): Rainbow brackets and semantic highlighting (rainbow variables) (#59)
Two editor toggles under Settings › Editor › Color Scheme › Language Defaults (off by default, also actions `editor.toggleRainbowBrackets` / `editor.toggleSemanticHighlighting`):
- Semantic highlighting (IDEA's rainbow variables): locals and parameters coloured by a name hash from LSP semantic tokens; fields, statics, constants, library symbols untouched.
- Rainbow brackets (VS Code's bracket pair colorization): (), [], {} by depth, unmatched in the error colour, strings/comments skipped, visible ranges only with 4 KB checkpoints.
Palettes are theme tokens (`--syn-rainbow-1..5`, `--syn-bracket-1..3`, light/dark/high-contrast), editable in the Color Scheme tree, and mapped from IntelliJ `.icls` RAINBOW_COLOR1..5.

App verification on macOS found the colours were overridden by the syntax highlighter's span nested inside the marks; the rules now cover descendants. Verified both toggles on/off live in a TS file.

Fixes #56

https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 11:52:07 +08:00
l0ng-ai 2e0c74e31d docs(themes): Regenerate the theme token reference (#62)
Main's Frontend CI failed: docs/plugins/themes.md was stale after a token change.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 11:47:39 +08:00
l0ng-ai e16253a890 fix(editor): Ctrl/⌘-hover info replaces hover popups instead of stacking (#60)
Root cause: the quick-doc/problem hover and the Ctrl/⌘-hover navigation info were independent tooltips with no precedence, and the navigation modifier was only seen through the focused editor's key events, so holding Ctrl stacked both popups.

Fix: a window-wide platform navigation modifier (`src/platform/navigationModifier.ts`, ⌘ on macOS / Ctrl elsewhere, unchorded); with it held the plain hover doesn't open, late LSP results are dropped, an open hover closes (unless the pointer is inside it, so Ctrl/⌘+C still copies), release clears the link and info.

Siblings: problem/diagnostic hover, debugger value tooltip, inlay hint hovers (no doc or underline through hints, platform-correct Ctrl/⌘-click), consistent ⌘ vs ⌃ handling on macOS.

Verified in the app on macOS (⌘): hover then ⌘ leaves only the nav info, ⌘ before hover shows only nav info, release clears both and plain hover returns. Not verified on Windows.

Fixes #57

https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 11:46:04 +08:00
l0ng-ai 7146779f6c feat(vim): Built-in Vim mode modelled on IdeaVim (#55)
Built-in Vim emulation on @replit/codemirror-vim (approved dependency), modelled on IdeaVim: `vim.toggle` (Tools › Vim, status widget, Settings › Editor › Vim), mode widget (NORMAL / INSERT / VISUAL / V-LINE / V-BLOCK / REPLACE), IdeaVim-style shortcut conflict handlers (Vim / IDE per key) through a generic `registerKeyClaim()` in the keymap dispatcher, Escape closing popups first, a safe subset of ~/.openideavimrc / ~/.ideavimrc (set, map variants, mapleader, :action / <Action>()), Ex commands :w :wa :q :qa :wq :x :action. Covers file editors, diff editable side and merge result via a new `embeddedEditorExtensions` extension point.

Verified in the app on macOS: motions/operators, i/Esc/V mode widget, :w saves, Ctrl+R redoes in Vim without running Run, toggling off restores plain editing. Not verified on Windows/Linux.

Fixes #27

https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 11:43:37 +08:00
l0ng-ai cac95273d3 fix(java): Detect Lombok inherited from outside the project (#58)
Root cause: `uses_lombok` only scanned build files ~3 levels below the jdtls root, so Lombok inherited from outside that tree was judged `Unused` and no `-javaagent` was attached — even when Lombok was installed in Settings.

Covered: parent pom only in the local Maven repository (settings.xml localRepository honoured, multi-hop, cycle-safe), parent via relativePath outside the workspace, outer Gradle root build / version catalog, `lombok.config` in ancestor directories, and a bounded source fallback (`import lombok.` / `@lombok.`) for convention plugins and BOMs. A Lombok jar installed in Settings is now always attached (like IDEA's always-on Lombok support). Detection in `java_resolve_launch` runs in `spawn_blocking`.

Fixes #33

https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 11:19:45 +08:00
胡翀 55f42d2771 fix(editor): match IDEA font weights in the light scheme (#35)
Root cause: the editor had no font weight settings, and the WebView rendering of JetBrains Mono looks lighter than IDEA (#32).
Fix (IDEA's Settings › Editor › Font › Typography Settings): configurable Main font weight and Bold font weight (defaults Regular 400 / Bold 700) via --fw-code / --fw-code-bold; colour-scheme bold/regular overrides still win; settings preview updates live. Replaces the Light-only 450/550 hard-coding.
Siblings covered: sticky lines, diff/merge, run console (ANSI bold), Find in Files, completion/parameter info/docs, database editor, debugger value popup, matched braces, terminal with "Use editor font".
Verified: scoped vitest, ide-core tests, in-app on macOS (settings UI, editor weight follows the setting end to end).

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:41:56 +08:00
l0ng-ai 30310810e6 feat(plugins): Theme plugin template, theme docs and IntelliJ theme import (#54)
Per the maintainer's decision for #24, no third-party themes are bundled; instead a theme plugin template and docs let the community port themes (IntelliJ also ships few themes, the rest are plugins).
- templates/theme-plugin: manifest-only plugin with an original example (Harbor Night) covering every UI token and an editor scheme (.icls equivalent).
- docs/plugins/themes.md: format, IntelliJ / VS Code porting tables, generated token reference (pnpm gen:theme-docs); drift test fails when tokens.css and the template/reference disagree.
- pnpm theme:import-intellij: dependency-free converter for IntelliJ .theme.json (+ .icls).
- Plugin host: themes may name an editor-scheme merged over the theme; comments allowed in theme files.
- Fixes: a plugin theme's kind now switches the light/dark base; plugin themes go in their own stylesheet so the Appearance accent and editor scheme still layer on top.
Verified: ide-plugin tests, vitest (44), in-app on macOS: installed the template from disk, applied Harbor Night (dark base + teal accent over Islands Light), back to default restored the light theme.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:39:08 +08:00
l0ng-ai b2fec4ae30 feat(vcs): Show combined changes for multiple selected log commits (#52)
Root cause: the Git Log already supported multi-selection, but the Changes pane only read the last clicked commit and the backend had no "changes across several commits" query.
Fix (IDEA): ide-vcs Repo::commits_changes merges per-file changes across selected commits (before the first touching commit ↔ after the last, renames chained, add-then-delete dropped); the details pane shows "N files in M commits" with the commit list; exactly two commits get "Compare Versions" (version ↔ version dialog, also fixing added/deleted sides).
Siblings covered: Show History for file/folder (same log), Local History multi-select (oldest ↔ newest diff).
Verified: ide-vcs tests incl. temp-repo commits_changes, vcs vitest (143), in-app on macOS: 3 contiguous commits → "2 files in 3 commits"; Cmd-click 2 commits → Compare Versions lists the right files.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:39:01 +08:00
l0ng-ai aa5821bb46 fix(spelling): Rename identifiers on Typo fixes, add inspection controls, cut false positives (#51)
Root causes: Typo "Change to" replaced one occurrence even for declared names (breaking references); inspections had no Disable / Edit settings controls anywhere; en_US Hunspell does not derive agent nouns like "checkpointer" and compound identifier words were flagged; local inspections (Typo, file references, SQL) never reached Problems.
Fix (IDEA): "Typo: Rename to…" renames via LSP rename, falling back to syntax-based local rename, never a silent single replace, and lists identifier-safe words only; intention submenu (→) with Edit inspection profile setting / Disable inspection for every inspection; Problems and Inspection Results get Disable Inspection, Change Severity, Edit Inspection Profile Setting; Typo options Process code / literals / comments; -er/-ers derivation and identifier compounds accepted, common misspellings still flagged.
Siblings covered: all LSP and built-in inspections' intentions, file reference and SQL inspections in Problems, severity counter.
Verified: ide-spell tests (issue examples + ~50 real misspellings), vitest (286), in-app on macOS: only 'mesage' flagged, submenu, Rename to → 'message' updated both occurrences.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:38:53 +08:00
kevinh eda8cae0a1 feat(project-tree): Exchange files with the OS clipboard on Windows (#41)
Exchange files with the OS clipboard on Windows: CF_HDROP read/write in a new ide-clipboard crate (Win32 FFI behind cfg(windows), stub elsewhere), three thin commands, and project-view copy/paste hooks. Pasting from Explorer always copies; our own hand-off falls back to the internal clipboard so Copy/Move dialogs and refactoring stay intact.
Verified: ide-clipboard round-trip tests, project-tree vitest (93), CI on all three OSes. Not verified on Windows hardware here.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:38:45 +08:00
l0ng-ai e150101244 feat(debugger): Remote debug run configurations (Remote JVM, Go, Python, Node.js) (#50)
Root cause: run configurations could only launch a process; there was no "attach to a debugger that is already listening" type, and debugServer only connected to 127.0.0.1.
Fix (IDEA / GoLand / PyCharm): debug-only Remote JVM Debug (attach / listen, live JDWP agent args per JDK version), Go Remote (dlv --headless, substitutePath), Python Remote Debug (debugpy --listen, pathMappings) and Attach to Node.js (inspector, localRoot/remoteRoot); debugServer accepts host:port and [v6]:port; JVM listen mode via a cancellable relay so java-debug can attach.
Verified: ide-dap tests (host:port, relay handshake, cancel), run/debugger vitest, in-app on macOS: Python Remote Debug attached to a debugpy server, paused at app.py:3 with variables. Remote JVM/Go/Node not exercised in-app.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:38:38 +08:00
l0ng-ai 642b80cef0 fix(workbench): Keep a way out of Distraction Free Mode on Windows (#47)
Root cause: on Windows the window is frameless and the main menu lives in the custom title bar; Distraction Free Mode rendered a bare title bar without it, the toggle has no default shortcut (as in IDEA) and the mode persists across restarts, leaving no way out.
Fix (IDEA): the bare title bar keeps the main menu when there is no native menu bar; a lone Alt opens the main menu; entering the mode (or restoring it) shows "To exit Distraction Free Mode, use View | Appearance … or Find Action" with an Exit action, in its own notification group.
Siblings covered: Distraction Free + Full Screen on Windows; other chrome-hiding settings checked (unaffected).
Verified in-app on macOS (hint, Exit action, single Don't Show Again). Windows-only parts (☰ in bare title bar, lone Alt) not verified on Windows.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:38:26 +08:00
l0ng-ai b4a3e866c6 fix(terminal): render the terminal in the bundled JetBrains Mono (#44)
Root cause: the terminal built its own font-family ("JetBrains Mono", Nerd Fonts, monospace) without the bundled "JetBrains Mono Variable", so on Windows (no JetBrains Mono installed) xterm fell back to the system monospace (SimSun on Chinese Windows); xterm also measured cells before the webfont loaded.
Fix: one resolver (src/platform/fonts.ts monoFontFamily) maps JetBrains Mono to the bundled face; xterm re-measures once fonts load; "Use editor font" also takes the editor's fallback font (IDEA).
Siblings covered: embedded run terminal, editor default family + fallback, Settings › Editor › Font preview.
Verified in-app on macOS (terminal renders JetBrains Mono Variable). Not verified on Windows.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:38:18 +08:00
l0ng-ai 5670c2e8dd test: stub Range layout methods once in the test setup (#53)
Root cause: jsdom has no layout and CodeMirror measures text ranges in an animation frame, sometimes after a test finished; test files that did not stub Range.getClientRects (e.g. search/codePreview) threw an unhandled TypeError that failed whole CI runs at random (seen on #41).
Fix: stub Range.getClientRects / getBoundingClientRect once in src/test/setup.ts; drop the six per-file copies.
Verified: vitest on editor/lsp, editor/refactor, templates, search (55 files, 458 tests, no unhandled errors).

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:38:11 +08:00
l0ng-ai 843127f4a3 fix(app): Apply the saved IDE zoom before the page loads so the splash doesn't jump
The frontend set the webview zoom once settings loaded, while the splash was
still up, so a non-100% zoom visibly scaled the splash logo at the end.
2026-10-27 10:17:06 +08:00
l0ng-ai 1127263ea8 fix(run): Shorten java command lines too long for the OS (#28) (#45)
Root cause: every java launch inlined the whole classpath into one -cp argument with no "Shorten command line", so long classpaths exceeded CreateProcessW's 32767-char limit (os error 206) before the JVM started.
Fix (IDEA's auto "Shorten command line"): ide-run rewrites a too-long java command line at spawn time — @argfile on JDK 9+ with ASCII paths, otherwise a MANIFEST pathing jar (percent-encoded file: URLs, 72-byte lines); temp files are removed when the process exits. Debug passes the same choice to java-debug's shortenCommandLine.
Siblings covered: Application/Spring Boot, test classpath, Kotlin main, explicit java -cp configs, profiler, PTY launches, Debug.
Verified: unit tests, pathing jar loaded by real JDK 8/11/25, ProcessManager integration test with 3000 entries on JDK 8/17/25. Not verified on Windows.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 10:13:31 +08:00
l0ng-ai de84a643aa fix(ui): Make read-only content selectable with a Copy context menu (#48)
Root cause: body is user-select: none and each feature had to opt back in; the Markdown preview (and other read-only views) never did, and the app-wide contextmenu guard left no Copy item.
Fix: shared selectableText class (src/ui) for read-only content, and a fallback Copy context menu from browserGuards when right-clicking a selection or a selectable area (component menus still win).
Siblings covered: Quick Documentation / hover / completion docs, hover errors, Quick Definition, debugger value tooltip, inspection messages, message dialogs (no drag on body text), notification titles, About dialog; existing selectable consoles now get Copy too.
Verified in-app on macOS: select in Markdown preview, right-click Copy puts the text on the clipboard; tab context menu unchanged.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 08:56:13 +08:00
l0ng-ai 6dfd82de4c fix(vue): Run Vue Language Server 3 in hybrid mode with a usable TypeScript (#46)
Root cause: the tools dir installed typescript@latest, now TypeScript 7 (native port, no typescript.js/tsserver.js/ts.server), so @vue/language-server 3 crashed on ts.server.protocol and restarted forever; Volar 3 hybrid mode also needs tsserver/request forwarding, which we never answered.
Fix: pin TS-as-library servers to typescript@<7 and keep shared deps on uninstall; pick a usable tsdk (setting / bundled / project, --tsdk); bridge tsserver/request to vtsls with @vue/typescript-plugin (null when vtsls is absent); answer workspace/configuration for section ""; stop restarting after 3 consecutive early crashes (IDEA); crash summary starts at the exception line.
Siblings covered: typescript-language-server and svelte-language-server (same TS 7 break), vtsls config, install hints in language TOMLs.
Verified: scoped cargo tests, real-server tests (vue-language-server 3.3.13 + vtsls), in-app on macOS (server running, no crash loop). Not verified on Windows.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 08:21:42 +08:00
kevinh b79522fd03 fix(java): Point the missing-JDK error at the Language Server JDK setting (#31)
Root cause: missing_runtime_message only suggested JAVA_HOME (process-wide) although a per-app Language Server JDK setting exists since #21.
Siblings covered: server_jdk_too_old_message now names the same Settings page via a shared SERVER_JDK_SETTING const; both asserted in tests.
2026-10-26 23:08:52 +08:00
l0ng-ai d7c27c1184 fix: configure git identity for merge and rebase test 2026-10-26 08:30:07 +08:00
l0ng-ai 6b9a2ec67e fix: sync inspection results with profiles and restore CSS validation 2026-10-25 23:41:15 +08:00
454 змінених файлів з 31934 додано та 1588 видалено

No files matched your search

Створено
+66 -28
Переглянути файл
@@ -3960,9 +3960,27 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-jsonrpc",
"ide-vcs",
"parking_lot",
"serde",
"serde_json",
"specta",
"tempfile",
"tokio",
"toml 0.9.12+spec-1.1.0",
"tracing",
"uuid",
]
[[package]]
name = "ide-analysis"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -3976,7 +3994,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -3989,9 +4007,13 @@ dependencies = [
"tracing",
]
[[package]]
name = "ide-clipboard"
version = "0.1.17"
[[package]]
name = "ide-core"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"dunce",
"serde",
@@ -4003,7 +4025,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-run",
@@ -4017,7 +4039,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4034,7 +4056,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -4054,7 +4076,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"libc",
@@ -4068,7 +4090,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4082,7 +4104,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"parking_lot",
@@ -4100,7 +4122,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"blake3",
"criterion",
@@ -4122,7 +4144,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"futures",
"ide-core",
@@ -4137,7 +4159,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"blake3",
"criterion",
@@ -4158,6 +4180,7 @@ dependencies = [
"tree-sitter-css",
"tree-sitter-dart",
"tree-sitter-elixir",
"tree-sitter-gdscript",
"tree-sitter-go",
"tree-sitter-graphql",
"tree-sitter-haskell",
@@ -4189,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"futures",
"globset",
@@ -4212,7 +4235,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-language",
@@ -4230,7 +4253,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-run",
@@ -4243,7 +4266,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4258,17 +4281,19 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"zip 2.4.2",
]
[[package]]
name = "ide-sdk"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"dunce",
"ide-core",
"ide-language",
"ide-run",
"ide-vfs",
"ignore",
"serde",
"serde_json",
"specta",
@@ -4280,7 +4305,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"criterion",
"globset",
@@ -4300,11 +4325,12 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"parking_lot",
"serde",
"serde_json",
"specta",
"spellbook",
"tracing",
@@ -4312,7 +4338,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"ide-language",
@@ -4327,7 +4353,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"libc",
@@ -4340,7 +4366,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"criterion",
"ide-core",
@@ -4352,7 +4378,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"flate2",
"hex",
@@ -4372,7 +4398,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"dunce",
"gix",
@@ -4389,7 +4415,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"chardetng",
"dunce",
@@ -4410,7 +4436,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"ide-core",
"open",
@@ -4426,7 +4452,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"blake3",
"dunce",
@@ -5851,12 +5877,14 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.14"
version = "0.1.17"
dependencies = [
"dirs 6.0.0",
"dunce",
"ide-agent",
"ide-analysis",
"ide-build",
"ide-clipboard",
"ide-core",
"ide-coverage",
"ide-dap",
@@ -9268,6 +9296,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-gdscript"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7a37fe8c0a10c0c39ecd5b2f7db53933f691488f5572409a4d3c0dfeb3f6108"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-go"
version = "0.25.0"
+3 -1
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.14"
version = "0.1.17"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -34,6 +34,8 @@ ide-http = { path = "crates/ide-http" }
ide-db = { path = "crates/ide-db" }
ide-web = { path = "crates/ide-web" }
ide-spell = { path = "crates/ide-spell" }
ide-agent = { path = "crates/ide-agent" }
ide-clipboard = { path = "crates/ide-clipboard" }
# serialization & IPC typing
serde = { version = "1", features = ["derive"] }
+11
Переглянути файл
@@ -100,6 +100,17 @@ c → cpp, php_only), node names adapted to the bundled grammar versions
definitions re-kinded as `field` / `method`, and missing scopes, definitions and
references added; each file's header notes its changes.
## Theme plugin palettes
The sample theme plugins port MIT-licensed palettes; each package's `LICENSE`
holds the full notice and source revisions:
- `plugins/theme-solarized/`: [Solarized](https://github.com/altercation/solarized),
Copyright (c) 2011 Ethan Schoonover.
- `plugins/theme-one/`: Atom [One Light](https://github.com/atom/one-light-syntax) /
[One Dark](https://github.com/atom/one-dark-syntax) syntax themes, Copyright (c) 2016
GitHub Inc., and their UI themes, Copyright (c) 2014 GitHub Inc.
---
Apache License
+22
Переглянути файл
@@ -0,0 +1,22 @@
[package]
name = "ide-agent"
description = "Coding agents over the Agent Client Protocol: tasks, sessions, worktrees and their timelines"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ide-core.workspace = true
ide-jsonrpc.workspace = true
ide-vcs.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tokio.workspace = true
toml.workspace = true
tracing.workspace = true
parking_lot.workspace = true
uuid.workspace = true
[dev-dependencies]
tempfile.workspace = true
+224
Переглянути файл
@@ -0,0 +1,224 @@
//! Session settings (model, mode, thinking effort…), slash commands and context use, as
//! the agent reports them over ACP.
use crate::model::{AgentCommand, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentUsage};
use serde_json::{Value, json};
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
/// plus the older `modes` / `models` fields for what those don't cover.
pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
let mut out = result.get("configOptions").map(parse_options).unwrap_or_default();
let has = |out: &[AgentConfigOption], category: &str| out.iter().any(|o| o.category.as_deref() == Some(category));
if !has(&out, "mode")
&& let Some(modes) = result.get("modes")
{
out.push(legacy(modes, "mode", "Mode", "availableModes", "id", "currentModeId", AgentConfigVia::Mode));
}
if !has(&out, "model")
&& let Some(models) = result.get("models")
{
out.push(legacy(
models,
"model",
"Model",
"availableModels",
"modelId",
"currentModelId",
AgentConfigVia::Model,
));
}
out.retain(|o| !o.values.is_empty());
out
}
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
let Some(list) = options.as_array() else { return Vec::new() };
list.iter()
.filter(|o| o.get("type").and_then(Value::as_str).is_none_or(|t| t == "select"))
.filter_map(|o| {
let id = o.get("id").or_else(|| o.get("configId")).and_then(Value::as_str)?.to_owned();
let mut values = Vec::new();
for v in o.get("options").and_then(Value::as_array).into_iter().flatten() {
// Grouped options: `{ group, name, options: [...] }`.
match v.get("options").and_then(Value::as_array) {
Some(group) => values.extend(group.iter().filter_map(value_of)),
None => values.extend(value_of(v)),
}
}
Some(AgentConfigOption {
name: str_of(o, "name").unwrap_or_else(|| id.clone()),
description: str_of(o, "description"),
category: str_of(o, "category").or_else(|| matches!(id.as_str(), "model" | "mode").then(|| id.clone())),
current: str_of(o, "currentValue"),
values,
via: AgentConfigVia::Option,
id,
})
})
.collect()
}
/// A `config_option_update`: its options replace the config-option ones; `modes` / `models`
/// stand-ins stay.
pub(crate) fn merge_update(config: &mut Vec<AgentConfigOption>, options: &Value) {
let fresh = parse_options(options);
let covered = |o: &AgentConfigOption| fresh.iter().any(|f| f.category.is_some() && f.category == o.category);
config.retain(|o| o.via != AgentConfigVia::Option && !covered(o));
let legacy = std::mem::take(config);
config.extend(fresh);
config.extend(legacy);
config.retain(|o| !o.values.is_empty());
}
/// `current_mode_update`.
pub(crate) fn set_mode(config: &mut [AgentConfigOption], mode: &str) {
if let Some(o) = config.iter_mut().find(|o| o.category.as_deref() == Some("mode")) {
o.current = Some(mode.to_owned());
}
}
/// The request (method, params without the session id) that sets `option` to `value`.
pub(crate) fn set_request(option: &AgentConfigOption, value: &str) -> (&'static str, Value) {
match option.via {
AgentConfigVia::Option => ("session/set_config_option", json!({ "configId": option.id, "value": value })),
AgentConfigVia::Mode => ("session/set_mode", json!({ "modeId": value })),
AgentConfigVia::Model => ("session/set_model", json!({ "modelId": value })),
}
}
/// `available_commands_update`.
pub(crate) fn commands_of(update: &Value) -> Vec<AgentCommand> {
update
.get("availableCommands")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|c| {
Some(AgentCommand {
name: c.get("name")?.as_str()?.trim_start_matches('/').to_owned(),
description: str_of(c, "description").unwrap_or_default(),
hint: c.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty()).map(str::to_owned),
})
})
.collect()
}
/// `usage_update`: `{ used, size, cost?: { amount, currency } }`.
pub(crate) fn usage_of(update: &Value) -> Option<AgentUsage> {
let tokens = |key: &str| update.get(key)?.as_f64().map(|n| n.clamp(0.0, f64::from(u32::MAX)) as u32);
let used = tokens("used")?;
let size = tokens("size").filter(|s| *s > 0)?;
Some(AgentUsage {
used,
size,
cost: update.pointer("/cost/amount").and_then(Value::as_f64),
currency: update.pointer("/cost/currency").and_then(Value::as_str).map(str::to_owned),
})
}
fn legacy(
v: &Value,
id: &str,
name: &str,
list: &str,
key: &str,
current: &str,
via: AgentConfigVia,
) -> AgentConfigOption {
let values = v
.get(list)
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|m| {
let value = m.get(key)?.as_str()?.to_owned();
Some(AgentConfigValue {
name: str_of(m, "name").unwrap_or_else(|| value.clone()),
description: str_of(m, "description"),
value,
})
})
.collect();
AgentConfigOption {
id: id.to_owned(),
name: name.to_owned(),
description: None,
category: Some(id.to_owned()),
current: str_of(v, current),
values,
via,
}
}
fn value_of(v: &Value) -> Option<AgentConfigValue> {
let value = v.get("value")?.as_str()?.to_owned();
Some(AgentConfigValue {
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
description: str_of(v, "description"),
value,
})
}
fn str_of(v: &Value, key: &str) -> Option<String> {
v.get(key).and_then(Value::as_str).map(str::to_owned)
}
#[cfg(test)]
mod tests {
use super::*;
fn ids(c: &[AgentConfigOption]) -> Vec<(&str, Option<&str>)> {
c.iter().map(|o| (o.id.as_str(), o.current.as_deref())).collect()
}
#[test]
fn config_options_win_over_the_older_fields() {
let r = json!({
"modes": {"currentModeId": "default", "availableModes": [{"id": "default", "name": "Manual"}]},
"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "plan",
"options": [{"value": "default", "name": "Manual"}, {"value": "plan", "name": "Plan"}]},
{"id": "effort", "category": "thought_level", "type": "select", "currentValue": "medium",
"options": [{"group": "g", "name": "G", "options": [{"value": "low"}, {"value": "medium", "name": "Medium"}]}]},
{"id": "fast", "type": "boolean", "currentValue": false}
],
"models": {"currentModelId": "m1", "availableModels": [{"modelId": "m1", "name": "One"}]}
});
let c = options_of(&r);
assert_eq!(ids(&c), [("mode", Some("plan")), ("effort", Some("medium")), ("model", Some("m1"))]);
assert_eq!(c[1].values.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["low", "Medium"]);
assert_eq!(set_request(&c[0], "default").0, "session/set_config_option");
assert_eq!(set_request(&c[2], "m1"), ("session/set_model", json!({"modelId": "m1"})));
}
#[test]
fn updates_replace_options_and_track_the_mode() {
let mut c = options_of(&json!({
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask"}, {"id": "code"}]},
"configOptions": [{"id": "model", "type": "select", "currentValue": "a", "options": [{"value": "a"}]}]
}));
assert_eq!(c[0].category.as_deref(), Some("model"), "the category defaults from the id");
set_mode(&mut c, "code");
assert_eq!(c[1].current.as_deref(), Some("code"));
assert_eq!(set_request(&c[1], "ask").0, "session/set_mode");
merge_update(
&mut c,
&json!([{"id": "model", "type": "select", "currentValue": "b", "options": [{"value": "b"}]}]),
);
assert_eq!(ids(&c), [("model", Some("b")), ("mode", Some("code"))]);
}
#[test]
fn commands_and_usage() {
let cmds = commands_of(&json!({"availableCommands": [
{"name": "review", "description": "Review changes", "input": {"hint": "what to review"}},
{"name": "/init", "description": "Write CLAUDE.md", "input": null}
]}));
assert_eq!(cmds[0].hint.as_deref(), Some("what to review"));
assert_eq!((cmds[1].name.as_str(), cmds[1].hint.as_ref()), ("init", None));
let u = usage_of(&json!({"used": 1200, "size": 200000, "cost": {"amount": 0.42, "currency": "USD"}})).unwrap();
assert_eq!((u.used, u.cost, u.currency.as_deref()), (1200, Some(0.42), Some("USD")));
assert!(usage_of(&json!({"used": 1, "size": 0})).is_none());
}
}
File diff suppressed because it is too large. Load diff
+285
Переглянути файл
@@ -0,0 +1,285 @@
//! IPC types: tasks, their timeline entries and the events streamed to the UI.
use ide_core::IpcPath;
use serde::{Deserialize, Serialize};
use specta::Type;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentStatus {
/// Creating the worktree / starting the agent.
Starting,
Running,
/// Waiting for a permission answer.
NeedsInput,
/// The turn ended; the result can be reviewed or the conversation continued.
Ready,
Failed,
Archived,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Isolation {
/// A new git worktree on its own branch.
Worktree,
/// The project's own checkout.
Local,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentTask {
pub id: String,
pub title: String,
/// [`AgentProvider::id`].
pub provider: String,
/// Model the task runs on (its `model` setting), when known.
pub model: Option<String>,
pub status: AgentStatus,
pub isolation: Isolation,
/// Directory the agent works in (the worktree, or the project root).
pub cwd: IpcPath,
/// Branch of the task's worktree.
pub branch: Option<String>,
/// Branch (or revision) the worktree was created from.
pub base: Option<String>,
/// Commit the task's changes are compared against.
pub base_commit: Option<String>,
/// Why the task failed, when it did.
pub error: Option<String>,
pub created_ms: f64,
pub updated_ms: f64,
/// The session's settings (model, mode, thinking effort…) as last reported, with the
/// user's choices applied.
pub config: Vec<AgentConfigOption>,
/// Slash commands the agent offers.
pub commands: Vec<AgentCommand>,
/// Context window use, when the agent reports it.
pub usage: Option<AgentUsage>,
/// Messages waiting for the current turn to end, oldest first.
pub queue: Vec<AgentQueued>,
}
/// One value of a select-type session setting.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentConfigValue {
pub value: String,
pub name: String,
pub description: Option<String>,
}
/// How a setting is changed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentConfigVia {
/// `session/set_config_option`.
#[default]
Option,
/// `session/set_mode` (agents that report `modes` instead of a mode config option).
Mode,
/// `session/set_model` (agents that report `models` instead of a model config option).
Model,
}
/// A session setting: an ACP select config option, or the older `modes` / `models`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentConfigOption {
pub id: String,
pub name: String,
pub description: Option<String>,
/// ACP category: `model`, `mode`, `thought_level`, or agent-specific.
pub category: Option<String>,
pub current: Option<String>,
pub values: Vec<AgentConfigValue>,
pub via: AgentConfigVia,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommand {
/// Without the leading `/`.
pub name: String,
pub description: String,
/// What to type after the command, when it takes input.
pub hint: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentUsage {
/// Tokens in the context window.
pub used: u32,
/// Size of the context window.
pub size: u32,
/// Session cost so far.
pub cost: Option<f64>,
pub currency: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentImage {
pub mime_type: String,
/// Base64, without a `data:` prefix.
pub data: String,
pub name: Option<String>,
}
/// A message to the agent: text, plus files to look at and images.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPrompt {
pub text: String,
pub files: Vec<IpcPath>,
pub images: Vec<AgentImage>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentQueued {
pub id: String,
pub prompt: AgentPrompt,
}
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentConfigChoice {
pub id: String,
pub value: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentToolStatus {
Pending,
Running,
Completed,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentToolDiff {
pub path: IpcPath,
pub added: u32,
pub removed: u32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPlanItem {
pub content: String,
/// `pending`, `in_progress` or `completed`.
pub status: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPermissionOption {
pub id: String,
pub name: String,
/// `allow_once`, `allow_always`, `reject_once` or `reject_always`.
pub kind: String,
}
/// One item of a task's conversation.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEntry {
User {
text: String,
/// Names of the files and images sent with it.
attachments: Vec<String>,
},
Agent {
text: String,
},
Thought {
text: String,
},
Tool {
id: String,
title: String,
/// ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`…
kind: String,
status: AgentToolStatus,
locations: Vec<IpcPath>,
/// Text the tool reported (command output…), truncated.
output: Option<String>,
diffs: Vec<AgentToolDiff>,
},
Plan {
items: Vec<AgentPlanItem>,
},
Permission {
id: u32,
title: String,
options: Vec<AgentPermissionOption>,
/// Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled".
chosen: Option<String>,
},
Error {
message: String,
},
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentProvider {
pub id: String,
pub name: String,
/// The command line that starts its ACP server.
pub command: String,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
pub config: Vec<AgentConfigOption>,
/// Slash commands it offered last time.
pub commands: Vec<AgentCommand>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct NewAgentTask {
pub prompt: AgentPrompt,
pub provider: String,
/// Settings for the new session (model, mode…).
pub config: Vec<AgentConfigChoice>,
pub isolation: Isolation,
/// Branch to start the worktree from; the current branch when `None`.
pub base: Option<String>,
}
/// A file the task changed, relative to [`AgentTask::base_commit`].
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentChange {
pub path: IpcPath,
pub rel_path: String,
pub kind: ide_vcs::ChangeKind,
pub added: u32,
pub removed: u32,
}
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
#[derive(Clone, Debug, Serialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
/// A task was created or its metadata changed.
Task {
task: AgentTask,
},
Removed {
id: String,
},
/// Entry `index` of `task` was added or replaced.
Entry {
task: String,
index: u32,
entry: AgentEntry,
},
}
+158
Переглянути файл
@@ -0,0 +1,158 @@
//! Agents and how to launch their ACP servers: the built-in ones, plus user-defined
//! agents from `<config>/agents/<id>.toml`.
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ProviderSpec {
pub id: String,
pub name: String,
pub command: String,
pub args: Vec<String>,
pub env: Vec<(String, String)>,
/// How to sign in when the agent reports it needs authentication.
pub login_hint: String,
}
/// `(id, name, command line, sign-in hint)`. npm adapters are pinned so a session's
/// protocol does not change under the user.
const BUILTIN: &[(&str, &str, &[&str], &str)] = &[
(
"claude",
"Claude Code",
&["npx", "-y", "@agentclientprotocol/[email protected]"],
"Run `claude` in a terminal and sign in.",
),
("codex", "Codex", &["npx", "-y", "@agentclientprotocol/[email protected]"], "Run `codex login` in a terminal."),
("gemini", "Gemini CLI", &["gemini", "--experimental-acp"], "Run `gemini` in a terminal and sign in."),
("copilot", "GitHub Copilot", &["copilot", "--acp"], "Run `copilot` in a terminal and sign in."),
("cursor", "Cursor", &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
("opencode", "OpenCode", &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
("qwen", "Qwen Code", &["qwen", "--experimental-acp"], "Run `qwen` in a terminal and sign in."),
("kimi", "Kimi CLI", &["kimi", "acp"], "Run `kimi` in a terminal and sign in."),
("goose", "Goose", &["goose", "acp"], "Run `goose configure` in a terminal."),
("auggie", "Auggie", &["auggie", "--acp"], "Run `auggie login` in a terminal."),
("kiro", "Kiro", &["kiro-cli", "acp"], "Run `kiro-cli login` in a terminal."),
("vibe", "Mistral Vibe", &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
];
fn builtins() -> Vec<ProviderSpec> {
BUILTIN
.iter()
.map(|(id, name, cmd, hint)| ProviderSpec {
id: (*id).into(),
name: (*name).into(),
command: cmd[0].into(),
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
env: Vec::new(),
login_hint: (*hint).into(),
})
.collect()
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CustomAgent {
name: Option<String>,
command: String,
#[serde(default)]
args: Vec<String>,
#[serde(default)]
env: HashMap<String, String>,
}
/// Built-in agents, then the `*.toml` agents of `custom_dir`; a custom agent with a
/// built-in id replaces it.
pub(crate) fn load(custom_dir: Option<&Path>) -> Vec<ProviderSpec> {
let mut specs = builtins();
let mut files: Vec<PathBuf> = custom_dir
.and_then(|d| std::fs::read_dir(d).ok())
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
.collect();
files.sort();
for path in files {
let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue };
let parsed = std::fs::read_to_string(&path)
.map_err(|e| e.to_string())
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()));
let agent = match parsed {
Ok(a) => a,
Err(e) => {
tracing::warn!("skipping agent {}: {e}", path.display());
continue;
}
};
let mut env: Vec<(String, String)> = agent.env.into_iter().collect();
env.sort();
let spec = ProviderSpec {
name: agent.name.unwrap_or_else(|| id.clone()),
command: agent.command,
args: agent.args,
env,
login_hint: "Sign in with the agent's own command line first.".into(),
id,
};
match specs.iter_mut().find(|s| s.id == spec.id) {
Some(existing) => *existing = spec,
None => specs.push(spec),
}
}
specs
}
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
pub(crate) fn installed(command: &str) -> bool {
let p = Path::new(command);
if p.components().count() > 1 {
return is_executable(p);
}
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
std::env::var_os("PATH").is_some_and(|path| {
std::env::split_paths(&path).any(|dir| {
let c = dir.join(command);
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
})
})
}
fn is_executable(p: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
p.metadata().is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
{
p.is_file()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn custom_agents_extend_and_override_the_builtins() {
let dir = tempfile::tempdir().unwrap();
let write = |name: &str, text: &str| std::fs::write(dir.path().join(name), text).unwrap();
write("mine.toml", "name = \"Mine\"\ncommand = \"/opt/mine\"\nargs = [\"acp\"]\n[env]\nK = \"v\"\n");
write("gemini.toml", "command = \"gemini\"\nargs = [\"--acp\"]\n");
write("broken.toml", "nope = 1\n");
let specs = load(Some(dir.path()));
let mine = specs.iter().find(|s| s.id == "mine").unwrap();
assert_eq!((mine.name.as_str(), mine.command.as_str()), ("Mine", "/opt/mine"));
assert_eq!(mine.env, vec![("K".to_owned(), "v".to_owned())]);
let gemini = specs.iter().find(|s| s.id == "gemini").unwrap();
assert_eq!((gemini.name.as_str(), gemini.args.as_slice()), ("gemini", &["--acp".to_owned()][..]));
assert!(!specs.iter().any(|s| s.id == "broken"));
assert_eq!(specs.iter().filter(|s| s.id == "claude").count(), 1);
assert!(!installed("/definitely/not/here"));
assert!(installed("sh"));
}
}
+423
Переглянути файл
@@ -0,0 +1,423 @@
//! End-to-end task flow against an in-memory ACP agent.
use super::*;
use std::sync::OnceLock;
use tokio::io::duplex;
/// Says "Hi", edits a file, asks to run a command and reports what it was allowed.
#[derive(Default)]
struct FakeAgent {
peer: OnceLock<Peer>,
calls: Mutex<Vec<String>>,
}
impl FakeAgent {
fn update(&self, session: &str, update: Value) {
let peer = self.peer.get().unwrap();
peer.notify("session/update", json!({ "sessionId": session, "update": update })).unwrap();
}
fn say(&self, session: &str, text: &str) {
self.update(
session,
json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}}),
);
}
}
impl Handler for FakeAgent {
fn on_notification(&self, method: &str, _: Value) {
self.calls.lock().push(method.to_owned());
}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.calls.lock().push(method.to_owned());
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
match method {
"initialize" => Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true}})),
"session/new" => Ok(json!({"sessionId": "s1",
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
"configOptions": [{"id": "model", "category": "model", "type": "select", "currentValue": "big",
"options": [{"value": "big", "name": "Big"}, {"value": "small", "name": "Small"}]}]})),
"session/load" => {
self.say(&session, "replayed history");
Ok(json!({}))
}
"session/set_config_option" | "session/set_mode" => {
self.calls.lock().push(format!("{method} {}", params.get("value").or(params.get("modeId")).unwrap()));
Ok(json!({}))
}
"session/prompt" => {
let text = params.pointer("/prompt/0/text").and_then(Value::as_str).unwrap_or_default().to_owned();
if text == "again" {
self.say(&session, "second turn");
return Ok(json!({"stopReason": "end_turn"}));
}
if text == "wait" {
// Works until cancelled.
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
std::thread::sleep(Duration::from_millis(5));
}
return Ok(json!({"stopReason": "cancelled"}));
}
self.update(
&session,
json!({"sessionUpdate": "available_commands_update",
"availableCommands": [{"name": "review", "description": "Review", "input": {"hint": "focus"}}]}),
);
self.update(&session, json!({"sessionUpdate": "usage_update", "used": 50, "size": 1000}));
self.say(&session, "Hi");
self.update(
&session,
json!({"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Edit a.rs",
"kind": "edit", "status": "completed",
"content": [{"type": "diff", "path": "/p/a.rs", "oldText": "a\n", "newText": "b\n"}]}),
);
let peer = self.peer.get().unwrap().clone();
let answer: Value = tokio::runtime::Handle::current()
.block_on(peer.request(
"session/request_permission",
json!({"sessionId": session, "toolCall": {"toolCallId": "t1", "title": "Run cargo test"},
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"},
{"optionId": "no", "name": "Reject", "kind": "reject_once"}]}),
None,
))
.unwrap();
let chosen = answer.pointer("/outcome/optionId").and_then(Value::as_str).unwrap_or("none");
self.say(&session, &format!("chose {chosen}"));
Ok(json!({"stopReason": "end_turn"}))
}
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
}
}
}
fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
let connector: Connector = Arc::new(move |_spec, _cwd, client, _stderr| {
let (a, b) = duplex(1 << 20);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let server = Peer::connect_framed(br, bw, agent.clone(), Framing::Lines);
// Keep the latest connection: a restarted manager connects again.
let _ = agent.peer.set(server);
Ok(Peer::connect_framed(ar, aw, client, Framing::Lines))
});
AgentManager::with_connector(
AgentPaths {
project_root: dir.to_path_buf(),
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
custom_agents_dir: None,
},
tokio::runtime::Handle::current(),
connector,
)
}
async fn wait_for(mgr: &AgentManager, id: &str, status: AgentStatus) {
for _ in 0..500 {
if mgr.task(id).unwrap().state.lock().task.status == status {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("task never reached {status:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
let task = mgr
.create(NewAgentTask {
prompt: text("Fix the lexer\nmore detail"),
provider: "claude".into(),
config: vec![AgentConfigChoice { id: "model".into(), value: "small".into() }],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
assert_eq!(task.title, "Fix the lexer");
assert_ne!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready, "a new task is not settled");
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let permission = mgr
.entries(&task.id)
.unwrap()
.iter()
.find_map(|e| match e {
AgentEntry::Permission { id, .. } => Some(*id),
_ => None,
})
.unwrap();
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id).unwrap();
let kinds: Vec<String> = entries
.iter()
.map(|e| match e {
AgentEntry::User { text, .. } | AgentEntry::Agent { text } => text.clone(),
AgentEntry::Tool { title, .. } => title.clone(),
AgentEntry::Permission { chosen, .. } => format!("permission: {}", chosen.clone().unwrap_or_default()),
other => format!("{other:?}"),
})
.collect();
assert_eq!(kinds, ["Fix the lexer\nmore detail", "Hi", "Edit a.rs", "permission: Allow", "chose yes"]);
assert!(
agent.calls.lock().contains(&"session/set_config_option \"small\"".to_owned()),
"switched to the chosen model"
);
{
let t = mgr.task(&task.id).unwrap().state.lock().task.clone();
assert_eq!(t.model.as_deref(), Some("small"));
let modes = t.config.iter().find(|o| o.id == "mode").unwrap();
assert_eq!((modes.via, modes.current.as_deref()), (AgentConfigVia::Mode, Some("ask")));
assert_eq!(t.commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["review"]);
assert_eq!(t.usage.as_ref().map(|u| (u.used, u.size)), Some((50, 1000)));
}
mgr.set_config(&task.id, "mode", "code".into()).await.unwrap();
assert!(agent.calls.lock().contains(&"session/set_mode \"code\"".to_owned()));
assert!(mgr.set_config(&task.id, "mode", "nope".into()).await.is_err());
tokio::time::sleep(FLUSH_DELAY * 3).await;
{
let events = events.lock();
assert!(
events.iter().any(|e| matches!(e, AgentEvent::Task { task } if task.status == AgentStatus::NeedsInput))
);
let last_entry = events.iter().rev().find_map(|e| match e {
AgentEvent::Entry { index, entry, .. } => Some((*index, entry.clone())),
_ => None,
});
assert_eq!(last_entry, Some((4, AgentEntry::Agent { text: "chose yes".into() })));
}
let providers = mgr.providers();
let claude = providers.iter().find(|p| p.id == "claude").unwrap();
assert_eq!(claude.config.iter().map(|o| o.id.as_str()).collect::<Vec<_>>(), ["model", "mode"]);
assert_eq!(claude.commands.len(), 1);
// A new manager (IDE restart) finds the task and resumes its session without duplicating history.
mgr.shutdown();
let agent2 = Arc::new(FakeAgent::default());
let mgr2 = manager(tmp.path(), agent2.clone());
assert_eq!(mgr2.entries(&task.id).unwrap().len(), 5);
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
let entries = mgr2.entries(&task.id).unwrap();
assert_eq!(entries.len(), 7);
assert_eq!(entries[6], AgentEntry::Agent { text: "second turn".into() });
assert!(agent2.calls.lock().contains(&"session/load".to_owned()));
// The chosen settings are re-applied to the reloaded session.
let calls = agent2.calls.lock().clone();
assert!(calls.contains(&"session/set_mode \"code\"".to_owned()), "{calls:?}");
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
#[tokio::test(flavor = "multi_thread")]
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
mgr.prompt(&task.id, text("again"), false).await.unwrap();
let queue = mgr.task(&task.id).unwrap().state.lock().task.queue.clone();
assert_eq!(queue.iter().map(|q| q.prompt.text.as_str()).collect::<Vec<_>>(), ["again"]);
assert!(mgr.prompt(&task.id, text(" "), false).await.is_err());
mgr.send_queued_now(&task.id, &queue[0].id).unwrap();
for _ in 0..500 {
if mgr.entries(&task.id).unwrap().iter().any(|e| *e == AgentEntry::Agent { text: "second turn".into() }) {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let users: Vec<String> = mgr
.entries(&task.id)
.unwrap()
.into_iter()
.filter_map(|e| match e {
AgentEntry::User { text, .. } => Some(text),
_ => None,
})
.collect();
assert_eq!(users, ["wait", "again"]);
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
// Stopping a turn keeps the queue for later.
mgr.prompt(&task.id, text("wait"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
agent.calls.lock().retain(|c| c != "session/cancel");
mgr.prompt(&task.id, text("later"), false).await.unwrap();
mgr.cancel(&task.id).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let queued = mgr.task(&task.id).unwrap().state.lock().task.queue.clone();
assert_eq!(queued.len(), 1);
assert_eq!(mgr.unqueue(&task.id, &queued[0].id).unwrap().prompt.text, "later");
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
}
#[test]
fn prompts_become_acp_content_blocks() {
let p = AgentPrompt {
text: "look".into(),
files: vec![IpcPath(PathBuf::from("/p/my file.rs"))],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None }],
};
assert_eq!(
blocks(&p, &[]),
[
json!({"type": "text", "text": "look"}),
json!({"type": "resource_link", "uri": "file:///p/my%20file.rs", "name": "my file.rs"}),
json!({"type": "image", "mimeType": "image/png", "data": "AAA"}),
]
);
assert_eq!(
blocks(&p, &[Some("fn a() {}".into())])[1],
json!({"type": "resource", "resource": {"uri": "file:///p/my%20file.rs", "text": "fn a() {}"}})
);
let old = upgrade(
json!({"task": {"id": "t"}, "entries": [{"type": "user", "text": "hi"}, {"type": "agent", "text": "a"}]}),
);
assert_eq!(old["task"]["queue"], json!([]));
assert_eq!(old["entries"][0]["attachments"], json!([]));
assert!(old["entries"][1].get("attachments").is_none());
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
assert!(clean(text(" ")).is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("do it"),
provider: "codex".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.cancel(&task.id).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")));
assert_eq!(entries.last(), Some(&AgentEntry::Agent { text: "chose none".into() }));
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.model.as_deref(), Some("big"), "the agent's default");
mgr.delete(&task.id, false).await.unwrap();
assert!(mgr.entries(&task.id).is_err());
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
assert!(
mgr.create(NewAgentTask {
prompt: text(" "),
provider: "codex".into(),
config: vec![],
isolation: Isolation::Local,
base: None
})
.await
.is_err()
);
}
/// Drives the real Claude Code adapter (needs `npx`, network and a signed-in `claude`):
/// `OPENIDEA_AGENT_E2E=1 cargo test -p ide-agent real_claude -- --ignored --nocapture`.
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn real_claude_task_in_a_worktree() {
if std::env::var_os("OPENIDEA_AGENT_E2E").is_none() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
for args in [&["init", "-q", "-b", "main"][..], &["commit", "-q", "--allow-empty", "-m", "init"]] {
let ok = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(&repo)
.status()
.unwrap()
.success();
assert!(ok);
}
let mgr = AgentManager::new(
AgentPaths {
project_root: repo.clone(),
store_dir: tmp.path().join("store"),
worktrees_dir: tmp.path().join("wt"),
models_file: tmp.path().join("models.json"),
custom_agents_dir: None,
},
tokio::runtime::Handle::current(),
);
let task = mgr
.create(NewAgentTask {
prompt: text("Create a file named hello.txt containing the single word hi. Do nothing else."),
provider: "claude".into(),
config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }],
isolation: Isolation::Worktree,
base: None,
})
.await
.unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(240);
loop {
assert!(std::time::Instant::now() < deadline, "timed out");
let status = mgr.task(&task.id).unwrap().state.lock().task.status;
match status {
AgentStatus::NeedsInput => {
let pending = mgr.entries(&task.id).unwrap().into_iter().rev().find_map(|e| match e {
AgentEntry::Permission { id, options, chosen: None, .. } => Some((id, options)),
_ => None,
});
if let Some((id, options)) = pending {
let allow = options.iter().find(|o| o.kind == "allow_once").or(options.first()).unwrap();
eprintln!("allowing: {}", allow.name);
let _ = mgr.respond(&task.id, id, Some(allow.id.clone()));
}
}
AgentStatus::Ready | AgentStatus::Failed => break,
_ => {}
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
for e in mgr.entries(&task.id).unwrap() {
eprintln!("{e:?}");
}
let t = mgr.task(&task.id).unwrap().state.lock().task.clone();
assert_eq!(t.status, AgentStatus::Ready, "{:?}", t.error);
assert_eq!(t.model.as_deref(), Some("haiku"));
let changes = mgr.changes(&task.id).await.unwrap();
assert!(changes.iter().any(|c| c.rel_path == "hello.txt"), "{changes:?}");
assert!(!repo.join("hello.txt").exists(), "the project checkout is untouched");
assert!(!mgr.providers().iter().find(|p| p.id == "claude").unwrap().config.is_empty());
mgr.shutdown();
}
+304
Переглянути файл
@@ -0,0 +1,304 @@
//! Folds ACP `session/update` notifications into a task's entries.
use crate::model::{AgentEntry, AgentPlanItem, AgentToolDiff, AgentToolStatus};
use ide_core::IpcPath;
use serde_json::Value;
use std::collections::HashMap;
/// Tool output kept per call; longer output keeps its tail.
const MAX_OUTPUT: usize = 64 * 1024;
#[derive(Default)]
pub(crate) struct Timeline {
pub entries: Vec<AgentEntry>,
tools: HashMap<String, usize>,
plan: Option<usize>,
}
/// What a `session/update` changed in the timeline.
#[derive(Debug, Default, PartialEq)]
pub(crate) struct Applied {
/// Indices of the entries added or changed.
pub changed: Vec<usize>,
}
impl Timeline {
pub fn from_entries(entries: Vec<AgentEntry>) -> Self {
let mut t = Self { entries, ..Self::default() };
for (i, e) in t.entries.iter().enumerate() {
match e {
AgentEntry::Tool { id, .. } => {
t.tools.insert(id.clone(), i);
}
AgentEntry::Plan { .. } => t.plan = Some(i),
_ => {}
}
}
t
}
pub fn has_tool(&self, id: &str) -> bool {
self.tools.contains_key(id)
}
pub fn push(&mut self, entry: AgentEntry) -> usize {
self.entries.push(entry);
self.entries.len() - 1
}
/// Applies one `session/update` `update` object.
pub fn apply(&mut self, update: &Value) -> Applied {
let mut out = Applied::default();
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
match kind {
"agent_message_chunk" | "agent_thought_chunk" => {
let Some(text) = content_text(update.get("content")) else { return out };
out.changed.push(self.append_text(kind == "agent_thought_chunk", &text));
}
"tool_call" => {
let id = str_field(update, "toolCallId");
let entry = AgentEntry::Tool {
id: id.clone(),
title: str_field(update, "title"),
kind: update.get("kind").and_then(Value::as_str).unwrap_or("other").to_owned(),
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
locations: locations(update.get("locations")),
output: None,
diffs: Vec::new(),
};
let index = match self.tools.get(&id) {
Some(&i) => {
self.entries[i] = entry;
i
}
None => {
let i = self.push(entry);
self.tools.insert(id, i);
i
}
};
self.merge_tool(index, update);
out.changed.push(index);
}
"tool_call_update" => {
let Some(&index) = self.tools.get(&str_field(update, "toolCallId")) else { return out };
self.merge_tool(index, update);
out.changed.push(index);
}
"plan" => {
let items = update
.get("entries")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.map(|e| AgentPlanItem { content: str_field(e, "content"), status: str_field(e, "status") })
.collect()
})
.unwrap_or_default();
let entry = AgentEntry::Plan { items };
let index = match self.plan {
Some(i) => {
self.entries[i] = entry;
i
}
None => self.push(entry),
};
self.plan = Some(index);
out.changed.push(index);
}
_ => {}
}
out
}
fn append_text(&mut self, thought: bool, text: &str) -> usize {
match self.entries.last_mut() {
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
Some(AgentEntry::Thought { text: t }) if thought => t.push_str(text),
_ => {
let text = text.to_owned();
return self.push(if thought { AgentEntry::Thought { text } } else { AgentEntry::Agent { text } });
}
}
self.entries.len() - 1
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, .. } = &mut self.entries[index]
else {
return;
};
if let Some(t) = update.get("title").and_then(Value::as_str) {
*title = t.to_owned();
}
if let Some(k) = update.get("kind").and_then(Value::as_str) {
*kind = k.to_owned();
}
if let Some(s) = tool_status(update.get("status")) {
*status = s;
}
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new();
let mut new_diffs = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
if let Some(t) = content_text(item.get("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() {
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
}
/// Settles what an ended turn left open: running tools and pending permissions.
pub fn end_turn(&mut self) -> Vec<usize> {
let mut changed = Vec::new();
for (i, e) in self.entries.iter_mut().enumerate() {
match e {
AgentEntry::Tool { status, .. }
if matches!(status, AgentToolStatus::Pending | AgentToolStatus::Running) =>
{
*status = AgentToolStatus::Failed;
changed.push(i);
}
AgentEntry::Permission { chosen, .. } if chosen.is_none() => {
*chosen = Some("Cancelled".into());
changed.push(i);
}
_ => {}
}
}
changed
}
}
fn str_field(v: &Value, key: &str) -> String {
v.get(key).and_then(Value::as_str).unwrap_or_default().to_owned()
}
fn content_text(content: Option<&Value>) -> Option<String> {
let c = content?;
match c.get("type").and_then(Value::as_str) {
Some("text") => c.get("text").and_then(Value::as_str).map(str::to_owned),
Some("resource_link") => c.get("uri").and_then(Value::as_str).map(str::to_owned),
Some("resource") => c.pointer("/resource/text").and_then(Value::as_str).map(str::to_owned),
_ => None,
}
}
fn tool_status(v: Option<&Value>) -> Option<AgentToolStatus> {
Some(match v?.as_str()? {
"pending" => AgentToolStatus::Pending,
"in_progress" => AgentToolStatus::Running,
"completed" => AgentToolStatus::Completed,
"failed" => AgentToolStatus::Failed,
_ => return None,
})
}
fn locations(v: Option<&Value>) -> Vec<IpcPath> {
v.and_then(Value::as_array)
.map(|a| a.iter().filter_map(|l| l.get("path")?.as_str()).map(|p| IpcPath(p.into())).collect())
.unwrap_or_default()
}
fn line_stats(old: &str, new: &str) -> (u32, u32) {
ide_vcs::diff_hunks(old, new).iter().fold((0, 0), |(a, r), h| (a + h.lines, r + h.old_lines))
}
fn tail(mut text: String) -> String {
if text.len() > MAX_OUTPUT {
let mut cut = text.len() - MAX_OUTPUT;
while !text.is_char_boundary(cut) {
cut += 1;
}
text.replace_range(..cut, "…");
}
text
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
let chunk = |s: &str| json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": s}});
assert_eq!(t.apply(&chunk("Hel")).changed, vec![0]);
assert_eq!(t.apply(&chunk("lo")).changed, vec![0]);
t.apply(&json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm"}}));
t.apply(&chunk("again"));
assert_eq!(
t.entries,
vec![
AgentEntry::Agent { text: "Hello".into() },
AgentEntry::Thought { text: "hmm".into() },
AgentEntry::Agent { text: "again".into() },
]
);
}
#[test]
fn tool_calls_update_in_place() {
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c1", "title": "Edit a.rs", "kind": "edit",
"status": "pending", "locations": [{"path": "/p/a.rs", "line": 3}]}));
let applied = t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "completed",
"content": [
{"type": "diff", "path": "/p/a.rs", "oldText": "a\nb\n", "newText": "a\nB\nc\n"},
{"type": "content", "content": {"type": "text", "text": "done"}}
]}));
assert_eq!(applied.changed, vec![0]);
let AgentEntry::Tool { status, diffs, output, locations, .. } = &t.entries[0] else { panic!() };
assert_eq!(*status, AgentToolStatus::Completed);
assert_eq!(diffs, &vec![AgentToolDiff { path: IpcPath("/p/a.rs".into()), added: 2, removed: 1 }]);
assert_eq!(output.as_deref(), Some("done"));
assert_eq!(locations, &vec![IpcPath("/p/a.rs".into())]);
// Unknown calls are ignored.
assert!(t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "zz"})).changed.is_empty());
}
#[test]
fn plan_is_one_entry_and_end_turn_settles_open_items() {
let mut t = Timeline::default();
let plan =
|s: &str| json!({"sessionUpdate": "plan", "entries": [{"content": "x", "priority": "high", "status": s}]});
t.apply(&plan("pending"));
t.push(AgentEntry::Agent { text: "between".into() });
assert_eq!(t.apply(&plan("completed")).changed, vec![0]);
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "title": "Run", "status": "in_progress"}));
t.push(AgentEntry::Permission { id: 1, title: "Run?".into(), options: vec![], chosen: None });
assert_eq!(t.end_turn(), vec![2, 3]);
let again = Timeline::from_entries(t.entries.clone());
assert_eq!(again.plan, Some(0));
assert_eq!(again.tools.get("c"), Some(&2));
}
#[test]
fn long_output_keeps_its_tail() {
let s = tail("é".repeat(MAX_OUTPUT));
assert!(s.starts_with('…') && s.len() <= MAX_OUTPUT + 3);
}
}
+156
Переглянути файл
@@ -0,0 +1,156 @@
//! Task worktrees and the changes made in them.
use crate::model::AgentChange;
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_vcs::{ChangeKind, Repo};
use std::path::{Path, PathBuf};
pub(crate) struct Created {
pub path: PathBuf,
pub branch: String,
pub base: String,
pub base_commit: String,
}
fn repo_at(path: &Path) -> IdeResult<Repo> {
Repo::discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display())))
}
/// The current branch (or commit when detached) and its commit.
pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
let info = repo_at(path)?.branch_info()?;
let commit = info.head_commit.ok_or_else(|| IdeError::unavailable("the repository has no commits yet"))?;
Ok((info.head.unwrap_or_else(|| commit.clone()), commit))
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
let repo = repo_at(project_root)?;
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
Some(b) => {
let commit =
repo.merge_base(b, b)?.ok_or_else(|| IdeError::not_found(format!("no branch or revision {b}")))?;
(b.to_owned(), commit)
}
None => head_of(project_root)?,
};
std::fs::create_dir_all(worktrees_dir).map_err(|e| IdeError::internal(e.to_string()))?;
let branch_exists = |s: &str| {
let r = format!("refs/heads/agent/{s}");
repo.merge_base(&r, &r).ok().flatten().is_some()
};
let slug = unique_slug(&slugify(title), |s| worktrees_dir.join(s).exists() || branch_exists(s));
let path = worktrees_dir.join(&slug);
let branch = format!("agent/{slug}");
repo.add_worktree(&path, &base_commit, Some(&branch))?;
Ok(Created { path, branch, base, base_commit })
}
pub(crate) fn remove(project_root: &Path, path: &Path) -> IdeResult<()> {
repo_at(project_root)?.remove_worktree(path, true)
}
/// Files under `cwd` that differ from `base` (untracked files included), with line counts.
pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
let repo = repo_at(cwd)?;
let root = repo.root().to_path_buf();
let stats = repo.numstat_with_worktree(base)?;
let stat = |rel: &str| stats.iter().find(|(p, ..)| p == rel).map_or((0, 0), |&(_, a, r)| (a, r));
let mut out: Vec<AgentChange> = repo
.diff_with_worktree(base)?
.into_iter()
.map(|f| {
let (added, removed) = stat(&f.path);
AgentChange { path: IpcPath(root.join(&f.path)), rel_path: f.path, kind: f.kind, added, removed }
})
.collect();
for s in repo.status()? {
if s.unstaged == Some(ChangeKind::Untracked) && !out.iter().any(|c| c.rel_path == s.rel_path) {
let added = std::fs::read_to_string(&*s.path).map_or(0, |t| t.lines().count() as u32);
out.push(AgentChange { path: s.path, rel_path: s.rel_path, kind: ChangeKind::Added, added, removed: 0 });
}
}
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
Ok(out)
}
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
repo_at(cwd)?.file_at(path, Some(rev))
}
/// A short ASCII branch-safe name from the task title.
pub(crate) fn slugify(title: &str) -> String {
let mut out = String::new();
for c in title.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_lowercase());
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
if out.len() >= 32 {
break;
}
}
let out = out.trim_matches('-');
if out.is_empty() { "task".to_owned() } else { out.to_owned() }
}
fn unique_slug(base: &str, taken: impl Fn(&str) -> bool) -> String {
if !taken(base) {
return base.to_owned();
}
(2..).map(|n| format!("{base}-{n}")).find(|s| !taken(s)).expect("unbounded")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugs_are_branch_safe() {
assert_eq!(slugify("Fix lexer UTF-16 columns!"), "fix-lexer-utf-16-columns");
assert_eq!(slugify("修复 lexer 越界"), "lexer");
assert_eq!(slugify("修复越界"), "task");
assert_eq!(slugify(&"a".repeat(50)).len(), 32);
assert_eq!(unique_slug("x", |s| s == "x" || s == "x-2"), "x-3");
}
fn git(dir: &Path, args: &[&str]) {
let ok = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(dir)
.status()
.unwrap()
.success();
assert!(ok, "git {args:?}");
}
#[test]
fn worktree_changes_are_listed_against_the_base() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\ntwo\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let created = create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap();
assert_eq!(created.branch, "agent/edit-a");
assert_eq!(created.base, "main");
std::fs::write(created.path.join("a.txt"), "one\nTWO\nthree\n").unwrap();
std::fs::write(created.path.join("new.txt"), "x\ny\n").unwrap();
let got = changes(&created.path, &created.base_commit).unwrap();
let summary: Vec<_> = got.iter().map(|c| (c.rel_path.as_str(), c.kind, c.added, c.removed)).collect();
assert_eq!(summary, [("a.txt", ChangeKind::Modified, 2, 1), ("new.txt", ChangeKind::Added, 2, 0)]);
let base_text = file_at(&created.path, &created.path.join("a.txt"), &created.base_commit).unwrap();
assert_eq!(base_text.as_deref(), Some("one\ntwo\n"));
// A second task with the same title gets its own worktree.
assert_eq!(create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap().branch, "agent/edit-a-2");
remove(&repo, &created.path).unwrap();
assert!(!created.path.exists());
}
}
+8
Переглянути файл
@@ -0,0 +1,8 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP read/write, no window or message loop"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
+293
Переглянути файл
@@ -0,0 +1,293 @@
//! The file list on the OS clipboard: what Explorer copies when the user
//! copies files, so the project view can paste them, and what the project view
//! writes so Explorer can paste the files it copied (IDEA does both).
//!
//! Windows keeps it as `CF_HDROP`: a `DROPFILES` header and a double-NUL
//! terminated list of absolute paths, wide when `fWide` is set. The data is set
//! in full rather than rendered on demand, so no window or message loop is
//! needed and the list survives after `CloseClipboard`.
//!
//! Other platforms keep file lists elsewhere (`public.file-url` on macOS,
//! `text/uri-list` on X11) and are not wired up: [`files`] is empty and
//! [`set_files`] fails there.
use std::path::PathBuf;
/// Size of `DROPFILES`: `pFiles`, `pt` (two `LONG`s), `fNC`, `fWide`.
const HEADER: usize = 20;
/// The absolute paths on the clipboard, empty when it holds no file list.
pub fn files() -> Vec<PathBuf> {
imp::files()
}
/// Whether the clipboard holds a file list, without reading it.
pub fn has_files() -> bool {
imp::has_files()
}
/// Replaces the clipboard with `paths`. False when it is busy or holds nothing
/// to write; the clipboard is a shared resource, so callers treat this as
/// best-effort.
pub fn set_files(paths: &[PathBuf]) -> bool {
if paths.is_empty() {
return false;
}
imp::set_files(paths)
}
/// `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> {
let mut units: Vec<u16> = Vec::new();
for path in paths {
let path = path.to_string_lossy();
if path.is_empty() {
continue;
}
units.extend(path.encode_utf16());
units.push(0);
}
// The list ends with an empty string: with one path, two NULs in a row.
units.push(0);
let mut out = Vec::with_capacity(HEADER + units.len() * 2);
out.extend_from_slice(&(HEADER as u32).to_le_bytes()); // pFiles: list starts after the header
out.extend_from_slice(&[0u8; 8]); // pt: the drop point, unused
out.extend_from_slice(&0u32.to_le_bytes()); // fNC: not a file manager drop
out.extend_from_slice(&1u32.to_le_bytes()); // fWide: UTF-16 paths
for unit in units {
out.extend_from_slice(&unit.to_le_bytes());
}
out
}
/// The paths of a `DROPFILES` block, stopping at the empty string that ends the
/// list. An ANSI list (pre-Unicode writers) is decoded as UTF-8, lossily.
pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
if bytes.len() < HEADER {
return Vec::new();
}
let offset = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
let wide = u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]) != 0;
if offset >= bytes.len() {
return Vec::new();
}
let body = &bytes[offset..];
let mut out = Vec::new();
if wide {
let mut current: Vec<u16> = Vec::new();
for chunk in body.as_chunks::<2>().0 {
let unit = u16::from_le_bytes(*chunk);
if unit != 0 {
current.push(unit);
} else if current.is_empty() {
break;
} else {
out.push(PathBuf::from(String::from_utf16_lossy(&current)));
current.clear();
}
}
} else {
for part in body.split(|b| *b == 0) {
if part.is_empty() {
break;
}
out.push(PathBuf::from(String::from_utf8_lossy(part).into_owned()));
}
}
out
}
#[cfg(windows)]
mod imp {
use super::{HEADER, decode, encode};
use std::ffi::c_void;
use std::path::PathBuf;
use std::ptr;
use std::time::Duration;
/// `CF_HDROP`, the clipboard format holding a file list.
const CF_HDROP: u32 = 15;
/// An `HGLOBAL` or a `HANDLE`: both are opaque pointers here.
type Handle = *mut c_void;
const GMEM_MOVEABLE: u32 = 0x0002;
/// Another process holds the clipboard only while it copies; retrying beats
/// reporting "no files" for a paste the user just made.
const OPEN_ATTEMPTS: usize = 10;
const OPEN_RETRY: Duration = Duration::from_millis(20);
#[link(name = "user32")]
unsafe extern "system" {
fn OpenClipboard(owner: Handle) -> i32;
fn CloseClipboard() -> i32;
fn EmptyClipboard() -> i32;
fn GetClipboardData(format: u32) -> Handle;
fn SetClipboardData(format: u32, memory: Handle) -> Handle;
fn IsClipboardFormatAvailable(format: u32) -> i32;
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn GlobalAlloc(flags: u32, bytes: usize) -> Handle;
fn GlobalLock(memory: Handle) -> *mut c_void;
fn GlobalUnlock(memory: Handle) -> i32;
fn GlobalFree(memory: Handle) -> Handle;
fn GlobalSize(memory: Handle) -> usize;
}
/// Opens the clipboard as its owner: the list is written in full, so no
/// owning window is needed.
fn open() -> bool {
for _ in 0..OPEN_ATTEMPTS {
if unsafe { OpenClipboard(ptr::null_mut()) } != 0 {
return true;
}
std::thread::sleep(OPEN_RETRY);
}
false
}
pub fn has_files() -> bool {
(unsafe { IsClipboardFormatAvailable(CF_HDROP) }) != 0
}
pub fn files() -> Vec<PathBuf> {
if !has_files() || !open() {
return Vec::new();
}
let memory = unsafe { GetClipboardData(CF_HDROP) };
let paths = if memory.is_null() {
Vec::new()
} else {
// SAFETY: the clipboard keeps the block alive while it is open, and
// `GlobalSize` bounds the bytes read from it.
unsafe {
let data = GlobalLock(memory);
if data.is_null() {
Vec::new()
} else {
let bytes = std::slice::from_raw_parts(data as *const u8, GlobalSize(memory));
let paths = decode(bytes);
GlobalUnlock(memory);
paths
}
}
};
unsafe { CloseClipboard() };
paths
}
pub fn set_files(paths: &[PathBuf]) -> bool {
let bytes = encode(paths);
if bytes.len() <= HEADER {
return false;
}
// SAFETY: the block is allocated, filled, handed to the clipboard and
// freed only on the paths where the clipboard did not take ownership.
unsafe {
let memory = GlobalAlloc(GMEM_MOVEABLE, bytes.len());
if memory.is_null() {
return false;
}
let data = GlobalLock(memory);
if data.is_null() {
GlobalFree(memory);
return false;
}
ptr::copy_nonoverlapping(bytes.as_ptr(), data as *mut u8, bytes.len());
GlobalUnlock(memory);
if !open() {
GlobalFree(memory);
return false;
}
// Replacing the list also drops the text the user copied before.
if EmptyClipboard() == 0 {
CloseClipboard();
GlobalFree(memory);
return false;
}
let taken = !SetClipboardData(CF_HDROP, memory).is_null();
CloseClipboard();
if !taken {
GlobalFree(memory);
}
taken
}
}
}
#[cfg(not(windows))]
mod imp {
use std::path::PathBuf;
pub fn has_files() -> bool {
false
}
pub fn files() -> Vec<PathBuf> {
Vec::new()
}
pub fn set_files(_paths: &[PathBuf]) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
fn paths(list: &[&str]) -> Vec<PathBuf> {
list.iter().map(PathBuf::from).collect()
}
#[test]
fn a_written_list_reads_back_unchanged() {
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
assert_eq!(decode(&encode(&list)), list);
}
#[test]
fn the_header_says_where_the_paths_start_and_that_they_are_wide() {
let bytes = encode(&paths(&["C:/a"]));
assert_eq!(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]), HEADER as u32);
assert_eq!(u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]), 1);
// `C:/a` plus its NUL, then the empty string that ends the list.
assert_eq!(bytes.len(), HEADER + (4 + 1 + 1) * 2);
assert_eq!(&bytes[HEADER + 6..HEADER + 8], b"a\0");
assert_eq!(&bytes[bytes.len() - 4..], &[0, 0, 0, 0]);
}
#[test]
fn names_outside_the_ansi_code_page_survive() {
let list = paths(&["C:/工作/文档/测试.txt", "C:/a/"]);
assert_eq!(decode(&encode(&list)), list);
}
#[test]
fn an_empty_list_has_no_paths() {
assert_eq!(decode(&encode(&[])), Vec::<PathBuf>::new());
// A lone terminator is enough for the reader to stop.
assert_eq!(decode(&[0u8; HEADER]), Vec::<PathBuf>::new());
}
#[test]
fn a_truncated_or_foreign_block_reads_as_no_paths() {
assert_eq!(decode(&[]), Vec::<PathBuf>::new());
assert_eq!(decode(&[1, 2, 3]), Vec::<PathBuf>::new());
let mut far = encode(&paths(&["C:/a"]));
far[0] = 0xff; // pFiles past the end
assert_eq!(decode(&far), Vec::<PathBuf>::new());
}
#[test]
fn an_ansi_list_is_still_read_before_the_terminator() {
let mut bytes = vec![0u8; HEADER];
bytes[..4].copy_from_slice(&(HEADER as u32).to_le_bytes());
bytes[16] = 0; // fWide: the list is single-byte
bytes.extend_from_slice(b"C:\\a\\b.txt\0C:\\c\0\0");
assert_eq!(decode(&bytes), paths(&["C:\\a\\b.txt", "C:\\c"]));
}
}
+9
Переглянути файл
@@ -64,6 +64,10 @@ pub struct InspectionOverride {
pub enabled: Option<bool>,
#[specta(optional)]
pub severity: Option<InspectionLevel>,
/// The inspection's own options (Typo: `processCode`, `processLiterals`,
/// `processComments`); absent ones keep their defaults.
#[specta(optional)]
pub options: Option<BTreeMap<String, bool>>,
}
/// IDEA's highlighting levels.
@@ -101,5 +105,10 @@ mod tests {
assert_eq!(s.ide_profiles["strict"].name, "Strict");
assert_eq!(s.ide_profiles["strict"].overrides["lsp:ruff"].severity, Some(InspectionLevel::Error));
assert!(serde_json::from_str::<InspectionSettings>(r#"{"default":{"x":{"severity":"loud"}}}"#).is_err());
let s: InspectionSettings =
serde_json::from_str(r#"{"default":{"builtin:spelling":{"options":{"processCode":false}}}}"#).unwrap();
assert!(!s.default["builtin:spelling"].options.as_ref().unwrap()["processCode"]);
let back: InspectionSettings = serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap();
assert_eq!(back, s);
}
}
+33
Переглянути файл
@@ -1,6 +1,8 @@
//! Child-process helpers shared by every crate that spawns tools.
use std::ffi::{OsStr, OsString};
use std::process::Command;
use std::sync::OnceLock;
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
/// with other flags. Prefer [`no_window`] otherwise.
@@ -18,3 +20,34 @@ pub fn no_window(cmd: &mut Command) -> &mut Command {
}
cmd
}
static SHELL_ENV: OnceLock<Vec<(OsString, OsString)>> = OnceLock::new();
/// Records the login shell's environment, read once at startup off the main thread.
pub fn set_shell_env(vars: Vec<(OsString, OsString)>) {
let _ = SHELL_ENV.set(vars);
}
/// The login shell's variables this process lacks: an app started from Finder/Dock gets only
/// PATH from the shell, not what rc files export (API keys and provider switches, SDK homes...).
/// Apply before a call site's own variables so those win. Empty until the shell has been read.
pub fn shell_env() -> impl Iterator<Item = (&'static OsStr, &'static OsStr)> {
SHELL_ENV
.get()
.into_iter()
.flatten()
.filter(|(k, _)| std::env::var_os(k).is_none())
.map(|(k, v)| (k.as_os_str(), v.as_os_str()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shell_env_adds_only_what_the_process_lacks() {
set_shell_env(vec![("OPENIDEA_SHELL_ONLY_VAR".into(), "1".into()), ("PATH".into(), "/from/shell".into())]);
let vars: Vec<_> = shell_env().collect();
assert_eq!(vars, [(OsStr::new("OPENIDEA_SHELL_ONLY_VAR"), OsStr::new("1"))]);
}
}
+23
Переглянути файл
@@ -289,9 +289,18 @@ pub struct EditorSettings {
pub color_scheme: String,
/// Color Scheme edits: scheme id → attribute id → override.
pub color_overrides: BTreeMap<String, BTreeMap<String, TextAttributesOverride>>,
/// Color Scheme › Language Defaults › Semantic highlighting: local variables and
/// parameters get a colour derived from their name (IDEA's rainbow identifiers).
pub semantic_highlighting: bool,
/// Color Scheme › Language Defaults › Rainbow brackets: `()`, `[]`, `{}` coloured by depth.
pub rainbow_brackets: bool,
pub ligatures: bool,
/// Fallback font for glyphs the main font lacks; empty = none.
pub fallback_font: String,
/// Typography Settings › Main font weight (CSS 100–900), as IDEA.
pub font_weight: u16,
/// Typography Settings › Bold font weight: wherever the editor renders bold.
pub bold_font_weight: u16,
pub general: EditorGeneralSettings,
pub appearance: EditorAppearanceSettings,
pub breadcrumbs: BreadcrumbsSettings,
@@ -325,8 +334,12 @@ impl Default for EditorSettings {
format_on_save: false,
color_scheme: "theme-default".into(),
color_overrides: BTreeMap::new(),
semantic_highlighting: false,
rainbow_brackets: false,
ligatures: false,
fallback_font: String::new(),
font_weight: 400,
bold_font_weight: 700,
general: EditorGeneralSettings::default(),
appearance: EditorAppearanceSettings::default(),
breadcrumbs: BreadcrumbsSettings::default(),
@@ -564,6 +577,16 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn editor_font_weights_default_to_regular_and_bold() {
let json = serde_json::to_value(Settings::default()).unwrap();
assert_eq!(json["editor"]["fontWeight"], 400);
assert_eq!(json["editor"]["boldFontWeight"], 700);
let s: Settings = serde_json::from_str(r#"{"editor":{"fontWeight":300,"boldFontWeight":600}}"#).unwrap();
assert_eq!((s.editor.font_weight, s.editor.bold_font_weight), (300, 600));
assert_eq!(s.editor.font_size, 13.0);
}
#[test]
fn keymap_overrides_are_camel_case_and_default_empty() {
let s: Settings =
+70 -7
Переглянути файл
@@ -18,6 +18,8 @@ use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader};
use tokio::process::{Child, Command};
pub const PORT_PLACEHOLDER: &str = "${port}";
/// Replaced by the session's working directory (the project) in adapter arguments.
pub const ROOT_PLACEHOLDER: &str = "${root}";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Transport {
@@ -36,6 +38,11 @@ pub struct AdapterSpec {
pub cwd: PathBuf,
/// Extra environment of the adapter process (debugpy's private copy on `PYTHONPATH`).
pub env: Vec<(String, String)>,
/// Host of an adapter that is already running (`debugServer`); `None` is the loopback interface.
pub server_host: Option<String>,
/// `host:port` of an adapter inside another program (the Godot editor): connected to
/// when it accepts, else `command` is started.
pub connect: Option<String>,
}
/// Built-in adapters used when no language definition names `adapter`.
@@ -45,6 +52,7 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
command: command.to_owned(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
transport: transport.to_owned(),
connect: None,
install_hint: Some(hint.to_owned()),
};
Some(match adapter {
@@ -116,6 +124,8 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
install_hint: config.install_hint.clone(),
cwd,
env: Vec::new(),
server_host: None,
connect: config.connect.clone(),
}
}
@@ -124,6 +134,19 @@ pub fn substitute_port(args: &[String], port: u16) -> Vec<String> {
args.iter().map(|a| a.replace(PORT_PLACEHOLDER, &port.to_string())).collect()
}
/// Replaces every `${root}` occurrence with `root`.
pub fn substitute_root(args: &[String], root: &Path) -> Vec<String> {
let root = root.to_string_lossy();
args.iter().map(|a| a.replace(ROOT_PLACEHOLDER, &root)).collect()
}
/// Splits `host:port` (`[v6]:port`).
pub fn parse_address(addr: &str) -> Option<(String, u16)> {
let (host, port) = addr.trim().rsplit_once(':')?;
let host = host.trim_start_matches('[').trim_end_matches(']');
Some((host.to_owned(), port.parse().ok().filter(|p| *p != 0)?))
}
/// A port that was free a moment ago on the loopback interface.
pub fn free_port() -> std::io::Result<u16> {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
@@ -303,13 +326,22 @@ pub trait AdapterLauncher: Send + Sync + 'static {
pub struct ProcessLauncher;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
/// How long an adapter inside another program (a headless Godot editor) may take to listen.
const EMBEDDED_START_TIMEOUT: Duration = Duration::from_secs(120);
/// Probe of a `connect` address before starting the command.
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
impl AdapterLauncher for ProcessLauncher {
fn launch(&self, mut spec: AdapterSpec, reuse_port: Option<u16>) -> LaunchFuture {
Box::pin(async move {
let stderr = Arc::new(parking_lot::Mutex::new(Vec::new()));
if let Some(port) = reuse_port {
let stream = connect_with_retries(port, None, Duration::from_secs(5)).await?;
// A remote adapter (`dlv --headless` on another machine) may answer slowly.
let (host, timeout) = match spec.server_host.as_deref() {
Some(host) => (host, CONNECT_TIMEOUT),
None => (LOOPBACK, Duration::from_secs(5)),
};
let stream = connect_with_retries(host, port, None, timeout).await?;
let (r, w) = stream.into_split();
return Ok(AdapterIo {
reader: Box::new(r),
@@ -319,6 +351,28 @@ impl AdapterLauncher for ProcessLauncher {
stderr,
});
}
let embedded = match spec.connect.as_deref().filter(|_| spec.transport == Transport::Tcp) {
Some(addr) => Some(
parse_address(addr)
.ok_or_else(|| IdeError::invalid(format!("invalid debug adapter address `{addr}`")))?,
),
None => None,
};
// An adapter inside a program the user runs (the Godot editor): use it, never stop it.
if let Some((host, port)) = &embedded
&& let Ok(Ok(stream)) =
tokio::time::timeout(PROBE_TIMEOUT, tokio::net::TcpStream::connect((host.as_str(), *port))).await
{
let _ = stream.set_nodelay(true);
let (r, w) = stream.into_split();
return Ok(AdapterIo {
reader: Box::new(r),
writer: Box::new(w),
child: None,
port: Some(*port),
stderr,
});
}
if spec.adapter == DEBUGPY_TOOL {
prepare_debugpy(&mut spec).await?;
}
@@ -329,12 +383,17 @@ impl AdapterLauncher for ProcessLauncher {
.flatten()
.ok_or_else(|| missing(&spec))?;
let port = match spec.transport {
Transport::Tcp => Some(free_port()?),
// An embedded adapter started without `${port}` listens on its usual address.
Transport::Tcp => match &embedded {
Some((_, port)) if !spec.args.iter().any(|a| a.contains(PORT_PLACEHOLDER)) => Some(*port),
_ => Some(free_port()?),
},
Transport::Stdio => None,
};
let args = substitute_root(&spec.args, &spec.cwd);
let args = match port {
Some(port) => substitute_port(&spec.args, port),
None => spec.args.clone(),
Some(port) => substitute_port(&args, port),
None => args,
};
let mut cmd = Command::new(&binary);
ide_core::process::no_window(cmd.as_std_mut());
@@ -366,7 +425,8 @@ impl AdapterLauncher for ProcessLauncher {
if let Some(out) = child.stdout.take() {
pump_lines(out, spec.adapter.clone(), stderr.clone());
}
let stream = match connect_with_retries(port, Some(&mut child), CONNECT_TIMEOUT).await {
let timeout = if embedded.is_some() { EMBEDDED_START_TIMEOUT } else { CONNECT_TIMEOUT };
let stream = match connect_with_retries(LOOPBACK, port, Some(&mut child), timeout).await {
Ok(s) => s,
Err(e) => {
let _ = child.start_kill();
@@ -410,14 +470,17 @@ fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
});
}
const LOOPBACK: &str = "127.0.0.1";
async fn connect_with_retries(
host: &str,
port: u16,
mut child: Option<&mut Child>,
timeout: Duration,
) -> IdeResult<tokio::net::TcpStream> {
let deadline = Instant::now() + timeout;
loop {
match tokio::net::TcpStream::connect(("127.0.0.1", port)).await {
match tokio::net::TcpStream::connect((host, port)).await {
Ok(s) => {
let _ = s.set_nodelay(true);
return Ok(s);
@@ -432,7 +495,7 @@ async fn connect_with_retries(
}
if Instant::now() >= deadline {
return Err(IdeError::unavailable(format!(
"could not connect to debug adapter on port {port}: {e}"
"could not connect to debug adapter at {host}:{port}: {e}"
)));
}
tokio::time::sleep(Duration::from_millis(100)).await;
+97
Переглянути файл
@@ -0,0 +1,97 @@
//! "Listen to remote JVM" (IDEA's Remote JVM Debug in listen mode): the IDE listens,
//! the remote JVM (`-agentlib:jdwp=…,server=n,address=<ide-host>:<port>`) connects to
//! it. java-debug can only attach, so the connection is relayed: once the JVM has
//! connected, java-debug attaches to a one-shot loopback port that forwards the JDWP
//! stream (handshake included) both ways.
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::io::ErrorKind;
use std::time::Duration;
use tokio::net::{TcpListener, TcpStream};
/// How long the relay waits for java-debug to attach once the JVM is connected.
const ATTACH_TIMEOUT: Duration = Duration::from_secs(60);
/// The address to listen on for `host`: the interface it names, or every interface when
/// it is not one of this machine's (a DNS name or a NAT address the JVM connects to).
async fn bind(host: &str, port: u16) -> IdeResult<TcpListener> {
let host = host.trim();
let host = if host.is_empty() { "0.0.0.0" } else { host.trim_start_matches('[').trim_end_matches(']') };
match TcpListener::bind((host, port)).await {
Ok(l) => Ok(l),
Err(e) if e.kind() == ErrorKind::AddrNotAvailable || e.kind() == ErrorKind::Other => {
TcpListener::bind(("0.0.0.0", port))
.await
.map_err(|e| IdeError::unavailable(format!("cannot listen on port {port}: {e}")))
}
Err(e) => Err(IdeError::unavailable(format!("cannot listen on {host}:{port}: {e}"))),
}
}
/// Waits for a JVM to connect to `host:port`, then returns a loopback port that relays
/// to it (accepts one connection). Cancelled through `cancel` while waiting.
pub async fn listen_for_jvm(host: &str, port: u16, cancel: CancellationToken) -> IdeResult<u16> {
let listener = bind(host, port).await?;
let jvm = tokio::select! {
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
accepted = listener.accept() => accepted.map_err(IdeError::from)?.0,
};
drop(listener);
let _ = jvm.set_nodelay(true);
let relay = TcpListener::bind(("127.0.0.1", 0)).await?;
let local = relay.local_addr()?.port();
tokio::spawn(relay_one(relay, jvm));
Ok(local)
}
async fn relay_one(relay: TcpListener, mut jvm: TcpStream) {
let debugger = match tokio::time::timeout(ATTACH_TIMEOUT, relay.accept()).await {
Ok(Ok((s, _))) => s,
_ => return,
};
drop(relay);
let _ = debugger.set_nodelay(true);
let mut debugger = debugger;
if let Err(e) = tokio::io::copy_bidirectional(&mut debugger, &mut jvm).await {
tracing::debug!(target: "ide_dap::jdwp", "JDWP relay closed: {e}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::test]
async fn relays_the_jdwp_handshake_both_ways() {
let port = TcpListener::bind(("127.0.0.1", 0)).await.unwrap().local_addr().unwrap().port();
let waiting = tokio::spawn(listen_for_jvm("127.0.0.1", port, CancellationToken::new()));
// The remote JVM (`server=n`) connects to the IDE.
let mut jvm = loop {
if let Ok(s) = TcpStream::connect(("127.0.0.1", port)).await {
break s;
}
tokio::time::sleep(Duration::from_millis(20)).await;
};
let local = waiting.await.unwrap().unwrap();
// java-debug attaches to the relay and starts the handshake.
let mut debugger = TcpStream::connect(("127.0.0.1", local)).await.unwrap();
debugger.write_all(b"JDWP-Handshake").await.unwrap();
let mut buf = [0u8; 14];
jvm.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"JDWP-Handshake");
jvm.write_all(b"JDWP-Handshake").await.unwrap();
debugger.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"JDWP-Handshake");
}
#[tokio::test]
async fn waiting_is_cancellable() {
let cancel = CancellationToken::new();
let waiting = tokio::spawn(listen_for_jvm("127.0.0.1", 0, cancel.clone()));
tokio::time::sleep(Duration::from_millis(50)).await;
cancel.cancel();
let err = waiting.await.unwrap().unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
}
+51 -16
Переглянути файл
@@ -12,6 +12,7 @@ pub mod adapter;
pub mod attach;
mod cargo;
pub mod connection;
pub mod jdwp;
mod session;
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
@@ -45,7 +46,8 @@ pub struct LaunchConfig {
/// A `"cargo": {"args": [...], "filter": {"name", "kind"}}` entry builds with cargo
/// and launches the produced executable; `"debugServer": <port>` connects to an
/// adapter already listening on that local port (e.g. java-debug inside jdtls)
/// instead of starting one.
/// instead of starting one, `"debugServer": "host:port"` to one on another machine
/// (`dlv --headless`, `debugpy --listen`).
pub extra_json: Option<String>,
}
@@ -357,15 +359,34 @@ pub(crate) fn substitute_free_port(value: &mut Value, port: &mut impl FnMut() ->
})
}
/// Where a running adapter listens: `debugServer` of the launch arguments.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct DebugServer {
/// `None` for the loopback interface (an adapter inside a local process such as jdtls).
pub host: Option<String>,
pub port: u16,
}
/// Removes `debugServer` (VS Code's "connect to a running adapter" attribute) from the
/// launch arguments and returns its port.
pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<u16>> {
/// launch arguments: a port (`4711`, `"4711"`) on this machine, or `"host:port"` /
/// `"[v6]:port"` of a remote one (`dlv --headless`, `debugpy --listen`).
pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<DebugServer>> {
let Some(v) = arguments.as_object_mut().and_then(|o| o.remove("debugServer")) else { return Ok(None) };
let port = v.as_u64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok()));
match port.and_then(|p| u16::try_from(p).ok()).filter(|p| *p != 0) {
Some(p) => Ok(Some(p)),
None => Err(IdeError::invalid(format!("invalid debugServer port: {v}"))),
let invalid = || IdeError::invalid(format!("invalid debugServer address: {v}"));
let port_of = |p: u64| u16::try_from(p).ok().filter(|p| *p != 0);
if let Some(p) = v.as_u64() {
return port_of(p).map(|port| Some(DebugServer { host: None, port })).ok_or_else(invalid);
}
let s = v.as_str().map(str::trim).ok_or_else(invalid)?;
let (host, port) = match s.rsplit_once(':') {
Some((host, port)) => {
let host = host.trim().trim_start_matches('[').trim_end_matches(']');
(Some(host).filter(|h| !h.is_empty()).map(str::to_owned), port)
}
None => (None, s),
};
let port = port.trim().parse::<u64>().ok().and_then(port_of).ok_or_else(invalid)?;
Ok(Some(DebugServer { host, port }))
}
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
@@ -558,6 +579,9 @@ impl DebugManager {
}
let id = DebugSessionId::next();
let debug_server = take_debug_server(&mut arguments)?;
if let Some(server) = &debug_server {
spec.server_host = server.host.clone();
}
if let Some(cargo) = arguments.as_object_mut().and_then(|o| o.remove("cargo")) {
let cargo_args: Vec<String> = cargo
.get("args")
@@ -596,11 +620,19 @@ impl DebugManager {
if config.adapter == "js-debug" && arguments.get("__workspaceFolder").is_none() {
arguments["__workspaceFolder"] = json!(cwd);
}
// Godot compares `project` with its own (resolved) project path: `/tmp/game` is
// rejected by an editor that opened `/private/tmp/game`.
if config.adapter == "godot"
&& let Some(project) = arguments.get("project").and_then(Value::as_str)
&& let Ok(real) = std::fs::canonicalize(project)
{
arguments["project"] = json!(real);
}
if config.adapter == "codelldb" && arguments.get("sourceLanguages").is_none() {
arguments["sourceLanguages"] = json!(["rust"]);
}
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, debug_server)
.await
let port = debug_server.map(|s| s.port);
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, port).await
}
/// `startDebugging` reverse request: a child session on the same adapter.
@@ -960,8 +992,8 @@ impl DebugManager {
}
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
let body = self
.session(s)?
let session = self.session(s)?;
let body = session
.conn
.request_timeout(
"stackTrace",
@@ -969,11 +1001,14 @@ impl DebugManager {
REQUEST_TIMEOUT,
)
.await?;
Ok(body
.get("stackFrames")
.and_then(Value::as_array)
.map(|f| f.iter().map(frame_from).collect())
.unwrap_or_default())
let frame = |f: &Value| {
let mut frame = frame_from(f);
if let Some(client) = frame.path.as_deref().and_then(|p| session.client_path(&p.to_string_lossy())) {
frame.path = Some(client.into());
}
frame
};
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
}
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
+39 -3
Переглянути файл
@@ -51,9 +51,16 @@ pub(crate) struct Session {
pub pending_restore: Mutex<PendingRestore>,
/// Adapter breakpoint id → (file, index in the stored list).
pub breakpoint_ids: Mutex<HashMap<i64, (PathBuf, usize)>>,
/// Resolved path → the path as the IDE knows it, for adapters given resolved paths.
resolved_paths: Mutex<HashMap<PathBuf, PathBuf>>,
progress: Mutex<HashMap<String, TaskId>>,
}
/// Adapters that only match files by their resolved path: Godot maps a script to
/// `res://` by prefix and silently never stops at a breakpoint set through a
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
const RESOLVES_PATHS: &[&str] = &["godot"];
impl Session {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -86,6 +93,7 @@ impl Session {
terminated: AtomicBool::new(false),
pending_restore: Mutex::default(),
breakpoint_ids: Mutex::new(HashMap::new()),
resolved_paths: Mutex::new(HashMap::new()),
progress: Mutex::new(HashMap::new()),
}
}
@@ -94,6 +102,25 @@ impl Session {
self.owner.sink.emit(IdeEvent::Debug { session: self.id, event });
}
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
pub fn adapter_path(&self, path: &Path) -> PathBuf {
if !RESOLVES_PATHS.contains(&self.adapter.as_str()) {
return path.to_path_buf();
}
match std::fs::canonicalize(path) {
Ok(real) if real != path => {
self.resolved_paths.lock().insert(real.clone(), path.to_path_buf());
real
}
_ => path.to_path_buf(),
}
}
/// A path from the adapter as the IDE knows it (undoes [`Session::adapter_path`]).
pub fn client_path(&self, path: &str) -> Option<PathBuf> {
self.resolved_paths.lock().get(Path::new(path)).cloned()
}
pub fn supports(&self, cap: &str) -> bool {
self.caps.lock().get(cap).and_then(Value::as_bool).unwrap_or(false)
}
@@ -135,7 +162,7 @@ impl Session {
.request_timeout(
"setBreakpoints",
json!({
"source": { "path": path, "name": name },
"source": { "path": self.adapter_path(path), "name": name },
"breakpoints": source_bps,
"sourceModified": false,
}),
@@ -311,7 +338,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, body:
s.emit(DebugEvent::BreakpointsChanged { path: path.into() });
}
}
"exited" => s.emit(DebugEvent::Exited { code: int("exitCode").unwrap_or(0) as i32 }),
// Godot repeats `exited` / `terminated` when the client disconnects afterwards.
"exited" if !s.terminated.load(Ordering::Acquire) => {
s.emit(DebugEvent::Exited { code: int("exitCode").unwrap_or(0) as i32 })
}
"exited" => {}
"terminated" => {
if !s.terminated.swap(true, Ordering::AcqRel) {
s.emit(DebugEvent::Terminated);
@@ -391,7 +422,12 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
};
let mut cmd = tokio::process::Command::new(program);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(rest).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
cmd.args(rest)
.envs(ide_core::process::shell_env())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
if let Some(cwd) = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()) {
cmd.current_dir(cwd);
}
+180 -2
Переглянути файл
@@ -597,14 +597,23 @@ async fn sessions_deliver_events_to_their_owner_only() {
#[test]
fn debug_server_is_taken_from_launch_arguments() {
let local = |port| Some(DebugServer { host: None, port });
let remote = |host: &str, port| Some(DebugServer { host: Some(host.into()), port });
let mut args = json!({"name": "x", "debugServer": 4711, "mainClass": "a.B"});
assert_eq!(take_debug_server(&mut args).unwrap(), Some(4711));
assert_eq!(take_debug_server(&mut args).unwrap(), local(4711));
assert!(args.get("debugServer").is_none());
assert_eq!(args["mainClass"], "a.B");
assert_eq!(take_debug_server(&mut json!({"debugServer": "5005"})).unwrap(), Some(5005));
assert_eq!(take_debug_server(&mut json!({"debugServer": "5005"})).unwrap(), local(5005));
assert_eq!(take_debug_server(&mut json!({"name": "x"})).unwrap(), None);
// A remote adapter: `dlv --headless --listen=:2345`, `debugpy --listen 0.0.0.0:5678`.
assert_eq!(take_debug_server(&mut json!({"debugServer": "build-box:2345"})).unwrap(), remote("build-box", 2345));
assert_eq!(take_debug_server(&mut json!({"debugServer": "10.0.0.7:5678"})).unwrap(), remote("10.0.0.7", 5678));
assert_eq!(take_debug_server(&mut json!({"debugServer": "[::1]:2345"})).unwrap(), remote("::1", 2345));
assert_eq!(take_debug_server(&mut json!({"debugServer": ":2345"})).unwrap(), local(2345));
assert!(take_debug_server(&mut json!({"debugServer": 0})).is_err());
assert!(take_debug_server(&mut json!({"debugServer": 70000})).is_err());
assert!(take_debug_server(&mut json!({"debugServer": "host:"})).is_err());
assert!(take_debug_server(&mut json!({"debugServer": "host:abc"})).is_err());
}
#[test]
@@ -696,6 +705,41 @@ async fn connects_to_running_debug_server_over_tcp() {
assert!(events.lock().iter().any(|e| matches!(e, IdeEvent::Debug { event: DebugEvent::Started { .. }, .. })));
}
/// Go Remote / Python remote: the adapter runs on another machine (`dlv --headless`,
/// `debugpy --listen`); `debugServer: "host:port"` connects there instead of spawning one.
#[tokio::test]
async fn connects_to_remote_debug_server_by_host() {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let log: Log = Arc::default();
let server_log = log.clone();
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
fake_adapter(stream, server_log, Script::default()).await;
});
let (owner, _events) = recording_owner("main");
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
let config = LaunchConfig {
name: "Remote".into(),
adapter: "delve".into(),
request: "attach".into(),
program: None,
args: vec![],
cwd: Some(std::env::temp_dir().into()),
env: BTreeMap::new(),
extra_json: Some(
json!({"debugServer": format!("localhost:{port}"), "mode": "remote", "substitutePath": [{"from": "/src", "to": "/app"}]})
.to_string(),
),
};
let id = manager.start(config, owner).await.unwrap();
let attach = log.lock().iter().find(|m| m["command"] == "attach").cloned().unwrap();
assert_eq!(attach["arguments"]["mode"], "remote");
assert_eq!(attach["arguments"]["substitutePath"][0]["to"], "/app");
assert!(attach["arguments"].get("debugServer").is_none(), "consumed by the client");
manager.stop(id).await.unwrap();
}
fn requests(h: &Harness, command: &str) -> Vec<Value> {
h.log
.lock()
@@ -837,3 +881,137 @@ async fn hot_swap_only_for_java_debug() {
let failed = hot_swap_result(&json!({"changedClasses": [], "errorMessage": "boom"}));
assert_eq!(failed.error_message.as_deref(), Some("boom"));
}
fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc<LanguageRegistry> {
let lang = ide_language::LanguageConfig {
id: ide_core::LanguageId::new("gdscript"),
name: "GDScript".into(),
extensions: vec!["gd".into()],
filenames: vec![],
first_line: None,
line_comment: None,
block_comment: None,
indent: None,
ui_mode: None,
tree_sitter: None,
language_servers: vec![],
debugger: Some(ide_language::DebuggerConfig {
adapter: "godot".into(),
command: command.into(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
transport: "tcp".into(),
connect: Some(format!("127.0.0.1:{port}")),
install_hint: Some("Open the project in the Godot editor".into()),
}),
};
Arc::new(LanguageRegistry::from_configs(vec![lang]))
}
fn godot_launch(project: &std::path::Path) -> LaunchConfig {
LaunchConfig {
name: "Main Scene".into(),
adapter: "godot".into(),
request: "launch".into(),
program: None,
args: vec![],
cwd: Some(project.to_path_buf().into()),
env: BTreeMap::new(),
extra_json: Some(json!({"project": project, "scene": "main"}).to_string()),
}
}
/// Godot's debug adapter runs inside the editor (port 6006): an open editor is
/// used as is, nothing is started.
#[tokio::test]
async fn godot_connects_to_the_editor_adapter() {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let log: Log = Arc::default();
let server_log = log.clone();
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
fake_adapter(stream, server_log, Script::default()).await;
});
let (owner, _events) = recording_owner("main");
let manager = DebugManager::new(godot_registry(port, "openidea-no-such-godot", &[]));
let project = std::env::temp_dir();
let id = manager.start(godot_launch(&project), owner).await.unwrap();
let launch = log.lock().iter().find(|m| m["command"] == "launch").cloned().unwrap();
assert_eq!(launch["arguments"]["scene"], "main");
assert_eq!(launch["arguments"]["project"], json!(std::fs::canonicalize(&project).unwrap()));
assert!(log.lock().iter().any(|m| m["command"] == "configurationDone"));
manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn godot_without_editor_or_executable_says_what_to_do() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let (owner, _events) = recording_owner("main");
let manager = DebugManager::new(godot_registry(port, "openidea-no-such-godot", &[]));
let err = manager.start(godot_launch(&std::env::temp_dir()), owner).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.message.contains("Open the project in the Godot editor"), "{}", err.message);
}
/// No editor open: the command (a headless editor) is started for the project and
/// the client connects once it listens; the started process ends with the session.
#[cfg(unix)]
#[tokio::test]
async fn godot_starts_a_headless_editor_when_none_is_open() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let log: Log = Arc::default();
let server_log = log.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
let (stream, _) = listener.accept().await.unwrap();
fake_adapter(stream, server_log, Script::default()).await;
});
let (owner, _events) = recording_owner("main");
// `sleep` stands in for `godot --headless --editor --path ${root} …`.
let manager = DebugManager::new(godot_registry(port, "sleep", &["30"]));
let id = manager.start(godot_launch(&std::env::temp_dir()), owner).await.unwrap();
assert!(log.lock().iter().any(|m| m["command"] == "launch"));
manager.stop(id).await.unwrap();
}
/// Godot never stops at a breakpoint given through a symlinked path (it maps scripts
/// to `res://` by its resolved project path): breakpoints and `project` go out resolved.
#[cfg(unix)]
#[tokio::test]
async fn godot_gets_resolved_paths() {
let real = std::env::temp_dir().join(format!("openidea-godot-real-{}", std::process::id()));
let link = std::env::temp_dir().join(format!("openidea-godot-link-{}", std::process::id()));
std::fs::create_dir_all(&real).unwrap();
std::fs::write(real.join("player.gd"), "extends Node\n").unwrap();
let _ = std::fs::remove_file(&link);
std::os::unix::fs::symlink(&real, &link).unwrap();
let real = std::fs::canonicalize(&real).unwrap();
let log: Log = Arc::default();
let (owner, _events) = recording_owner("main");
let manager = DebugManager::with_launcher(
godot_registry(1, "godot", &[]),
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
);
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
let id = manager.start(godot_launch(&link), owner).await.unwrap();
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
let launch = log.lock().iter().find(|m| m["command"] == "launch").cloned().unwrap();
assert_eq!(launch["arguments"]["project"], json!(real));
manager.stop(id).await.unwrap();
std::fs::remove_file(&link).ok();
std::fs::remove_dir_all(&real).ok();
}
#[test]
fn root_and_address_placeholders() {
let args: Vec<String> = ["--path", "${root}", "--dap-port", "${port}"].iter().map(|s| s.to_string()).collect();
let args = adapter::substitute_port(&adapter::substitute_root(&args, std::path::Path::new("/g")), 6010);
assert_eq!(args, ["--path", "/g", "--dap-port", "6010"]);
assert_eq!(adapter::parse_address("127.0.0.1:6006"), Some(("127.0.0.1".into(), 6006)));
assert_eq!(adapter::parse_address("[::1]:6006"), Some(("::1".into(), 6006)));
assert_eq!(adapter::parse_address("6006"), None);
}
+157
Переглянути файл
@@ -0,0 +1,157 @@
//! Drives Godot's debug adapter (inside the Godot editor) with the GDScript
//! language definition: a headless editor is started for the project, the main
//! scene is played, a breakpoint hits, stack / variables / stepping work, and the
//! game and the editor end with the session.
//!
//! Ignored by default (needs Godot 4). Run with
//! `GODOT_BIN=<godot executable> cargo test -p ide-dap --test godot -- --ignored --nocapture`.
use ide_core::event::DebugEvent;
use ide_core::{IdeEvent, SharedSink};
use ide_dap::*;
use ide_language::{LanguageConfig, LanguageRegistry};
use parking_lot::Mutex;
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
const SCRIPT: &str = "extends Node
var health: int = 3
func _ready() -> void:
\tvar total := add(2, 3)
\tprint(\"total = \", total)
\thealth -= 1
\tget_tree().quit()
func add(a: int, b: int) -> int:
\treturn a + b
";
/// 0-based line of `return a + b`.
const BREAK_LINE: u32 = 11;
fn project(dir: &Path) {
std::fs::write(
dir.join("project.godot"),
"config_version=5\n\n[application]\nconfig/name=\"Probe\"\nrun/main_scene=\"res://main.tscn\"\n",
)
.unwrap();
std::fs::write(
dir.join("main.tscn"),
"[gd_scene load_steps=2 format=3]\n\n[ext_resource type=\"Script\" path=\"res://player.gd\" id=\"1\"]\n\n[node name=\"Main\" type=\"Node\"]\nscript = ExtResource(\"1\")\n",
)
.unwrap();
std::fs::write(dir.join("player.gd"), SCRIPT).unwrap();
}
/// The built-in GDScript definition, with the editor's usual port moved aside so an
/// open editor can't answer instead of the one this test starts.
fn registry() -> Arc<LanguageRegistry> {
let builtin = LanguageRegistry::load(None).unwrap();
let mut gd: LanguageConfig = builtin.get(&ide_core::LanguageId::new("gdscript")).unwrap();
let dbg = gd.debugger.as_mut().unwrap();
let unused = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
dbg.connect = Some(format!("127.0.0.1:{unused}"));
Arc::new(LanguageRegistry::from_configs(vec![gd]))
}
async fn wait_for(events: &Mutex<Vec<IdeEvent>>, timeout: Duration, pred: impl Fn(&DebugEvent) -> bool) -> DebugEvent {
let start = Instant::now();
loop {
if let Some(e) = events.lock().iter().find_map(|e| match e {
IdeEvent::Debug { event, .. } if pred(event) => Some(event.clone()),
_ => None,
}) {
return e;
}
assert!(start.elapsed() < timeout, "timed out; events: {:#?}", events.lock());
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
fn godot_processes(project: &Path) -> usize {
let out = std::process::Command::new("pgrep").args(["-f", &project.to_string_lossy()]).output().unwrap();
String::from_utf8_lossy(&out.stdout).lines().count()
}
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn breakpoints_stepping_and_variables_in_a_real_godot() {
let Ok(godot) = std::env::var("GODOT_BIN") else {
eprintln!("GODOT_BIN not set; skipping");
return;
};
let dir = std::env::temp_dir().join(format!("openidea-godot-dap-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let root = std::fs::canonicalize(&dir).unwrap();
project(&root);
let manager = DebugManager::new(registry());
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let script_as_opened = dir.join("player.gd");
manager
.set_breakpoints(
script_as_opened.clone(),
vec![Breakpoint {
line: BREAK_LINE,
condition: None,
hit_condition: None,
log_message: None,
enabled: true,
}],
)
.await
.unwrap();
// As the UI builds it for "Godot Project" (`godot --path .`).
let config = LaunchConfig {
name: "Godot Project".into(),
adapter: "godot".into(),
request: "launch".into(),
program: None,
args: vec![],
// The project as opened, through a symlink on macOS (`/var` → `/private/var`).
cwd: Some(dir.clone().into()),
env: BTreeMap::new(),
extra_json: Some(serde_json::json!({ "project": dir, "scene": "main" }).to_string()),
};
let id = manager
.start_with(config, SessionOwner::new("main", sink), |_| Some(godot.clone()))
.await
.unwrap_or_else(|e| panic!("start: {e:?}"));
let stopped = wait_for(&events, Duration::from_secs(120), |e| matches!(e, DebugEvent::Stopped { .. })).await;
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
let frames = manager.stack_trace(id, thread_id).await.unwrap();
assert_eq!(frames[0].name, "add");
assert_eq!(frames[0].line, BREAK_LINE);
// Frames name the file as the IDE opened it, not Godot's resolved path.
assert_eq!(frames[0].path.as_deref().map(Path::new), Some(script_as_opened.as_path()));
assert_eq!(frames[1].name, "_ready");
let scopes = manager.scopes(id, frames[0].id).await.unwrap();
let locals = scopes.iter().find(|s| s.name == "Locals").expect("Locals scope");
let vars = manager.variables(id, locals.variables_reference).await.unwrap();
let value = |n: &str| vars.iter().find(|v| v.name == n).map(|v| v.value.clone());
assert_eq!((value("a").as_deref(), value("b").as_deref()), (Some("2"), Some("3")), "{vars:?}");
events.lock().clear();
manager.step(id, thread_id, StepKind::Over).await.unwrap();
wait_for(&events, Duration::from_secs(30), |e| matches!(e, DebugEvent::Stopped { .. })).await;
let frames = manager.stack_trace(id, thread_id).await.unwrap();
assert_eq!((frames[0].name.as_str(), frames[0].line), ("_ready", 6), "stepped back into `_ready`, at the print");
manager.resume(id, thread_id).await.unwrap();
// (The game's last output is not always forwarded when it quits right away.)
wait_for(&events, Duration::from_secs(30), |e| matches!(e, DebugEvent::Terminated)).await;
let _ = manager.stop(id).await;
// The headless editor started for the session ends with it, the game too.
let start = Instant::now();
while godot_processes(&root) > 0 {
assert!(start.elapsed() < Duration::from_secs(10), "Godot still running for {}", root.display());
tokio::time::sleep(Duration::from_millis(200)).await;
}
std::fs::remove_dir_all(&root).ok();
}
+11 -4
Переглянути файл
@@ -40,6 +40,8 @@ pub struct QueryResult {
/// More rows exist beyond the limit.
pub has_more: bool,
pub elapsed_ms: f64,
/// Until the server's first answer; the rest of `elapsed_ms` is fetching.
pub execution_ms: f64,
}
pub enum Pool {
@@ -130,7 +132,9 @@ macro_rules! fetch {
let mut affected: Option<u64> = None;
let mut has_more = false;
let mut failure = None;
let mut first: Option<Instant> = None;
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)) => {
@@ -152,12 +156,13 @@ macro_rules! fetch {
drop(stream);
match failure {
Some(e) => Err(e),
None => Ok((columns, rows, affected, has_more)),
None => Ok((columns, rows, affected, has_more, first)),
}
}};
}
type Fetched = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, Option<u64>, bool);
/// Columns, rows, rows affected, more rows beyond the limit, time of the first answer.
type Fetched = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, Option<u64>, bool, Option<Instant>);
/// The server-side id of a connection (to cancel its statement from another one).
macro_rules! backend_id {
@@ -552,14 +557,16 @@ impl Held {
}
Held::Mysql(c) => run!(c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
};
let (columns, rows, affected, has_more) = fetched;
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: started.elapsed().as_secs_f64() * 1000.0,
elapsed_ms,
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
})
}
}
+137
Переглянути файл
@@ -0,0 +1,137 @@
//! Query history (IDEA's Browse Query History): the statements each data
//! source ran, newest first. One JSON file in the app's data directory for all
//! projects, keyed by project root, then data source id — never committed.
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// Statements kept per data source.
pub const MAX_ENTRIES: usize = 500;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbHistoryEntry")]
pub struct HistoryEntry {
pub text: String,
/// Milliseconds since the Unix epoch.
pub time: f64,
}
/// Project root → data source id → entries, newest first.
type Contents = BTreeMap<String, BTreeMap<String, Vec<HistoryEntry>>>;
/// Serialises read-modify-write across the projects sharing the file.
static LOCK: Mutex<()> = Mutex::new(());
pub struct HistoryStore {
path: PathBuf,
project: String,
}
impl HistoryStore {
pub fn new(path: PathBuf, root: &Path) -> Self {
Self { path, project: root.to_string_lossy().into_owned() }
}
pub fn list(&self, source: &str) -> Vec<HistoryEntry> {
let _g = LOCK.lock();
self.read().remove(&self.project).and_then(|mut p| p.remove(source)).unwrap_or_default()
}
/// Records `text`; running a statement again moves it to the top.
pub fn add(&self, source: &str, text: &str, time: f64) -> IdeResult<()> {
let text = text.trim();
if text.is_empty() {
return Ok(());
}
let _g = LOCK.lock();
let mut all = self.read();
let entries = all.entry(self.project.clone()).or_default().entry(source.to_owned()).or_default();
entries.retain(|e| e.text != text);
entries.insert(0, HistoryEntry { text: text.to_owned(), time });
entries.truncate(MAX_ENTRIES);
self.write(&all)
}
/// Removes the entries with these texts (all of them for `None`).
pub fn remove(&self, source: &str, texts: Option<&[String]>) -> IdeResult<()> {
let _g = LOCK.lock();
let mut all = self.read();
let Some(project) = all.get_mut(&self.project) else { return Ok(()) };
match texts {
None => {
project.remove(source);
}
Some(texts) => {
if let Some(entries) = project.get_mut(source) {
entries.retain(|e| !texts.contains(&e.text));
}
}
}
self.write(&all)
}
fn read(&self) -> Contents {
match std::fs::read(&self.path) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
tracing::warn!("query history: {}: {e}", self.path.display());
Contents::new()
}),
Err(_) => Contents::new(),
}
}
fn write(&self, all: &Contents) -> IdeResult<()> {
let err = |e: std::io::Error| IdeError::unavailable(format!("query history: {e}"));
if let Some(dir) = self.path.parent() {
std::fs::create_dir_all(dir).map_err(err)?;
}
let tmp = self.path.with_extension("json.tmp");
let bytes = serde_json::to_vec(all).map_err(|e| IdeError::internal(e.to_string()))?;
std::fs::write(&tmp, bytes).map_err(err)?;
std::fs::rename(&tmp, &self.path).map_err(err)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keeps_newest_first_without_duplicates_per_project_and_source() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("h.json");
let a = HistoryStore::new(file.clone(), Path::new("/p/a"));
let b = HistoryStore::new(file, Path::new("/p/b"));
a.add("s1", "select 1", 1.0).unwrap();
a.add("s1", " select 2 ", 2.0).unwrap();
a.add("s1", "select 1", 3.0).unwrap();
a.add("s2", "select 3", 4.0).unwrap();
b.add("s1", "select 4", 5.0).unwrap();
let texts = |v: Vec<HistoryEntry>| v.into_iter().map(|e| e.text).collect::<Vec<_>>();
assert_eq!(texts(a.list("s1")), ["select 1", "select 2"]);
assert_eq!(texts(a.list("s2")), ["select 3"]);
assert_eq!(texts(b.list("s1")), ["select 4"]);
a.remove("s1", Some(&["select 2".to_owned()])).unwrap();
assert_eq!(texts(a.list("s1")), ["select 1"]);
a.remove("s1", None).unwrap();
assert!(a.list("s1").is_empty());
assert_eq!(texts(b.list("s1")), ["select 4"]);
}
#[test]
fn caps_entries() {
let dir = tempfile::tempdir().unwrap();
let h = HistoryStore::new(dir.path().join("h.json"), Path::new("/p"));
for i in 0..MAX_ENTRIES + 5 {
h.add("s", &format!("select {i}"), i as f64).unwrap();
}
let list = h.list("s");
assert_eq!(list.len(), MAX_ENTRIES);
assert_eq!(list[0].text, format!("select {}", MAX_ENTRIES + 4));
}
}
+211 -10
Переглянути файл
@@ -3,6 +3,8 @@
//! and statement splitting ([`split`]), for SQLite, PostgreSQL and MySQL/MariaDB.
pub mod conn;
pub mod history;
pub mod plan;
pub mod secrets;
pub mod source;
pub mod split;
@@ -10,11 +12,14 @@ pub mod sql;
pub mod tunnel;
pub use conn::{Held, Pool, QueryResult, ResultColumn};
pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSsh, DbSshAuth, DbSslMode, DbTxMode,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
use history::HistoryStore;
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::Mutex;
use secrets::SecretStore;
@@ -31,6 +36,67 @@ use tunnel::{OpenError, Tunnel, TunnelSpec, UnknownHostKey};
pub enum DbTableKind {
Table,
View,
MaterializedView,
}
impl DbTableKind {
fn from_catalog(kind: Option<&str>) -> Self {
match kind {
Some("view") => Self::View,
Some("materialized view") => Self::MaterializedView,
_ => Self::Table,
}
}
}
/// Schema objects other than tables and columns (Go to DDL, Drop).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbObjectKind {
Function,
Procedure,
Trigger,
Sequence,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTriggerInfo")]
pub struct TriggerInfo {
pub name: String,
/// `before`, `after`, `instead of`.
pub timing: String,
/// `insert`, `update or delete`…
pub events: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbRoutineInfo")]
pub struct RoutineInfo {
pub name: String,
/// `Function` or `Procedure`.
pub kind: DbObjectKind,
pub arguments: String,
/// Result type of a function.
pub returns: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbSequenceInfo")]
pub struct SequenceInfo {
pub name: String,
pub data_type: String,
}
/// A schema's routines and sequences (the tree's `routines` / `sequences` folders).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbSchemaObjects")]
pub struct SchemaObjects {
pub routines: Vec<RoutineInfo>,
pub sequences: Vec<SequenceInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -68,6 +134,7 @@ pub struct TableDetails {
pub columns: Vec<ColumnInfo>,
pub indexes: Vec<IndexInfo>,
pub foreign_keys: Vec<ForeignKey>,
pub triggers: Vec<TriggerInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -148,6 +215,7 @@ pub struct DbManager {
known_hosts: PathBuf,
ssh_config: Option<PathBuf>,
saved_passwords: SecretStore,
history: Arc<HistoryStore>,
/// Passwords entered this session (not saved, or not yet), by credential key.
session_passwords: Mutex<HashMap<String, String>>,
/// Manual-commit data sources, each with the connection of its open
@@ -251,21 +319,24 @@ async fn end_session(session: &Session) {
}
impl DbManager {
/// `passwords` is the app-wide file of saved passwords ([`SecretStore`]).
pub fn new(root: PathBuf, passwords: PathBuf) -> Self {
/// `passwords` / `history` are the app-wide files of saved passwords
/// ([`SecretStore`]) and query history ([`HistoryStore`]).
pub fn new(root: PathBuf, passwords: PathBuf, history: PathBuf) -> Self {
let ssh_dir = dirs::home_dir().unwrap_or_default().join(".ssh");
Self::with_ssh_files(root, passwords, ssh_dir.join("known_hosts"), Some(ssh_dir.join("config")))
Self::with_ssh_files(root, passwords, history, ssh_dir.join("known_hosts"), Some(ssh_dir.join("config")))
}
/// [`DbManager::new`] with other `known_hosts` / `~/.ssh/config` files (tests).
pub fn with_ssh_files(
root: PathBuf,
passwords: PathBuf,
history: PathBuf,
known_hosts: PathBuf,
ssh_config: Option<PathBuf>,
) -> Self {
Self {
saved_passwords: SecretStore::new(passwords, &root),
history: Arc::new(HistoryStore::new(history, &root)),
root,
pools: Mutex::default(),
tunnels: Mutex::default(),
@@ -529,14 +600,15 @@ impl DbManager {
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
let id = split_target(id).0;
let system = self.source(id)?.introspection.show_system;
let introspection = self.source(id)?.introspection;
let system = introspection.show_system;
let pool = self.pool(id).await?;
if pool.driver() != DbDriver::Postgres {
return Err(IdeError::invalid("only PostgreSQL data sources list databases"));
}
let first = |rows: Vec<Vec<Option<String>>>| rows.into_iter().filter_map(|r| r.into_iter().next().flatten());
let current = first(pool.rows("SELECT current_database()", 1).await?).next().unwrap_or_default();
let rows = pool.rows(sql::databases(system), MAX_META_ROWS).await?;
let rows = pool.rows(sql::databases(introspection.show_templates), MAX_META_ROWS).await?;
let mut names: Vec<String> =
first(rows).filter(|n| system || *n == current || !sql::INTERNAL_DATABASES.contains(&n.as_str())).collect();
if !names.contains(&current) {
@@ -562,9 +634,7 @@ impl DbManager {
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
let kind =
if it.next().flatten().as_deref() == Some("view") { DbTableKind::View } else { DbTableKind::Table };
Some(TableInfo { name, kind })
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
})
.collect())
}
@@ -612,7 +682,85 @@ impl DbManager {
.collect();
}
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
Ok(TableDetails { columns, indexes, foreign_keys })
let triggers = pool
.rows(&sql::triggers(driver, schema, table), MAX_META_ROWS)
.await
.unwrap_or_else(|e| {
tracing::warn!("triggers: {}", e.message);
Vec::new()
})
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
let (timing, events) = if driver == DbDriver::Sqlite {
sql::sqlite_trigger_event(&it.next().flatten().unwrap_or_default())
} else {
(it.next().flatten().unwrap_or_default(), it.next().flatten().unwrap_or_default())
};
Some(TriggerInfo { name, timing, events })
})
.collect();
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
}
/// The routines and sequences of `schema`.
pub async fn schema_objects(&self, id: &str, schema: &str) -> IdeResult<SchemaObjects> {
let pool = self.pool(id).await?;
let driver = pool.driver();
let mut out = SchemaObjects::default();
if let Some(q) = sql::routines(driver, schema) {
out.routines = pool
.rows(&q, MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
let kind = if it.next().flatten().as_deref() == Some("procedure") {
DbObjectKind::Procedure
} else {
DbObjectKind::Function
};
let arguments = it.next().flatten().unwrap_or_default();
let returns = it.next().flatten().filter(|r| !r.is_empty() && kind == DbObjectKind::Function);
Some(RoutineInfo { name, kind, arguments, returns })
})
.collect();
}
if let Some(q) = sql::sequences(driver, schema) {
out.sequences = pool
.rows(&q, MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some(SequenceInfo {
name: it.next().flatten()?,
data_type: it.next().flatten().unwrap_or_default(),
})
})
.collect();
}
Ok(out)
}
/// The definition of a routine (every overload), trigger or sequence.
pub async fn object_ddl(&self, id: &str, schema: &str, kind: DbObjectKind, name: &str) -> IdeResult<String> {
let pool = self.pool(id).await?;
let (q, column) = sql::object_ddl(pool.driver(), schema, kind, name)
.ok_or_else(|| IdeError::invalid(format!("no {kind:?} objects in this database")))?;
let defs: Vec<String> = pool
.rows(&q, MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| r.into_iter().nth(column).flatten())
.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';')))
.collect();
if defs.is_empty() {
return Err(IdeError::not_found(format!("{schema}.{name}")));
}
Ok(defs.join("\n"))
}
/// The DDL of table or view `name`: SQLite's stored statements, MySQL's
@@ -708,7 +856,7 @@ impl DbManager {
_ => tables.push(CompletionTable {
schema,
name,
kind: if kind == "view" { DbTableKind::View } else { DbTableKind::Table },
kind: DbTableKind::from_catalog(Some(&kind)),
columns: vec![column],
}),
}
@@ -732,12 +880,65 @@ impl DbManager {
Ok(CompletionModel { default_schema, tables, foreign_keys })
}
/// Runs `statement` on `id` (in its open transaction in manual-commit mode),
/// recording it in the data source's query history.
pub async fn execute(
&self,
id: &str,
statement: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let r = self.run(id, statement, max_rows, cancel).await;
let ran = match &r {
Ok(_) => true,
Err(e) => !matches!(e.kind, ErrorKind::Cancelled | ErrorKind::PermissionDenied),
};
if ran {
self.remember_statement(id, statement);
}
r
}
fn remember_statement(&self, id: &str, statement: &str) {
let (history, source, text) = (self.history.clone(), split_target(id).0.to_owned(), statement.to_owned());
let time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0.0, |d| d.as_secs_f64() * 1000.0);
tokio::task::spawn_blocking(move || {
if let Err(e) = history.add(&source, &text, time) {
tracing::warn!("{}", e.message);
}
});
}
/// The query history of data source `id`, newest first.
pub async fn history(&self, id: &str) -> IdeResult<Vec<HistoryEntry>> {
let (history, source) = (self.history.clone(), split_target(id).0.to_owned());
tokio::task::spawn_blocking(move || history.list(&source)).await.map_err(|e| IdeError::internal(e.to_string()))
}
/// Forgets statements of the query history of `id` (all of them for `None`).
pub async fn remove_history(&self, id: &str, texts: Option<Vec<String>>) -> IdeResult<()> {
let (history, source) = (self.history.clone(), split_target(id).0.to_owned());
tokio::task::spawn_blocking(move || history.remove(&source, texts.as_deref()))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// The execution plan of `statement` (explained, not run).
pub async fn explain(&self, id: &str, statement: &str, cancel: &CancellationToken) -> IdeResult<Vec<PlanNode>> {
let driver = self.pool(id).await?.driver();
let result = self.run(id, &plan::explain_statement(driver, statement), MAX_META_ROWS, cancel).await?;
plan::parse(driver, &result)
}
async fn run(
&self,
id: &str,
statement: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let pool = self.pool(id).await?;
let session = self.sessions.lock().get(id).cloned();
+268
Переглянути файл
@@ -0,0 +1,268 @@
//! Execution plans (IDEA's Explain Plan): the `EXPLAIN` statement of each
//! dialect and its output read into one flat tree of operations.
use crate::DbDriver;
use crate::conn::QueryResult;
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbPlanProperty")]
pub struct PlanProperty {
pub name: String,
pub value: String,
}
/// One operation of a plan; `parent` indexes the plan's node list (roots: `None`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbPlanNode")]
pub struct PlanNode {
pub parent: Option<u32>,
/// `Full Scan`, `Index Scan`, `Hash Join`…
pub operation: String,
/// The object it works on and its key details (`table: o;`).
pub params: String,
pub properties: Vec<PlanProperty>,
}
/// The statement that explains `statement` without running it.
pub fn explain_statement(driver: DbDriver, statement: &str) -> String {
let s = statement.trim().trim_end_matches(';');
match driver {
DbDriver::Sqlite => format!("EXPLAIN QUERY PLAN {s}"),
DbDriver::Postgres => format!("EXPLAIN (FORMAT JSON) {s}"),
DbDriver::Mysql => format!("EXPLAIN {s}"),
}
}
/// Reads the result of [`explain_statement`].
pub fn parse(driver: DbDriver, result: &QueryResult) -> IdeResult<Vec<PlanNode>> {
match driver {
DbDriver::Sqlite => Ok(sqlite(&result.rows)),
DbDriver::Postgres => {
let text: String =
result.rows.iter().filter_map(|r| r.first().cloned().flatten()).collect::<Vec<_>>().join("\n");
let json: Value = serde_json::from_str(&text).map_err(|e| IdeError::invalid(format!("plan: {e}")))?;
let mut out = Vec::new();
for root in json.as_array().into_iter().flatten() {
if let Some(plan) = root.get("Plan") {
postgres(plan, None, &mut out);
}
}
Ok(out)
}
DbDriver::Mysql => {
let names: Vec<&str> = result.columns.iter().map(|c| c.name.as_str()).collect();
Ok(mysql(&names, &result.rows))
}
}
}
fn prop(name: &str, value: impl Into<String>) -> PlanProperty {
PlanProperty { name: name.to_owned(), value: value.into() }
}
/// SQLite rows: `id, parent, notused, detail` (`SCAN o`, `SEARCH c USING INTEGER PRIMARY KEY (rowid=?)`).
fn sqlite(rows: &[Vec<Option<String>>]) -> Vec<PlanNode> {
let mut ids: Vec<String> = Vec::new();
let mut out = Vec::new();
for r in rows {
let cell = |i: usize| r.get(i).cloned().flatten().unwrap_or_default();
let (id, parent, detail) = (cell(0), cell(1), cell(3));
let parent = ids.iter().position(|x| *x == parent).map(|i| i as u32);
let (operation, params) = sqlite_operation(&detail);
out.push(PlanNode { parent, operation, params, properties: vec![prop("Detail", detail.clone())] });
ids.push(id);
}
out
}
fn sqlite_operation(detail: &str) -> (String, String) {
let words: Vec<&str> = detail.split_whitespace().collect();
let object = |i: usize| words.get(i).map(|t| format!("table: {t};")).unwrap_or_default();
let using = || detail.find(" USING ").map(|i| detail[i + 1..].to_owned()).unwrap_or_default();
match words.first().copied() {
Some("SCAN") if detail.contains(" USING ") => ("Index Scan".into(), format!("{} {}", object(1), using())),
Some("SCAN") => ("Full Scan".into(), object(1)),
Some("SEARCH") => ("Index Scan".into(), format!("{} {}", object(1), using()).trim().to_owned()),
Some("USE") if detail.contains("ORDER BY") => ("Order By".into(), String::new()),
Some("USE") if detail.contains("GROUP BY") => ("Group By".into(), String::new()),
Some("USE") if detail.contains("DISTINCT") => ("Distinct".into(), String::new()),
_ => (detail.to_owned(), String::new()),
}
}
/// PostgreSQL JSON plan node: `Node Type`, `Relation Name`, nested `Plans`.
fn postgres(node: &Value, parent: Option<u32>, out: &mut Vec<PlanNode>) {
let text = |k: &str| node.get(k).and_then(Value::as_str).unwrap_or_default();
let mut operation = text("Node Type").to_owned();
if let Some(j) = node.get("Join Type").and_then(Value::as_str).filter(|j| *j != "Inner") {
operation = format!("{operation} ({j})");
}
let mut params = Vec::new();
if let Some(r) = node.get("Relation Name").and_then(Value::as_str) {
let alias = text("Alias");
params.push(if alias.is_empty() || alias == r {
format!("table: {r};")
} else {
format!("table: {r} {alias};")
});
}
if let Some(i) = node.get("Index Name").and_then(Value::as_str) {
params.push(format!("index: {i};"));
}
for k in ["Index Cond", "Hash Cond", "Merge Cond", "Filter", "Join Filter"] {
if let Some(c) = node.get(k).and_then(Value::as_str) {
params.push(format!("{}: {c};", k.to_lowercase()));
}
}
let properties = node
.as_object()
.into_iter()
.flatten()
.filter(|(k, _)| k.as_str() != "Plans")
.map(|(k, v)| {
let value = match v {
Value::String(s) => s.clone(),
Value::Array(a) => a
.iter()
.map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_owned))
.collect::<Vec<_>>()
.join(", "),
other => other.to_string(),
};
prop(k, value)
})
.collect();
let me = out.len() as u32;
out.push(PlanNode { parent, operation, params: params.join(" "), properties });
for child in node.get("Plans").and_then(Value::as_array).into_iter().flatten() {
postgres(child, Some(me), out);
}
}
/// MySQL's tabular `EXPLAIN`: one row per table access, flat.
fn mysql(names: &[&str], rows: &[Vec<Option<String>>]) -> Vec<PlanNode> {
let col = |r: &[Option<String>], n: &str| {
names.iter().position(|c| c.eq_ignore_ascii_case(n)).and_then(|i| r.get(i).cloned().flatten())
};
rows.iter()
.map(|r| {
let access = col(r, "type").unwrap_or_default();
let operation = match access.as_str() {
"ALL" => "Full Scan".to_owned(),
"index" => "Full Index Scan".to_owned(),
"range" => "Index Range Scan".to_owned(),
"ref" | "eq_ref" | "ref_or_null" => "Index Lookup".to_owned(),
"const" | "system" => "Constant Lookup".to_owned(),
"" => col(r, "Extra").unwrap_or_else(|| "Select".to_owned()),
other => other.to_owned(),
};
let mut params = Vec::new();
if let Some(t) = col(r, "table") {
params.push(format!("table: {t};"));
}
if let Some(k) = col(r, "key") {
params.push(format!("key: {k};"));
}
let properties = names.iter().zip(r).filter_map(|(n, v)| v.as_ref().map(|v| prop(n, v.clone()))).collect();
PlanNode { parent: None, operation, params: params.join(" "), properties }
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::conn::ResultColumn;
fn result(columns: &[&str], rows: Vec<Vec<Option<&str>>>) -> QueryResult {
QueryResult {
statement: String::new(),
columns: columns.iter().map(|c| ResultColumn { name: (*c).into(), type_name: String::new() }).collect(),
rows: rows.into_iter().map(|r| r.into_iter().map(|v| v.map(str::to_owned)).collect()).collect(),
affected: None,
has_more: false,
elapsed_ms: 0.0,
execution_ms: 0.0,
}
}
#[test]
fn explains_per_dialect() {
assert_eq!(explain_statement(DbDriver::Sqlite, "select 1;"), "EXPLAIN QUERY PLAN select 1");
assert_eq!(explain_statement(DbDriver::Postgres, " select 1 "), "EXPLAIN (FORMAT JSON) select 1");
assert_eq!(explain_statement(DbDriver::Mysql, "select 1"), "EXPLAIN select 1");
}
#[test]
fn reads_sqlite_plans_like_idea() {
let r = result(
&["id", "parent", "notused", "detail"],
vec![
vec![Some("3"), Some("0"), Some("0"), Some("SCAN o")],
vec![Some("5"), Some("0"), Some("0"), Some("SEARCH c USING INTEGER PRIMARY KEY (rowid=?)")],
vec![Some("9"), Some("0"), Some("0"), Some("USE TEMP B-TREE FOR ORDER BY")],
],
);
let plan = parse(DbDriver::Sqlite, &r).unwrap();
let ops: Vec<(&str, &str)> = plan.iter().map(|n| (n.operation.as_str(), n.params.as_str())).collect();
assert_eq!(
ops,
[
("Full Scan", "table: o;"),
("Index Scan", "table: c; USING INTEGER PRIMARY KEY (rowid=?)"),
("Order By", "")
]
);
assert!(plan.iter().all(|n| n.parent.is_none()));
}
#[test]
fn nests_sqlite_children_under_their_parent() {
let r = result(
&["id", "parent", "notused", "detail"],
vec![
vec![Some("2"), Some("0"), Some("0"), Some("CO-ROUTINE sub")],
vec![Some("4"), Some("2"), Some("0"), Some("SCAN t")],
],
);
let plan = parse(DbDriver::Sqlite, &r).unwrap();
assert_eq!(plan[1].parent, Some(0));
}
#[test]
fn reads_postgres_json_trees() {
let json = r#"[{"Plan": {"Node Type": "Hash Join", "Join Type": "Inner", "Hash Cond": "(o.customer_id = c.id)",
"Total Cost": 12.5, "Plans": [
{"Node Type": "Seq Scan", "Relation Name": "orders", "Alias": "o", "Filter": "(status <> 'x')"},
{"Node Type": "Hash", "Plans": [{"Node Type": "Seq Scan", "Relation Name": "customers", "Alias": "c"}]}
]}}]"#;
let plan = parse(DbDriver::Postgres, &result(&["QUERY PLAN"], vec![vec![Some(json)]])).unwrap();
assert_eq!(plan.len(), 4);
assert_eq!(plan[0].operation, "Hash Join");
assert_eq!(plan[0].params, "hash cond: (o.customer_id = c.id);");
assert!(plan[0].properties.iter().any(|p| p.name == "Total Cost" && p.value == "12.5"));
assert_eq!((plan[1].parent, plan[1].params.as_str()), (Some(0), "table: orders o; filter: (status <> 'x');"));
assert_eq!((plan[3].parent, plan[3].operation.as_str()), (Some(2), "Seq Scan"));
}
#[test]
fn reads_mysql_rows() {
let r = result(
&["id", "select_type", "table", "type", "key", "rows", "Extra"],
vec![
vec![Some("1"), Some("SIMPLE"), Some("o"), Some("ALL"), None, Some("20"), Some("Using where")],
vec![Some("1"), Some("SIMPLE"), Some("c"), Some("eq_ref"), Some("PRIMARY"), Some("1"), None],
],
);
let plan = parse(DbDriver::Mysql, &r).unwrap();
assert_eq!((plan[0].operation.as_str(), plan[0].params.as_str()), ("Full Scan", "table: o;"));
assert_eq!((plan[1].operation.as_str(), plan[1].params.as_str()), ("Index Lookup", "table: c; key: PRIMARY;"));
assert!(plan[0].properties.iter().any(|p| p.name == "rows" && p.value == "20"));
}
}
+17 -2
Переглянути файл
@@ -77,6 +77,8 @@ pub struct DbOptions {
pub keep_alive_secs: Option<u32>,
/// Disconnect after this long without statements (enforced by the UI, which sees the activity).
pub auto_disconnect_secs: Option<u32>,
/// PostgreSQL: show only the configured database, its schemas right under the data source.
pub single_database: bool,
}
/// Schemas tab: the databases / schemas the tree shows. Names may use `*` and `?`.
@@ -87,13 +89,26 @@ pub struct DbIntrospection {
pub databases: Vec<String>,
pub all_schemas: bool,
pub schemas: Vec<String>,
/// `pg_catalog`, `information_schema`, `mysql`…, and PostgreSQL template databases.
/// `pg_catalog`, `information_schema`, `mysql`…, and service databases (`rdsadmin`…).
pub show_system: bool,
/// PostgreSQL template databases (`template0`, `template1`).
pub show_templates: bool,
/// Object filter: the tree lists only tables, views, routines and sequences matching
/// one of these patterns (`*`, `?`; separated by commas or spaces). Empty: all.
pub object_filter: String,
}
impl Default for DbIntrospection {
fn default() -> Self {
Self { all_databases: true, databases: Vec::new(), all_schemas: true, schemas: Vec::new(), show_system: false }
Self {
all_databases: true,
databases: Vec::new(),
all_schemas: true,
schemas: Vec::new(),
show_system: false,
show_templates: false,
object_filter: String::new(),
}
}
}
+154 -7
Переглянути файл
@@ -32,10 +32,9 @@ pub fn qualified(driver: DbDriver, schema: &str, table: &str) -> String {
}
}
/// Databases one can connect to (PostgreSQL).
/// PostgreSQL databases one can connect to; templates only with `system`.
pub fn databases(system: bool) -> &'static str {
if system {
/// PostgreSQL databases one can connect to; template databases only with `templates`.
pub fn databases(templates: bool) -> &'static str {
if templates {
"SELECT datname FROM pg_database WHERE datallowconn ORDER BY datname"
} else {
"SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname"
@@ -65,7 +64,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
}
}
/// Rows: `name, kind` where kind is `table` or `view`.
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
pub fn tables(driver: DbDriver, schema: &str) -> String {
match driver {
DbDriver::Sqlite => format!(
@@ -73,7 +72,13 @@ pub fn tables(driver: DbDriver, schema: &str) -> String {
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
quote_ident(driver, schema)
),
_ => format!(
DbDriver::Postgres => format!(
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = {} AND c.relkind IN ('r', 'v', 'm', 'p', 'f') ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Mysql => 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",
quote_literal(driver, schema)
@@ -146,7 +151,7 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY m.name, p.cid"
}
DbDriver::Postgres => {
"SELECT n.nspname, c.relname, CASE WHEN c.relkind IN ('v', 'm') THEN 'view' ELSE 'table' END, a.attname, \
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, a.attname, \
format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, \
CASE WHEN EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary \
AND a.attnum = ANY(i.indkey)) THEN 1 ELSE 0 END, \
@@ -375,6 +380,123 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
)
}
/// Rows: `name, timing, events` of the triggers of a table (SQLite: `name, sql`).
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
DbDriver::Sqlite => format!(
"SELECT name, sql FROM {}.sqlite_master WHERE type = 'trigger' AND tbl_name = {t} ORDER BY name",
quote_ident(driver, schema)
),
DbDriver::Postgres => format!(
"SELECT t.tgname, CASE WHEN t.tgtype & 2 <> 0 THEN 'before' WHEN t.tgtype & 64 <> 0 THEN 'instead of' \
ELSE 'after' END, concat_ws(' or ', CASE WHEN t.tgtype & 4 <> 0 THEN 'insert' END, \
CASE WHEN t.tgtype & 16 <> 0 THEN 'update' END, CASE WHEN t.tgtype & 8 <> 0 THEN 'delete' END, \
CASE WHEN t.tgtype & 32 <> 0 THEN 'truncate' END) \
FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE NOT t.tgisinternal AND n.nspname = {s} AND c.relname = {t} ORDER BY 1"
),
DbDriver::Mysql => format!(
"SELECT trigger_name, lower(action_timing), lower(event_manipulation) FROM information_schema.triggers \
WHERE event_object_schema = {s} AND event_object_table = {t} ORDER BY 1"
),
}
}
/// `before`, `insert` of SQLite's `CREATE TRIGGER name BEFORE INSERT ON …` (its catalog keeps only the text).
pub fn sqlite_trigger_event(sql: &str) -> (String, String) {
let upper = sql.to_ascii_uppercase();
let words: Vec<&str> = upper.split_whitespace().collect();
let timing = if words.contains(&"BEFORE") {
"before"
} else if words.windows(2).any(|w| w == ["INSTEAD", "OF"]) {
"instead of"
} else {
"after"
};
let event = ["INSERT", "UPDATE", "DELETE"].into_iter().find(|e| words.contains(e)).unwrap_or_default();
(timing.to_owned(), event.to_ascii_lowercase())
}
/// Rows: `name, kind (function/procedure), arguments, result` of a schema's routines (none in SQLite).
pub fn routines(driver: DbDriver, schema: &str) -> Option<String> {
let s = quote_literal(driver, schema);
match driver {
DbDriver::Sqlite => None,
// Functions of extensions are left out, as in IDEA.
DbDriver::Postgres => Some(format!(
"SELECT p.proname, CASE WHEN p.prokind = 'p' THEN 'procedure' ELSE 'function' END, \
pg_get_function_identity_arguments(p.oid), pg_get_function_result(p.oid) \
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace \
WHERE n.nspname = {s} AND p.prokind IN ('f', 'p') \
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e') ORDER BY 1, 3"
)),
DbDriver::Mysql => Some(format!(
"SELECT r.routine_name, lower(r.routine_type), \
(SELECT GROUP_CONCAT(CONCAT(p.parameter_name, ' ', p.dtd_identifier) ORDER BY p.ordinal_position \
SEPARATOR ', ') FROM information_schema.parameters p WHERE p.specific_schema = r.routine_schema \
AND p.specific_name = r.specific_name AND p.ordinal_position > 0), r.dtd_identifier \
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
)),
}
}
/// Rows: `name, data type` of a schema's sequences (PostgreSQL).
pub fn sequences(driver: DbDriver, schema: &str) -> Option<String> {
(driver == DbDriver::Postgres).then(|| {
format!(
"SELECT sequence_name, data_type FROM information_schema.sequences WHERE sequence_schema = {} ORDER BY 1",
quote_literal(driver, schema)
)
})
}
/// The statement reading the definition of a routine (a row per overload), trigger
/// or sequence, and the column that holds it.
pub fn object_ddl(driver: DbDriver, schema: &str, kind: crate::DbObjectKind, name: &str) -> Option<(String, usize)> {
use crate::DbObjectKind as K;
let (s, n) = (quote_literal(driver, schema), quote_literal(driver, name));
let target = qualified(driver, schema, name);
Some(match (driver, kind) {
(DbDriver::Sqlite, K::Trigger) => (
format!(
"SELECT sql FROM {}.sqlite_master WHERE type = 'trigger' AND name = {n}",
quote_ident(driver, schema)
),
0,
),
(DbDriver::Postgres, K::Function | K::Procedure) => (
format!(
"SELECT pg_get_functiondef(p.oid) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace \
WHERE n.nspname = {s} AND p.proname = {n} ORDER BY pg_get_function_identity_arguments(p.oid)"
),
0,
),
(DbDriver::Postgres, K::Trigger) => (
format!(
"SELECT pg_get_triggerdef(t.oid, true) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid \
JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE NOT t.tgisinternal AND n.nspname = {s} AND t.tgname = {n}"
),
0,
),
(DbDriver::Postgres, K::Sequence) => (
format!(
"SELECT format(E'create sequence %s\\n as %s\\n increment by %s\\n minvalue %s\\n \
maxvalue %s\\n start with %s%s', {}, data_type, increment_by, min_value, max_value, start_value, \
CASE WHEN cycle THEN E'\\n cycle' ELSE '' END) \
FROM pg_sequences WHERE schemaname = {s} AND sequencename = {n}",
quote_literal(driver, &target)
),
0,
),
(DbDriver::Mysql, K::Function) => (format!("SHOW CREATE FUNCTION {target}"), 2),
(DbDriver::Mysql, K::Procedure) => (format!("SHOW CREATE PROCEDURE {target}"), 2),
(DbDriver::Mysql, K::Trigger) => (format!("SHOW CREATE TRIGGER {target}"), 2),
_ => return None,
})
}
/// A column of [`postgres_table_ddl`].
pub struct DdlColumn {
pub name: String,
@@ -464,6 +586,31 @@ mod tests {
assert!(edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![] }).is_err());
}
#[test]
fn sqlite_trigger_events() {
let ev = sqlite_trigger_event;
assert_eq!(
ev("CREATE TRIGGER t BEFORE UPDATE OF a ON x BEGIN SELECT 1; END"),
("before".into(), "update".into())
);
assert_eq!(ev("create trigger t instead of insert on v begin end"), ("instead of".into(), "insert".into()));
assert_eq!(ev("CREATE TRIGGER t DELETE ON x BEGIN END"), ("after".into(), "delete".into()));
}
#[test]
fn schema_objects_per_dialect() {
use crate::DbObjectKind as K;
assert!(routines(DbDriver::Sqlite, "main").is_none());
assert!(sequences(DbDriver::Mysql, "db").is_none());
assert!(routines(DbDriver::Postgres, "public").unwrap().contains("n.nspname = 'public'"));
assert_eq!(
object_ddl(DbDriver::Mysql, "db", K::Procedure, "p"),
Some(("SHOW CREATE PROCEDURE `db`.`p`".into(), 2))
);
assert!(object_ddl(DbDriver::Sqlite, "main", K::Function, "f").is_none());
assert!(object_ddl(DbDriver::Postgres, "s", K::Sequence, "q").unwrap().0.contains("sequencename = 'q'"));
}
#[test]
fn postgres_ddl() {
let cols = [
+52 -1
Переглянути файл
@@ -7,7 +7,7 @@ async fn setup() -> (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 db = DbManager::new(root.clone(), root.join("passwords.json"));
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"));
db.save_sources(vec![DataSource {
id: "s1".into(),
name: "app".into(),
@@ -247,6 +247,57 @@ async fn ddl_of_tables_and_views() -> IdeResult<()> {
Ok(())
}
#[tokio::test]
async fn explains_queries_without_running_them() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let c = CancellationToken::new();
let plan = db.explain("s1", "SELECT * FROM users WHERE id > 1 ORDER BY note;", &c).await?;
let ops: Vec<_> = plan.iter().map(|n| n.operation.as_str()).collect();
assert_eq!(ops, vec!["Index Scan", "Order By"]);
assert!(plan[0].params.starts_with("table: users;"), "{}", plan[0].params);
db.explain("s1", "DELETE FROM users", &c).await?;
assert_eq!(count(&db).await, "3");
Ok(())
}
#[tokio::test]
async fn records_executed_statements_in_the_query_history() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let c = CancellationToken::new();
db.execute("s1", "SELECT 1", 1, &c).await?;
assert!(db.execute("s1", "SELECT nope", 1, &c).await.is_err());
// Recorded off the async threads.
let mut texts = Vec::new();
for _ in 0..50 {
texts = db.history("s1").await?.into_iter().map(|e| e.text).collect::<Vec<_>>();
if texts.first().map(String::as_str) == Some("SELECT nope") {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert_eq!(texts[..2], ["SELECT nope", "SELECT 1"]);
db.remove_history("s1", Some(vec!["SELECT 1".into()])).await?;
assert!(!db.history("s1").await?.iter().any(|e| e.text == "SELECT 1"));
db.remove_history("s1", None).await?;
assert!(db.history("s1").await?.is_empty());
Ok(())
}
#[tokio::test]
async fn lists_triggers_and_their_ddl() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let c = CancellationToken::new();
db.execute("s1", "CREATE TRIGGER users_touch AFTER UPDATE ON users BEGIN SELECT 1; END", 1, &c).await?;
let d = db.table_details("s1", "main", "users").await?;
let triggers: Vec<_> = d.triggers.iter().map(|t| (t.name.as_str(), t.timing.as_str(), t.events.as_str())).collect();
assert_eq!(triggers, vec![("users_touch", "after", "update")]);
let ddl = db.object_ddl("s1", "main", ide_db::DbObjectKind::Trigger, "users_touch").await?;
assert!(ddl.starts_with("CREATE TRIGGER users_touch"), "{ddl}");
// SQLite has neither routines nor sequences.
assert_eq!(db.schema_objects("s1", "main").await?, ide_db::SchemaObjects::default());
Ok(())
}
#[tokio::test]
async fn applies_driver_properties_and_the_startup_script_on_connect() -> IdeResult<()> {
let (tmp, db) = setup().await;
+117 -8
Переглянути файл
@@ -1,7 +1,8 @@
//! Transport shared by the LSP and DAP clients.
//!
//! * [`framing`]: `Content-Length` header framing over any async byte stream
//! (used by both protocols).
//! (used by both protocols), and newline-delimited JSON ([`Framing::Lines`],
//! the Agent Client Protocol).
//! * [`Peer`]: a JSON-RPC 2.0 endpoint with request/response correlation,
//! cancellation (`$/cancelRequest`) and handlers for server→client traffic.
@@ -88,6 +89,34 @@ pub mod framing {
writer.write_all(&buf).await?;
writer.flush().await
}
/// Reads one newline-terminated message, skipping blank lines.
pub async fn read_line_message<R: AsyncBufRead + Unpin>(reader: &mut R) -> std::io::Result<Option<Vec<u8>>> {
let mut line = Vec::new();
loop {
line.clear();
let n = (&mut *reader).take(MAX_MESSAGE_LEN as u64 + 1).read_until(b'\n', &mut line).await?;
if n == 0 {
return Ok(None);
}
if line.len() > MAX_MESSAGE_LEN {
return Err(Error::new(ErrorKind::InvalidData, "message too large"));
}
let text = trim_line(&line);
if !text.iter().all(u8::is_ascii_whitespace) {
return Ok(Some(text.to_vec()));
}
}
}
/// Writes one message followed by `\n` and flushes once.
pub async fn write_line_message<W: AsyncWrite + Unpin>(writer: &mut W, body: &[u8]) -> std::io::Result<()> {
let mut buf = Vec::with_capacity(body.len() + 1);
buf.extend_from_slice(body);
buf.push(b'\n');
writer.write_all(&buf).await?;
writer.flush().await
}
}
use parking_lot::Mutex;
@@ -210,6 +239,32 @@ impl Inner {
}
}
/// How messages are delimited on the wire.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Framing {
/// `Content-Length` headers (LSP, DAP).
#[default]
ContentLength,
/// One JSON message per line (Agent Client Protocol).
Lines,
}
impl Framing {
async fn read<R: tokio::io::AsyncBufRead + Unpin>(self, reader: &mut R) -> std::io::Result<Option<Vec<u8>>> {
match self {
Framing::ContentLength => framing::read_message(reader).await,
Framing::Lines => framing::read_line_message(reader).await,
}
}
async fn write<W: AsyncWrite + Unpin>(self, writer: &mut W, body: &[u8]) -> std::io::Result<()> {
match self {
Framing::ContentLength => framing::write_message(writer, body).await,
Framing::Lines => framing::write_line_message(writer, body).await,
}
}
}
/// A connected JSON-RPC peer. Cloning shares the connection.
#[derive(Clone)]
pub struct Peer {
@@ -238,12 +293,26 @@ impl Peer {
env: &[(String, String)],
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> std::io::Result<Self> {
Self::spawn_framed(command, args, cwd, env, handler, on_stderr, Framing::ContentLength)
}
/// [`spawn`](Self::spawn) with the given wire framing.
pub fn spawn_framed(
command: &str,
args: &[String],
cwd: &std::path::Path,
env: &[(String, String)],
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
framing: Framing,
) -> std::io::Result<Self> {
use std::process::Stdio;
let mut cmd = tokio::process::Command::new(command);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(args)
.current_dir(cwd)
.envs(ide_core::process::shell_env())
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
@@ -255,7 +324,7 @@ impl Peer {
let stderr = child.stderr.take();
let pid = child.id();
let peer = Self::start(stdout, stdin, handler, false, pid);
let peer = Self::start(stdout, stdin, handler, false, pid, framing);
if let Some(stderr) = stderr {
let name = command.to_owned();
@@ -276,7 +345,13 @@ impl Peer {
});
}
let inner = peer.inner.clone();
peer.supervise(child);
Ok(peer)
}
/// Kills `child` when the connection is torn down; closes the connection when it exits.
fn supervise(&self, mut child: tokio::process::Child) {
let inner = self.inner.clone();
tokio::spawn(async move {
let status = tokio::select! {
status = child.wait() => status.ok(),
@@ -287,7 +362,6 @@ impl Peer {
};
inner.mark_closed(status.and_then(|s| s.code()));
});
Ok(peer)
}
/// Speaks JSON-RPC over arbitrary byte streams (in-memory pipes in tests, TCP sockets).
@@ -299,10 +373,45 @@ impl Peer {
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::start(reader, writer, handler, true, None)
Self::start(reader, writer, handler, true, None, Framing::ContentLength)
}
fn start<R, W>(reader: R, mut writer: W, handler: Arc<dyn Handler>, close_on_eof: bool, pid: Option<u32>) -> Self
/// [`connect`](Self::connect) with the given wire framing.
pub fn connect_framed<R, W>(reader: R, writer: W, handler: Arc<dyn Handler>, framing: Framing) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::start(reader, writer, handler, true, None, framing)
}
/// [`Peer::connect`] over streams served by `child` (a server reached over a socket
/// it listens on): the child is killed with the connection, and its exit closes it.
///
/// Must be called from within a Tokio runtime.
pub fn connect_with_child<R, W>(
reader: R,
writer: W,
handler: Arc<dyn Handler>,
child: tokio::process::Child,
) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
let peer = Self::start(reader, writer, handler, true, child.id(), Framing::ContentLength);
peer.supervise(child);
peer
}
fn start<R, W>(
reader: R,
mut writer: W,
handler: Arc<dyn Handler>,
close_on_eof: bool,
pid: Option<u32>,
framing: Framing,
) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
@@ -330,7 +439,7 @@ impl Peer {
_ = kill.cancelled() => None,
};
let Some(body) = body else { break };
if let Err(e) = framing::write_message(&mut writer, &body).await {
if let Err(e) = framing.write(&mut writer, &body).await {
tracing::debug!("jsonrpc write failed: {e}");
if let Some(inner) = weak.upgrade() {
inner.close_transport();
@@ -369,7 +478,7 @@ impl Peer {
let mut reader = BufReader::new(reader);
loop {
let msg = tokio::select! {
msg = framing::read_message(&mut reader) => msg,
msg = framing.read(&mut reader) => msg,
_ = inner.kill.cancelled() => break,
};
match msg {
+22
Переглянути файл
@@ -120,6 +120,28 @@ async fn request_response_and_errors() {
assert!(matches!(err, RpcError::Protocol(_)));
}
#[tokio::test]
async fn line_framing_round_trips_and_skips_blank_lines() {
let mut buf = Vec::new();
framing::write_line_message(&mut buf, br#"{"a":1}"#).await.unwrap();
buf.extend_from_slice(b"\r\n\n{\"b\":2}\r\n");
let mut reader = tokio::io::BufReader::new(&buf[..]);
assert_eq!(framing::read_line_message(&mut reader).await.unwrap().unwrap(), br#"{"a":1}"#);
assert_eq!(framing::read_line_message(&mut reader).await.unwrap().unwrap(), br#"{"b":2}"#);
assert!(framing::read_line_message(&mut reader).await.unwrap().is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn line_framed_peers_talk() {
let (a_io, b_io) = duplex(64 * 1024);
let (ar, aw) = tokio::io::split(a_io);
let (br, bw) = tokio::io::split(b_io);
let client = Peer::connect_framed(ar, aw, Arc::new(NoopHandler), Framing::Lines);
let _server = Peer::connect_framed(br, bw, Arc::new(Recorder::default()), Framing::Lines);
let v: Value = client.request("echo", json!({"x": "line\nbreak"}), None).await.unwrap();
assert_eq!(v, json!({"x": "line\nbreak"}));
}
#[tokio::test(flavor = "multi_thread")]
async fn notifications_arrive_in_order() {
let rec = Arc::new(Recorder::default());
+1
Переглянути файл
@@ -53,6 +53,7 @@ tree-sitter-xml = "0.7.0"
tree-sitter-haskell = "0.23.1"
tree-sitter-dart = "0.2.0"
tree-sitter-graphql = "0.3.0"
tree-sitter-gdscript = "6.1.0"
[dev-dependencies]
criterion = { version = "0.5", default-features = false }
+60
Переглянути файл
@@ -0,0 +1,60 @@
; GDScript highlighting (the grammar crate ships no query). Later patterns win.
(identifier) @variable
(name) @variable
(comment) @comment
[(region_start) (region_end)] @comment
(string) @string
(escape_sequence) @string.escape
[(string_name) (node_path) (get_node)] @string.special
(integer) @number
(float) @number
[(true) (false) (null)] @constant.builtin
(type) @type
(type (identifier) @type)
(extends_statement (type) @type)
(class_name_statement name: (name) @type)
(class_definition name: (name) @type)
(enum_definition name: (name) @type)
(enumerator left: (identifier) @constant)
(function_definition name: (name) @function.definition)
(constructor_definition "_init" @function.definition)
(lambda name: (name) @function.definition)
(signal_statement name: (name) @function.definition)
(call (identifier) @function)
(attribute_call (identifier) @function)
(base_call (identifier) @function)
(attribute (identifier) (identifier) @variable.member)
((identifier) @constant
(#lua-match? @constant "^[A-Z][A-Z_0-9]*$"))
((identifier) @variable.builtin
(#lua-match? @variable.builtin "^self$"))
(const_statement name: (name) @constant)
(typed_parameter (identifier) @variable.parameter)
(default_parameter (identifier) @variable.parameter)
(typed_default_parameter (identifier) @variable.parameter)
(annotation "@" @attribute (identifier) @attribute)
[(remote_keyword) (static_keyword)] @keyword
[(breakpoint_statement) (pass_statement) (break_statement) (continue_statement)] @keyword
[
"if" "elif" "else" "for" "while" "match" "when" "return" "await"
"func" "class" "class_name" "extends" "signal" "enum" "const" "var"
"set" "get" "setget" "onready" "export" "in" "is" "as" "and" "or" "not"
] @keyword
[
"+" "-" "*" "/" "%" "**" "<<" ">>" "&" "|" "^" "~" "!" "&&" "||"
"==" "!=" "<" "<=" ">" ">=" "=" ":=" "+=" "-=" "*=" "/=" "%=" "**="
"<<=" ">>=" "&=" "|=" "^=" "->"
] @operator
["(" ")" "[" "]" "{" "}"] @punctuation.bracket
["," "." ":" ";"] @punctuation.delimiter
+14
Переглянути файл
@@ -0,0 +1,14 @@
(class_name_statement name: (name) @name) @def.class
(class_definition name: (name) @name) @def.class
(function_definition name: (name) @name parameters: (parameters) @detail) @def.function
(constructor_definition "_init" @name parameters: (parameters) @detail) @def.constructor
(signal_statement name: (name) @name) @def.event
(enum_definition name: (name) @name) @def.enum
(enumerator left: (identifier) @name) @def.enum_member
(const_statement name: (name) @name) @def.constant
(source (variable_statement name: (name) @name) @def.field)
(source (export_variable_statement name: (name) @name) @def.field)
(source (onready_variable_statement name: (name) @name) @def.field)
(class_body (variable_statement name: (name) @name) @def.field)
(class_body (export_variable_statement name: (name) @name) @def.field)
(class_body (onready_variable_statement name: (name) @name) @def.field)
+12
Переглянути файл
@@ -75,6 +75,14 @@ pub struct LanguageServerConfig {
/// Human hint shown when the binary is missing.
#[serde(default)]
pub install_hint: Option<String>,
/// `host:port` of a server that speaks LSP over TCP (Godot's editor). Connects
/// there when something listens; otherwise starts `command` (when installed)
/// and connects once it accepts: to `127.0.0.1:${port}` when the arguments
/// contain `${port}` (a free port), else to this address. `${root}` in the
/// arguments is the workspace root. A server reached without starting it is
/// never shut down or killed by the IDE.
#[serde(default)]
pub connect: Option<String>,
/// An alternative to the servers listed before it (pyright after
/// basedpyright): only used while none of those is installed.
#[serde(default)]
@@ -96,6 +104,10 @@ pub struct DebuggerConfig {
/// `stdio` or `tcp`.
#[serde(default = "default_transport")]
pub transport: String,
/// `tcp` only: `host:port` of an adapter running inside another program (the
/// Godot editor). Used when it accepts connections; otherwise `command` is started.
#[serde(default)]
pub connect: Option<String>,
#[serde(default)]
pub install_hint: Option<String>,
}
+38
Переглянути файл
@@ -22,9 +22,12 @@ const BUILTIN: &[(&str, &str)] = &[
("erlang", include_str!("../../../languages/erlang.toml")),
("fsharp", include_str!("../../../languages/fsharp.toml")),
("gitattributes", include_str!("../../../languages/gitattributes.toml")),
("gdscript", include_str!("../../../languages/gdscript.toml")),
("gdshader", include_str!("../../../languages/gdshader.toml")),
("go", include_str!("../../../languages/go.toml")),
("gomod", include_str!("../../../languages/gomod.toml")),
("gowork", include_str!("../../../languages/gowork.toml")),
("godot-resource", include_str!("../../../languages/godot-resource.toml")),
("graphql", include_str!("../../../languages/graphql.toml")),
("groovy", include_str!("../../../languages/groovy.toml")),
("haskell", include_str!("../../../languages/haskell.toml")),
@@ -542,10 +545,17 @@ mod tests {
}
for ls in &cfg.language_servers {
assert!(!ls.command.is_empty() && ls.install_hint.is_some(), "{name}: {} incomplete", ls.name);
if let Some(addr) = &ls.connect {
assert!(addr.parse::<std::net::SocketAddr>().is_ok(), "{name}: bad connect address {addr}");
}
}
if let Some(d) = &cfg.debugger {
assert!(matches!(d.transport.as_str(), "stdio" | "tcp"), "{name}: bad transport");
assert!(d.install_hint.is_some(), "{name}: debugger without install hint");
if let Some(addr) = &d.connect {
assert_eq!(d.transport, "tcp", "{name}: `connect` needs the tcp transport");
assert!(addr.parse::<std::net::SocketAddr>().is_ok(), "{name}: bad connect address {addr}");
}
}
for ext in &cfg.extensions {
assert_eq!(ext, &ext.to_ascii_lowercase(), "{name}: extensions must be lower case");
@@ -679,6 +689,13 @@ mod tests {
(".gitignore", "ignore"),
(".gitattributes", "gitattributes"),
("server.log", "log"),
("player.gd", "gdscript"),
("main.tscn", "godot-resource"),
("theme.tres", "godot-resource"),
("project.godot", "godot-resource"),
("icon.svg.import", "godot-resource"),
("export_presets.cfg", "godot-resource"),
("water.gdshader", "gdshader"),
("notes.txt", "plaintext"),
];
for (path, id) in cases {
@@ -686,6 +703,27 @@ mod tests {
}
}
#[test]
fn gdscript_definition() {
let reg = reg();
let gd = reg.get(&LanguageId::new("gdscript")).unwrap();
assert_eq!(gd.line_comment.as_deref(), Some("#"));
let indent = gd.indent.unwrap();
assert!(!indent.insert_spaces, "Godot indents with tabs");
assert_eq!(gd.tree_sitter.as_deref(), Some("gdscript"));
let ls = &gd.language_servers[0];
assert_eq!((ls.name.as_str(), ls.command.as_str()), ("godot", "godot"));
assert_eq!(ls.connect.as_deref(), Some("127.0.0.1:6005"));
assert_eq!(ls.root_markers, ["project.godot"]);
assert!(ls.args.iter().any(|a| a == "${port}") && ls.args.iter().any(|a| a == "${root}"));
let dbg = gd.debugger.as_ref().unwrap();
assert_eq!((dbg.adapter.as_str(), dbg.transport.as_str()), ("godot", "tcp"));
assert_eq!(dbg.connect.as_deref(), Some("127.0.0.1:6006"));
assert!(dbg.args.iter().any(|a| a == "--dap-port"));
let res = reg.get(&LanguageId::new("godot-resource")).unwrap();
assert_eq!(res.line_comment.as_deref(), Some(";"));
}
#[test]
fn detects_shebangs() {
let reg = reg();
+10
Переглянути файл
@@ -450,4 +450,14 @@ pub(crate) static SPECS: &[Spec] = &[
imports: NONE,
constructors: NONE,
},
Spec {
name: "gdscript",
language: tree_sitter_gdscript::LANGUAGE,
outline: outline!("gdscript"),
highlights: Some(Highlights { query: highlights!("gdscript"), first_wins: false }),
fold_nodes: &["string"],
fold_bodies: &["body", "class_body", "match_body"],
imports: NONE,
constructors: &["_init"],
},
];
+25
Переглянути файл
@@ -440,6 +440,31 @@ mod tests {
],
),
("make", "# hi\nCC := gcc\nall: main.o\n\t$(CC) -o app main.o\n", &[("# hi", K::Comment)]),
(
"gdscript",
"extends Node2D\nclass_name Player\n# hi\n@export var speed: float = 1.5\nconst MAX_HP = 10\nsignal died(cause)\n\nfunc _ready() -> void:\n\tvar label = $Label\n\tself.position.x += speed\n\tprint(\"ready\", &\"name\", 3)\n",
&[
("extends", K::Keyword),
("Node2D", K::Type),
("class_name", K::Keyword),
("Player", K::Type),
("# hi", K::Comment),
("@export", K::Attribute),
("var", K::Keyword),
("float", K::Type),
("1.5", K::Number),
("MAX_HP", K::Constant),
("signal", K::Keyword),
("func", K::Keyword),
("_ready", K::Function),
("$Label", K::StringSpecial),
("self", K::SelfVariable),
("print", K::FunctionCall),
("\"ready\"", K::String),
("&\"name\"", K::StringSpecial),
("3", K::Number),
],
),
];
for (lang, src, expect) in cases {
let got = spans(lang, src);
+18
Переглянути файл
@@ -902,6 +902,24 @@ fn outline_more_languages() {
Function build
",
);
check_outline(
"gdscript",
"class_name Player\nextends Node\n\nsignal died\nenum State { IDLE, RUN }\nconst SPEED = 2\n@export var hp := 3\n\nfunc _init(a):\n\tpass\n\nfunc jump(height: float) -> void:\n\tvar local = 1\n\nclass Inner:\n\tvar x = 0\n\tfunc go():\n\t\tpass\n",
"
Class Player
Event died
Enum State
EnumMember IDLE
EnumMember RUN
Constant SPEED
Field hp
Constructor _init
Function jump
Class Inner
Field x
Method go
",
);
check_outline(
"cmake",
"project(Foo)\nfunction(my_fn arg)\n message(${arg})\nendfunction()\nadd_executable(app main.c)\n",
+1 -1
Переглянути файл
@@ -14,7 +14,7 @@ lsp-types.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["net"] }
parking_lot.workspace = true
tracing.workspace = true
futures.workspace = true
+11 -1
Переглянути файл
@@ -75,8 +75,12 @@ impl ClientHandler {
_ => return,
}
};
let ended = matches!(&event, IdeEvent::Task { done: true, .. });
mgr.sink().emit(event);
self.server.refresh_busy_status(mgr.sink());
if ended {
self.server.progress_ended();
}
}
fn publish_diagnostics(&self, mgr: &LspManager, params: Value) {
@@ -88,6 +92,10 @@ impl ClientHandler {
}
};
let Some(path) = uri_to_path(params.uri.as_str()) else { return };
// Files opened only for a request (references search) are not the user's problems.
if self.server.suppresses_diagnostics(&path) {
return;
}
let conv = mgr.conv(self.encoding());
let items = params
.diagnostics
@@ -128,7 +136,8 @@ impl ClientHandler {
Value::Array(
items
.iter()
.map(|item| match item.get("section").and_then(Value::as_str) {
// vtsls asks for the whole configuration as section `""`.
.map(|item| match item.get("section").and_then(Value::as_str).filter(|s| !s.is_empty()) {
Some(section) if section == self.server.name => options.clone(),
// Servers that take settings under `initializationOptions.settings`
// (jdtls) ask for the same sections later.
@@ -193,6 +202,7 @@ impl Handler for ClientHandler {
_ => tracing::debug!("[{}] {text}", self.server.name),
}
}
"tsserver/request" => mgr.forward_tsserver_requests(self.server.clone(), self.generation, params),
"telemetry/event" | "$/logTrace" | "$/cancelRequest" => {}
other => tracing::trace!("[{}] unhandled notification {other}", self.server.name),
}
+4
Переглянути файл
@@ -74,6 +74,9 @@ pub struct JavaLaunchInfo {
pub java_home: Option<ide_core::IpcPath>,
/// The `java` launcher to use (filled in by the caller from the installed JDKs).
pub java_exec: Option<String>,
/// How a launcher that builds the command line itself must shorten it (java-debug's
/// `shortenCommandLine`: `none` | `jarmanifest` | `argfile`; filled in by the caller).
pub shorten_command_line: Option<String>,
/// First compile errors of the workspace when the build had errors.
pub errors: Vec<JavaCompileError>,
/// All compile errors (`errors` is capped).
@@ -273,6 +276,7 @@ impl LspManager {
module_paths: cp.module_paths,
java_home: java_home.map(Into::into),
java_exec: None,
shorten_command_line: None,
errors,
error_count,
hints: Vec::new(),
+44 -3
Переглянути файл
@@ -1,5 +1,6 @@
//! Starting server processes: binary resolution and the [`Launcher`] seam.
use ide_core::CancellationToken;
use ide_jsonrpc::{Handler, Peer};
use ide_language::LanguageServerConfig;
use std::ffi::OsString;
@@ -27,13 +28,28 @@ pub trait Launcher: Send + Sync + 'static {
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> Result<Peer, LaunchError>;
/// [`Launcher::launch`] that gives up once `cancel` fires (the server was stopped
/// while still starting). Launchers that return at once need not override it.
fn launch_cancellable(
&self,
config: &LanguageServerConfig,
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
let _ = cancel;
self.launch(config, root, handler, on_stderr)
}
/// Whether `config` could start without a `Missing` error.
fn available(&self, _config: &LanguageServerConfig, _root: &Path) -> bool {
true
}
}
/// Resolves `command` on an augmented `PATH` and spawns it with stdio transport.
/// Resolves `command` on an augmented `PATH` and spawns it with stdio transport,
/// or for a `connect` server reaches it over TCP (see [`crate::tcp`]).
pub struct ProcessLauncher;
impl Launcher for ProcessLauncher {
@@ -43,12 +59,37 @@ impl Launcher for ProcessLauncher {
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> Result<Peer, LaunchError> {
self.launch_cancellable(config, root, handler, on_stderr, &CancellationToken::new())
}
fn launch_cancellable(
&self,
config: &LanguageServerConfig,
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
let search = server_search_path(config);
let binary = which::which_in(&config.command, Some(&search), root).map_err(|_| LaunchError::Missing)?;
let binary = resolve_rustup_proxy(&config.command, binary);
let binary = which::which_in(&config.command, Some(&search), root)
.ok()
.map(|b| resolve_rustup_proxy(&config.command, b));
let mut env: Vec<(String, String)> = vec![("PATH".into(), search.to_string_lossy().into_owned())];
env.extend(config.env.iter().filter(|(k, _)| *k != "PATH").map(|(k, v)| (k.clone(), v.clone())));
if let Some(addr) = &config.connect {
return crate::tcp::connect_or_start(
config,
addr,
binary.as_deref(),
&env,
root,
handler,
on_stderr,
cancel,
);
}
let binary = binary.ok_or(LaunchError::Missing)?;
Peer::spawn(&binary.to_string_lossy(), &config.args, root, &env, handler, on_stderr)
.map_err(|e| LaunchError::Failed(format!("failed to start {}: {e}", binary.display())))
}
+152 -77
Переглянути файл
@@ -13,14 +13,18 @@ mod handler;
mod inspect;
pub mod jdtls;
mod launch;
mod scope;
mod server;
mod tcp;
mod text;
mod tsserver_bridge;
pub mod types;
mod uri;
mod virtual_doc;
pub use inspect::{FileInspection, InspectHost, InspectOptions};
pub use launch::{LaunchError, Launcher, ProcessLauncher, search_path};
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
pub use uri::{is_virtual_uri, path_to_uri_string, uri_target, uri_to_path};
use caps::{ServerCaps, SyncKind};
@@ -141,6 +145,7 @@ pub struct LspManager {
docs: Mutex<HashMap<DocId, DocState>>,
apply_edit_hook: RwLock<Option<ApplyEditHook>>,
config_hook: RwLock<Option<ConfigHook>>,
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
shutting_down: AtomicBool,
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
shown_messages: Mutex<HashSet<(String, String)>>,
@@ -181,6 +186,19 @@ fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
}
}
/// Sends the user's `didOpen` for `path`, closing a transient copy of the file
/// first (one a references search opened).
fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, params: Value) {
if server.take_transient(path, run.generation)
&& let Err(e) = run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", server.name);
}
if let Err(e) = run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", server.name);
}
}
fn unsupported(feature: &str) -> IdeError {
IdeError::unavailable(format!("no running language server supports {feature}"))
}
@@ -233,6 +251,7 @@ impl LspManager {
docs: Mutex::new(HashMap::new()),
apply_edit_hook: RwLock::new(None),
config_hook: RwLock::new(None),
candidates_hook: RwLock::new(None),
shutting_down: AtomicBool::new(false),
shown_messages: Mutex::new(HashSet::new()),
virtual_origins: Mutex::new(HashMap::new()),
@@ -297,10 +316,8 @@ impl LspManager {
}
let mut attached = Attached { server: server.clone(), opened_gen: None };
if let Some(run) = server.running() {
if run.caps.read().open_close
&& let Err(e) = run.peer.notify("textDocument/didOpen", d.did_open_params())
{
tracing::debug!("{}: didOpen: {e}", server.name);
if run.caps.read().open_close {
user_did_open(&server, &run, &d.path, &d.uri, d.did_open_params());
}
attached.opened_gen = Some(run.generation);
}
@@ -331,7 +348,9 @@ impl LspManager {
let handler = Arc::new(handler::ClientHandler::new(self.me.clone(), server.clone(), generation));
let me = self.clone();
let tail = server.clone();
// The settings hook may touch the filesystem (e.g. scanning for JDKs).
let cancel = server.start_token();
// The settings hook may touch the filesystem (e.g. scanning for JDKs); TCP
// servers may take a while to start listening.
let launched = tokio::task::spawn_blocking(move || {
let cfg = me.configured(&tail);
tail.set_effective_config(cfg.clone());
@@ -341,7 +360,7 @@ impl LspManager {
let missing = !me.launcher.available(&cfg, &root);
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
}
me.launcher.launch(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)))
me.launcher.launch_cancellable(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)), &cancel)
})
.await
.unwrap_or_else(|e| Err(LaunchError::Failed(e.to_string())));
@@ -443,9 +462,11 @@ impl LspManager {
return;
}
let tail = server.stderr_tail(5);
let mut message = match code {
Some(c) => format!("{} exited with code {c}", server.name),
None => format!("{} terminated unexpectedly", server.name),
let cfg = server.effective_config();
let mut message = match (code, &cfg.connect) {
(Some(c), _) => format!("{} exited with code {c}", server.name),
(None, Some(addr)) => format!("{}: the connection to the server ({addr}) closed", server.name),
(None, None) => format!("{} terminated unexpectedly", server.name),
};
if !tail.is_empty() {
message.push_str(":\n");
@@ -475,6 +496,7 @@ impl LspManager {
for (id, title) in server.take_progress() {
self.sink.emit(ide_core::IdeEvent::Task { id, title, message: None, fraction: None, done: true });
}
server.progress_ended();
for path in server.take_diagnostic_paths() {
self.sink.emit(ide_core::IdeEvent::Diagnostics {
path: path.into(),
@@ -590,10 +612,8 @@ impl LspManager {
let params = state.did_open_params();
for a in &mut state.servers {
if let Some(run) = a.server.running() {
if run.caps.read().open_close
&& let Err(e) = run.peer.notify("textDocument/didOpen", params.clone())
{
tracing::debug!("{}: didOpen: {e}", a.server.name);
if run.caps.read().open_close {
user_did_open(&a.server, &run, &state.path, &state.uri, params.clone());
}
a.opened_gen = Some(run.generation);
}
@@ -939,40 +959,61 @@ impl LspManager {
out.finish(Vec::new())
}
pub async fn references(&self, doc: DocId, pos: Pos, include_declaration: bool) -> IdeResult<Vec<Location>> {
/// References of the symbol at `pos`. With `project_wide`, files outside
/// the servers' analysis scope that mention the name are opened for the
/// search (see [`scope`]); without, only what the servers analyse counts
/// (cheap, for bulk scans over many symbols).
pub async fn references(
&self,
doc: DocId,
pos: Pos,
include_declaration: bool,
project_wide: bool,
cancel: CancellationToken,
) -> IdeResult<References> {
let (snap, targets) = self.doc_targets(doc, "find references", |c| c.has("referencesProvider")).await?;
let requests = targets.iter().map(|t| {
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "includeDeclaration": include_declaration });
let (snap, cancel) = (&snap, &cancel);
async move {
(
t,
self.call::<_, Option<Vec<lsp::Location>>>(
t,
"textDocument/references",
params,
None,
LONG_TIMEOUT,
)
.await,
)
let query = || async move {
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "includeDeclaration": include_declaration });
let locs: Option<Vec<lsp::Location>> =
self.call(t, "textDocument/references", params, Some(cancel), LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
Ok(locs.unwrap_or_default().iter().filter_map(|l| conv.location(l)).collect::<Vec<Location>>())
};
let files =
|v: &Vec<Location>| v.iter().filter(|l| l.uri.is_none()).map(|l| l.path.to_path_buf()).collect();
let result = if project_wide {
self.widened(snap, t, pos, cancel, query, files).await
} else {
query().await.map(|first| {
let empty = first.is_empty();
scope::Widened::only(first, empty, &t.server)
})
};
(t, result)
}
});
let mut out = Outcome::new();
for (t, r) in join_all(requests).await {
match r {
Ok(locs) => {
let conv = self.conv(t.enc());
let locs: Vec<Location> =
locs.unwrap_or_default().iter().filter_map(|l| conv.location(l)).collect();
Ok(w) => {
let acc = out.value.get_or_insert_with(References::default);
let locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
out.value.get_or_insert_with(Vec::new).extend(locs);
acc.locations.extend(locs);
acc.incomplete = acc.incomplete.or(w.incomplete);
}
Err(e) => out.fail(e),
}
}
let mut v = out.finish(Vec::new())?;
convert::dedup_locations(&mut v);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut v = out.finish(References::default())?;
convert::dedup_locations(&mut v.locations);
Ok(v)
}
@@ -1202,13 +1243,29 @@ impl LspManager {
})
}
/// Renames across the project: like [`Self::references`], files outside the
/// server's analysis scope that mention the name are opened for the request.
pub async fn rename(&self, doc: DocId, pos: Pos, new_name: String) -> IdeResult<WorkspaceEdit> {
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
let t = &targets[0];
let mut params = snap.pos_params(t, pos);
params["newName"] = json!(new_name);
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
let query = || async {
let mut params = snap.pos_params(t, pos);
params["newName"] = json!(new_name);
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
};
let files = |e: &WorkspaceEdit| {
e.files
.iter()
.filter_map(|f| match f {
ide_core::FileEdit::Edit { path, .. } => Some(path.to_path_buf()),
_ => None,
})
.collect()
};
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
// The second edit covers the first: its files stay analysed.
Ok(w.second.unwrap_or(w.first))
}
// ---- file operations (`workspace/willRenameFiles`, `workspace/didRenameFiles`) ----
@@ -1257,16 +1314,17 @@ impl LspManager {
/// Some servers (tsserver) only answer for files of a loaded project: when
/// `t` has no document open, one moved file of its languages is opened for the request.
fn open_for_file_op(&self, t: &Target, moves: &[(PathBuf, PathBuf, bool)]) -> Option<lsp::Uri> {
fn open_for_file_op(&self, t: &Target, moves: &[(PathBuf, PathBuf, bool)]) -> scope::TransientFiles<'_> {
let mut opened = scope::TransientFiles::empty(self, t);
if !t.caps().open_close {
return None;
return opened;
}
let docs = self.docs.lock();
let busy = docs
.values()
.any(|d| d.servers.iter().any(|a| a.server.id == t.server.id && a.opened_gen == Some(t.run.generation)));
let busy =
self.docs.lock().values().any(|d| {
d.servers.iter().any(|a| a.server.id == t.server.id && a.opened_gen == Some(t.run.generation))
});
if busy {
return None;
return opened;
}
let languages = t.server.languages();
let candidate =
@@ -1281,14 +1339,10 @@ impl LspManager {
continue;
}
let Ok(text) = std::fs::read_to_string(&file) else { continue };
let uri = uri::path_to_uri(&file);
let params =
json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } });
if t.run.peer.notify("textDocument/didOpen", params).is_ok() {
return Some(uri);
}
opened.hold(&file, &language, &text);
break;
}
None
opened
}
/// Asks the servers for the edits that keep references intact when files or
@@ -1314,9 +1368,7 @@ impl LspManager {
let opened = self.open_for_file_op(&t, &moves);
let r: IdeResult<Option<lsp::WorkspaceEdit>> =
self.call(&t, "workspace/willRenameFiles", params, Some(&cancel), LONG_TIMEOUT).await;
if let Some(uri) = opened {
let _ = t.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }));
}
drop(opened);
match r {
Ok(Some(edit)) => out.edit.files.extend(convert::workspace_edit(&self.conv(t.enc()), edit).files),
Ok(None) => {}
@@ -1513,32 +1565,46 @@ impl LspManager {
let items: Option<Vec<lsp::CallHierarchyItem>> =
self.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
let mut out = Vec::new();
for item in items {
let params = json!({ "item": item });
match direction {
HierarchyDirection::Incoming => {
let calls: Option<Vec<lsp::CallHierarchyIncomingCall>> =
self.call(t, "callHierarchy/incomingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
for c in calls.unwrap_or_default() {
let (path, _) = uri_target(c.from.uri.as_str());
let ranges = c.from_ranges.iter().map(|r| conv.range(&path, *r)).collect();
out.extend(convert::call_item(&conv, &c.from, ranges));
let query = || async {
let mut out = Vec::new();
for item in &items {
let params = json!({ "item": item });
match direction {
HierarchyDirection::Incoming => {
let calls: Option<Vec<lsp::CallHierarchyIncomingCall>> =
self.call(t, "callHierarchy/incomingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
for c in calls.unwrap_or_default() {
let (path, _) = uri_target(c.from.uri.as_str());
let ranges = c.from_ranges.iter().map(|r| conv.range(&path, *r)).collect();
out.extend(convert::call_item(&conv, &c.from, ranges));
}
}
}
HierarchyDirection::Outgoing => {
let calls: Option<Vec<lsp::CallHierarchyOutgoingCall>> =
self.call(t, "callHierarchy/outgoingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
let (src, _) = uri_target(item.uri.as_str());
for c in calls.unwrap_or_default() {
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
out.extend(convert::call_item(&conv, &c.to, ranges));
HierarchyDirection::Outgoing => {
let calls: Option<Vec<lsp::CallHierarchyOutgoingCall>> =
self.call(t, "callHierarchy/outgoingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
let (src, _) = uri_target(item.uri.as_str());
for c in calls.unwrap_or_default() {
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
out.extend(convert::call_item(&conv, &c.to, ranges));
}
}
}
}
}
Ok(out)
};
let out = match direction {
// Callers are references: they may sit in files outside the server's scope.
HierarchyDirection::Incoming => {
let files = |v: &Vec<HierarchyItem>| {
v.iter().filter(|i| i.uri.is_none()).map(|i| i.path.to_path_buf()).collect()
};
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
w.second.unwrap_or(w.first)
}
HierarchyDirection::Outgoing => query().await?,
};
self.note_virtual(&t.server, out.iter().map(|i| i.uri.as_deref()));
Ok(out)
}
@@ -1752,6 +1818,15 @@ impl LspManager {
return;
};
let peer = run.peer.clone();
// A server we connected to without starting it (an open Godot editor) is not
// ours to shut down: only the connection closes.
if peer.pid().is_none() && server.effective_config().connect.is_some() {
peer.kill();
server.end_stop(run.generation);
self.clear_server_state(server);
server.set_status(&self.sink, ide_core::event::ServerStatus::Stopped, None);
return;
}
let graceful = async {
peer.request::<_, Value>("shutdown", (), None).await.ok();
peer.notify("exit", ()).ok();
+248
Переглянути файл
@@ -0,0 +1,248 @@
//! Reference searches beyond a server's analysis scope.
//!
//! Servers answer `textDocument/references` (and rename, incoming calls) from
//! the files they analyse: their configured scope (Pyright's `include`, a
//! `tsconfig.json`, a compilation database) plus the open documents. Usages in
//! other project files are silently missing. So, as a word index would, the
//! project files of the server's languages that contain the symbol's name as a
//! whole word (found through the host's [`CandidateFn`]) and that the first
//! answer did not cover are opened on the server for a second request, then
//! closed again. Diagnostics the server publishes for them are dropped.
use crate::server::{Running, Server};
use crate::types::ReferencesIncomplete;
use crate::{DocSnap, LspManager, Target};
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Pos};
use lsp_types as lsp;
use serde_json::json;
use std::collections::HashSet;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
/// Files opened for one search at most.
pub const MAX_CANDIDATES: usize = 300;
/// Larger files (generated code, bundles) are not opened.
const MAX_CANDIDATE_BYTES: u64 = 1 << 20;
/// How long a search that found nothing waits for a server to finish indexing.
const INDEX_WAIT: Duration = Duration::from_secs(10);
/// Project files that may mention a symbol.
#[derive(Clone, Debug)]
pub struct CandidateQuery {
/// Matched as a whole word, case-sensitively.
pub word: String,
/// Only files under this directory (the server's workspace root).
pub root: PathBuf,
/// Only files of these languages.
pub languages: Vec<LanguageId>,
pub limit: usize,
}
#[derive(Clone, Debug, Default)]
pub struct CandidateFiles {
pub files: Vec<PathBuf>,
/// More files matched than `limit`.
pub limit_hit: bool,
}
/// Finds [`CandidateFiles`] (honouring the project's ignore rules); runs on a
/// blocking thread and should stop early when cancelled.
pub type CandidateFn = dyn Fn(&CandidateQuery, &CancellationToken) -> CandidateFiles + Send + Sync;
/// A reference-based answer and, when files were opened for it, the second one.
pub(crate) struct Widened<R> {
pub first: R,
pub second: Option<R>,
pub incomplete: Option<ReferencesIncomplete>,
}
impl<R> Widened<R> {
/// An answer from the server's analysis scope alone; `empty`: it found nothing.
pub fn only(first: R, empty: bool, server: &Server) -> Self {
let incomplete = (empty && server.is_busy()).then_some(ReferencesIncomplete::Indexing);
Self { first, second: None, incomplete }
}
}
/// The name a search is about: the word at `pos` (a PHP `$` sigil dropped).
fn search_word(snap: &DocSnap, pos: Pos) -> Option<String> {
let r = snap.text.word_range_at(pos)?;
let text = snap.text.as_str();
let word = text.get(snap.text.byte_offset(r.start)..snap.text.byte_offset(r.end))?.trim_start_matches('$');
(!word.is_empty() && !word.chars().all(|c| c.is_ascii_digit())).then(|| word.to_owned())
}
impl LspManager {
/// Finds the project files a references search may open (see the module docs).
pub fn set_candidates_hook(&self, hook: Box<CandidateFn>) {
*self.candidates_hook.write() = Some(Arc::from(hook));
}
async fn candidates(&self, t: &Target, word: String, cancel: &CancellationToken) -> Option<CandidateFiles> {
let hook = self.candidates_hook.read().clone()?;
let query = CandidateQuery {
word,
root: t.server.root.clone(),
languages: t.server.languages(),
limit: MAX_CANDIDATES,
};
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || hook(&query, &cancel)).await.ok()
}
/// Runs `query` on `t`; then again with the project files that mention the
/// symbol at `pos` and are not in `covered(first)` opened on the server.
/// A first answer that is empty while the server indexes is retried once
/// indexing ends.
pub(crate) async fn widened<R, F, Fut>(
&self,
snap: &DocSnap,
t: &Target,
pos: Pos,
cancel: &CancellationToken,
query: F,
covered: impl Fn(&R) -> Vec<PathBuf>,
) -> IdeResult<Widened<R>>
where
F: Fn() -> Fut,
Fut: Future<Output = IdeResult<R>>,
{
let busy = t.server.is_busy();
let word = search_word(snap, pos).filter(|_| t.caps().open_close);
let candidates = async {
match word {
Some(w) => self.candidates(t, w, cancel).await,
None => None,
}
};
let (first, candidates) = futures::join!(query(), candidates);
let mut first = first?;
if busy && covered(&first).is_empty() && t.server.wait_idle(INDEX_WAIT, cancel).await {
first = query().await?;
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Servers report analysis progress often; only "nothing found" while it lasts is suspect.
let mut incomplete =
(t.server.is_busy() && covered(&first).is_empty()).then_some(ReferencesIncomplete::Indexing);
let Some(candidates) = candidates else { return Ok(Widened { first, second: None, incomplete }) };
if candidates.limit_hit {
incomplete = incomplete.or(Some(ReferencesIncomplete::TooManyFiles));
}
let known: HashSet<PathBuf> = covered(&first).into_iter().chain([snap.path.clone()]).collect();
let files: Vec<PathBuf> = candidates.files.into_iter().filter(|f| !known.contains(f)).collect();
if files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
let opened = self.open_transient(t, files, cancel).await;
if opened.files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
tracing::debug!("{}: opened {} more files for a references search", t.server.name, opened.files.len());
let second = query().await;
drop(opened);
match second {
Ok(second) => {
if !covered(&second).is_empty() && incomplete == Some(ReferencesIncomplete::Indexing) {
incomplete = None;
}
Ok(Widened { first, second: Some(second), incomplete })
}
Err(e) if cancel.is_cancelled() => Err(e),
Err(e) => {
tracing::debug!("{}: widened references search: {}", t.server.name, e.message);
Ok(Widened { first, second: None, incomplete })
}
}
}
/// Opens `files` on `t` (read from disk) unless the user has them open;
/// they are closed when the returned guard drops.
async fn open_transient(&self, t: &Target, files: Vec<PathBuf>, cancel: &CancellationToken) -> TransientFiles<'_> {
let read = {
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
files
.into_iter()
.take_while(|_| !cancel.is_cancelled())
.filter(|f| std::fs::metadata(f).is_ok_and(|m| m.is_file() && m.len() <= MAX_CANDIDATE_BYTES))
.filter_map(|f| std::fs::read_to_string(&f).ok().map(|text| (f, text)))
.collect::<Vec<_>>()
})
.await
.unwrap_or_default()
};
let mut guard = TransientFiles { mgr: self, server: t.server.clone(), run: t.run.clone(), files: Vec::new() };
if cancel.is_cancelled() {
return guard;
}
let docs = self.docs.lock();
for (path, text) in read {
if docs.values().any(|d| d.path == path) {
continue;
}
let uri = crate::uri::path_to_uri(&path);
if t.server.hold_transient(&path, t.run.generation) {
let language = self.languages.detect(&path, text.lines().next());
let params = json!({
"textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text }
});
if let Err(e) = t.run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", t.server.name);
}
}
guard.files.push((path, uri));
}
guard
}
}
/// Files opened by [`LspManager::open_transient`]; closed on drop.
pub(crate) struct TransientFiles<'a> {
mgr: &'a LspManager,
server: Arc<Server>,
run: Running,
pub files: Vec<(PathBuf, lsp::Uri)>,
}
impl TransientFiles<'_> {
/// Opens one file outside a references search (a file operation needs a loaded project).
pub(crate) fn hold(&mut self, path: &Path, language: &LanguageId, text: &str) {
let _docs = self.mgr.docs.lock();
let uri = crate::uri::path_to_uri(path);
if self.server.hold_transient(path, self.run.generation) {
let params =
json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } });
if let Err(e) = self.run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", self.server.name);
}
}
self.files.push((path.to_owned(), uri));
}
}
impl<'a> TransientFiles<'a> {
pub(crate) fn empty(mgr: &'a LspManager, t: &Target) -> Self {
Self { mgr, server: t.server.clone(), run: t.run.clone(), files: Vec::new() }
}
}
impl Drop for TransientFiles<'_> {
fn drop(&mut self) {
if self.files.is_empty() {
return;
}
// Under the documents lock, so a user `didOpen` of the same file can't interleave.
let _docs = self.mgr.docs.lock();
for (path, uri) in self.files.drain(..) {
if self.server.release_transient(&path, self.run.generation)
&& let Err(e) = self.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", self.server.name);
}
}
}
}
+233 -14
Переглянути файл
@@ -2,7 +2,7 @@
use crate::caps::ServerCaps;
use ide_core::event::ServerStatus;
use ide_core::{IdeEvent, LanguageId, ServerId, SharedSink, TaskId};
use ide_core::{CancellationToken, IdeEvent, LanguageId, ServerId, SharedSink, TaskId};
use ide_jsonrpc::Peer;
use ide_language::LanguageServerConfig;
use lsp_types as lsp;
@@ -13,9 +13,13 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Notify, watch};
const CRASH_WINDOW: Duration = Duration::from_secs(180);
/// An instance that stayed up this long ran fine: earlier crashes no longer count.
const STABLE_UPTIME: Duration = Duration::from_secs(180);
const MAX_RESTARTS: usize = 3;
const STDERR_LINES: usize = 50;
/// Diagnostics a server publishes for a transiently opened file shortly after
/// its `didClose` (analysis that was already running) are dropped too.
const TRANSIENT_GRACE: Duration = Duration::from_secs(3);
/// A live, initialized instance.
#[derive(Clone)]
@@ -48,6 +52,17 @@ struct State {
conn: Conn,
}
/// A file opened on the server by the client itself (not by the user) for the
/// duration of a request, e.g. to widen a references search.
struct Transient {
/// Requests holding the file open.
holders: usize,
generation: u64,
/// The user opened the file meanwhile: its `didOpen` replaced ours.
taken: bool,
closed_at: Option<Instant>,
}
pub struct Progress {
pub task: TaskId,
pub title: String,
@@ -64,9 +79,14 @@ pub struct Server {
effective: Mutex<Option<LanguageServerConfig>>,
languages: Mutex<Vec<LanguageId>>,
state: Mutex<State>,
/// Fired when the instance being started is abandoned (stop / restart while starting).
start_cancel: Mutex<CancellationToken>,
phase: watch::Sender<Phase>,
status: Mutex<(ServerStatus, Option<String>)>,
crashes: Mutex<VecDeque<Instant>>,
/// Consecutive crashes of short-lived instances.
crashes: Mutex<usize>,
/// When the current instance was launched.
started: Mutex<Option<Instant>>,
stderr: Mutex<VecDeque<String>>,
pub progress: Mutex<HashMap<String, Progress>>,
diagnostics: Mutex<HashMap<PathBuf, Vec<lsp::Diagnostic>>>,
@@ -74,6 +94,9 @@ pub struct Server {
published: Mutex<HashMap<PathBuf, Instant>>,
/// Woken on every `publishDiagnostics` (Inspect Code waits on it).
pub published_notify: Notify,
/// Woken when the last `$/progress` task ends.
idle_notify: Notify,
transient: Mutex<HashMap<PathBuf, Transient>>,
}
impl Server {
@@ -86,14 +109,18 @@ impl Server {
effective: Mutex::new(None),
languages: Mutex::new(vec![language]),
state: Mutex::new(State { generation: 0, conn: Conn::Idle }),
start_cancel: Mutex::new(CancellationToken::new()),
phase: watch::channel(Phase::Down).0,
status: Mutex::new((ServerStatus::Stopped, None)),
crashes: Mutex::new(VecDeque::new()),
crashes: Mutex::new(0),
started: Mutex::new(None),
stderr: Mutex::new(VecDeque::new()),
progress: Mutex::new(HashMap::new()),
diagnostics: Mutex::new(HashMap::new()),
published: Mutex::new(HashMap::new()),
published_notify: Notify::new(),
idle_notify: Notify::new(),
transient: Mutex::new(HashMap::new()),
}
}
@@ -127,6 +154,8 @@ impl Server {
}
st.generation += 1;
st.conn = Conn::Starting;
*self.start_cancel.lock() = CancellationToken::new();
*self.started.lock() = Some(Instant::now());
self.phase.send_replace(Phase::Starting);
Some(st.generation)
}
@@ -191,6 +220,7 @@ impl Server {
}
Conn::Starting => {
st.generation += 1; // invalidates the in-flight start
self.start_cancel.lock().cancel();
self.phase.send_replace(Phase::Down);
None
}
@@ -201,6 +231,11 @@ impl Server {
}
}
/// Cancelled when the current start is abandoned.
pub fn start_token(&self) -> CancellationToken {
self.start_cancel.lock().clone()
}
pub fn end_stop(&self, generation: u64) {
let mut st = self.state.lock();
if st.generation == generation && matches!(st.conn, Conn::Stopping) {
@@ -237,21 +272,22 @@ impl Server {
}
}
/// Records a crash; returns the backoff before restarting, or `None` when
/// the restart budget for the window is exhausted.
/// Records a crash; returns the backoff before restarting, or `None` once
/// [`MAX_RESTARTS`] instances in a row died before running [`STABLE_UPTIME`]
/// (a server that crashes on every start, however slowly, is not restarted forever).
pub fn record_crash(&self) -> Option<Duration> {
let uptime = self.started.lock().map(|t| t.elapsed()).unwrap_or_default();
let mut crashes = self.crashes.lock();
let now = Instant::now();
crashes.push_back(now);
while crashes.front().is_some_and(|t| now.duration_since(*t) > CRASH_WINDOW) {
crashes.pop_front();
if uptime >= STABLE_UPTIME {
*crashes = 0;
}
let n = crashes.len();
*crashes += 1;
let n = *crashes;
(n <= MAX_RESTARTS).then(|| Duration::from_millis(500) * (1 << (n - 1)) as u32)
}
pub fn reset_for_restart(&self) {
self.crashes.lock().clear();
*self.crashes.lock() = 0;
let mut st = self.state.lock();
if matches!(st.conn, Conn::Missing | Conn::Failed) {
st.conn = Conn::Idle;
@@ -288,6 +324,95 @@ impl Server {
self.set_status(sink, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, None);
}
/// Whether the server reports work in progress (indexing, analysis).
pub fn is_busy(&self) -> bool {
!self.progress.lock().is_empty()
}
/// Called after a `$/progress` task ended.
pub fn progress_ended(&self) {
if !self.is_busy() {
self.idle_notify.notify_waiters();
}
}
/// Waits until no `$/progress` task is active; false on timeout or cancellation.
pub async fn wait_idle(&self, timeout: Duration, cancel: &CancellationToken) -> bool {
let deadline = tokio::time::Instant::now() + timeout;
loop {
let notified = self.idle_notify.notified();
if !self.is_busy() || self.running().is_none() {
return !self.is_busy();
}
tokio::select! {
() = notified => {}
() = tokio::time::sleep_until(deadline) => return !self.is_busy(),
() = cancel.cancelled() => return false,
}
}
}
// ---- transiently opened files ----
/// Registers a holder of the transient file `path` on instance `generation`;
/// true when the caller must send `didOpen` (first holder).
pub fn hold_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
map.retain(|_, t| t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE));
let t =
map.entry(path.to_owned()).or_insert(Transient { holders: 0, generation, taken: false, closed_at: None });
if t.holders == 0 || t.generation != generation {
*t = Transient { holders: 1, generation, taken: false, closed_at: None };
return true;
}
t.holders += 1;
false
}
/// Drops a holder of `path`; true when the caller must send `didClose`
/// (last holder, same instance, and the user did not open the file meanwhile).
pub fn release_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
let Some(t) = map.get_mut(path) else { return false };
if t.holders == 0 {
return false;
}
t.holders -= 1;
if t.holders > 0 {
return false;
}
let close = !t.taken && t.generation == generation;
if close {
t.closed_at = Some(Instant::now());
} else {
map.remove(path);
}
close
}
/// The user opens `path` on instance `generation`: true when a transient
/// copy is open there and must be closed before the user's `didOpen`.
pub fn take_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
let Some(t) = map.get_mut(path) else { return false };
let open = t.holders > 0 && !t.taken && t.generation == generation;
if t.holders > 0 {
t.taken = true;
} else {
map.remove(path);
}
open
}
/// Whether diagnostics published for `path` belong to a transient copy
/// and must not reach the Problems view.
pub fn suppresses_diagnostics(&self, path: &Path) -> bool {
self.transient
.lock()
.get(path)
.is_some_and(|t| !t.taken && (t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE)))
}
// ---- bookkeeping ----
pub fn push_stderr(&self, line: String) {
@@ -300,8 +425,8 @@ impl Server {
pub fn stderr_tail(&self, n: usize) -> String {
let buf = self.stderr.lock();
let skip = buf.len().saturating_sub(n);
buf.iter().skip(skip).cloned().collect::<Vec<_>>().join("\n")
let lines: Vec<&str> = buf.iter().map(String::as_str).collect();
crash_excerpt(&lines, n)
}
pub fn take_progress(&self) -> Vec<(TaskId, String)> {
@@ -341,3 +466,97 @@ impl Server {
self.diagnostics.lock().drain().map(|(p, _)| p).collect()
}
}
/// The last `n` stderr lines, led by the exception headline: Node.js / Python /
/// JVM crashes print the error first and a stack after it, so a plain tail
/// shows frames without saying what went wrong.
pub(crate) fn crash_excerpt(lines: &[&str], n: usize) -> String {
const MAX_LINES: usize = 12;
let start = lines.len().saturating_sub(n);
let excerpt: Vec<&str> = match lines.iter().rposition(|l| is_error_headline(l)) {
Some(i) if i >= start => lines[start..].to_vec(),
Some(i) if lines.len() - i <= MAX_LINES => lines[i..].to_vec(),
Some(i) => [lines[i], "…"].into_iter().chain(lines[start..].iter().copied()).collect(),
None => lines[start..].to_vec(),
};
excerpt.join("\n")
}
fn is_error_headline(line: &str) -> bool {
let l = line.trim_start();
let head = l.split(':').next().unwrap_or_default();
let named = (head.ends_with("Error") || head.ends_with("Exception")) && !head.contains(' ') && head.len() < l.len();
named || l.starts_with("Exception in thread") || l.starts_with("thread '") && l.contains("panicked")
}
#[cfg(test)]
mod tests {
use super::*;
fn server() -> Server {
let cfg: LanguageServerConfig = toml::from_str("name = \"s\"\ncommand = \"s\"").unwrap();
Server::new(cfg, PathBuf::from("/p"), LanguageId::new("vue"))
}
#[test]
fn crashes_of_short_lived_instances_exhaust_the_budget_whatever_the_spacing() {
let s = server();
for _ in 0..MAX_RESTARTS {
// Even crashes spread minutes apart count while each instance dies young.
*s.started.lock() = Some(Instant::now());
assert!(s.record_crash().is_some());
}
*s.started.lock() = Some(Instant::now());
assert_eq!(s.record_crash(), None);
s.reset_for_restart();
assert!(s.record_crash().is_some());
}
#[test]
fn a_stable_run_resets_the_budget() {
let s = server();
for _ in 0..MAX_RESTARTS {
assert!(s.record_crash().is_some());
}
*s.started.lock() = Instant::now().checked_sub(STABLE_UPTIME);
assert_eq!(s.record_crash(), Some(Duration::from_millis(500)));
}
#[test]
fn crash_excerpt_keeps_the_exception_line() {
// Node.js 24 crash of vue-language-server (issue #25), verbatim shape.
let node = [
"C:\\tools\\node_modules\\@vue\\language-server\\lib\\server.js:40",
" projectInfoPromise = sendTsServerRequest('_vue:' + ts.server.protocol.CommandTypes.ProjectInfo, {",
" ^",
"",
"TypeError: Cannot read properties of undefined (reading 'protocol')",
" at Object.getLanguageService (C:\\tools\\node_modules\\@vue\\language-server\\lib\\server.js:40:86)",
" at Immediate.<anonymous> (C:\\tools\\node_modules\\@volar\\language-server\\lib\\features\\languageFeatures.js:744:62)",
" at process.processImmediate (node:internal/timers:504:21)",
"",
"Node.js v24.12.0",
];
let out = crash_excerpt(&node, 5);
assert!(out.starts_with("TypeError: Cannot read properties of undefined (reading 'protocol')"), "{out}");
assert!(out.ends_with("Node.js v24.12.0"));
let python = [
"Traceback (most recent call last):",
" File \"x.py\", line 1",
"ModuleNotFoundError: No module named 'jedi'",
];
assert_eq!(crash_excerpt(&python, 5), python.join("\n"));
let mut long_stack = vec!["Exception in thread \"main\" java.lang.IllegalStateException: boom"];
long_stack.extend(std::iter::repeat_n("\tat a.b.C.d(C.java:1)", 30));
let out = crash_excerpt(&long_stack, 5);
assert!(out.starts_with("Exception in thread \"main\""), "{out}");
assert_eq!(out.lines().count(), 7);
let plain = ["starting", "listening", "bye"];
assert_eq!(crash_excerpt(&plain, 2), "listening\nbye");
// "Error" in prose is not a headline.
assert_eq!(crash_excerpt(&["No Error here: fine", "a", "b"], 2), "a\nb");
}
}
+188
Переглянути файл
@@ -0,0 +1,188 @@
//! LSP over TCP, for servers living inside another program (the Godot editor's
//! GDScript server). Mirrors `ide-dap`'s `tcp` transport: connect to the
//! configured address when something listens there, else start the configured
//! command (`${port}` → a free port, `${root}` → the workspace root) and connect
//! once it accepts. The framing and session are the same as over stdio.
use crate::launch::LaunchError;
use ide_core::CancellationToken;
use ide_jsonrpc::{Handler, Peer};
use ide_language::LanguageServerConfig;
use parking_lot::Mutex;
use std::collections::VecDeque;
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
pub(crate) const PORT_PLACEHOLDER: &str = "${port}";
pub(crate) const ROOT_PLACEHOLDER: &str = "${root}";
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
/// A headless Godot editor imports the project before it listens.
const START_TIMEOUT: Duration = Duration::from_secs(120);
const POLL: Duration = Duration::from_millis(200);
const TAIL_LINES: usize = 20;
/// `${port}` / `${root}` substituted in every argument.
pub(crate) fn substitute_args(args: &[String], port: Option<u16>, root: &Path) -> Vec<String> {
let root = root.to_string_lossy();
args.iter()
.map(|a| {
let a = a.replace(ROOT_PLACEHOLDER, &root);
match port {
Some(p) => a.replace(PORT_PLACEHOLDER, &p.to_string()),
None => a,
}
})
.collect()
}
pub(crate) fn resolve_addr(addr: &str) -> Result<SocketAddr, LaunchError> {
addr.to_socket_addrs()
.ok()
.and_then(|mut a| a.next())
.ok_or_else(|| LaunchError::Config(format!("invalid language server address `{addr}`")))
}
/// A connection to `addr` if something accepts there right now.
pub(crate) fn probe(addr: &SocketAddr) -> Option<TcpStream> {
let stream = TcpStream::connect_timeout(addr, PROBE_TIMEOUT).ok()?;
let _ = stream.set_nodelay(true);
Some(stream)
}
/// A port that was free a moment ago on the loopback interface.
pub(crate) fn free_port() -> std::io::Result<u16> {
Ok(std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port())
}
fn into_tokio(stream: TcpStream) -> std::io::Result<tokio::net::TcpStream> {
stream.set_nonblocking(true)?;
tokio::net::TcpStream::from_std(stream)
}
/// Connects to the server of `config` (whose `connect` is set), starting `binary` when
/// nothing listens yet. Blocking; must run on a thread inside a Tokio runtime.
#[allow(clippy::too_many_arguments)]
pub(crate) fn connect_or_start(
config: &LanguageServerConfig,
addr: &str,
binary: Option<&Path>,
env: &[(String, String)],
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
let addr = resolve_addr(addr)?;
if let Some(stream) = probe(&addr) {
tracing::info!("{}: connected to the server running at {addr}", config.name);
let (r, w) = into_tokio(stream).map_err(|e| LaunchError::Failed(e.to_string()))?.into_split();
return Ok(Peer::connect(r, w, handler));
}
let binary = binary.ok_or(LaunchError::Missing)?;
let port = config
.args
.iter()
.any(|a| a.contains(PORT_PLACEHOLDER))
.then(free_port)
.transpose()
.map_err(|e| LaunchError::Failed(format!("no free port: {e}")))?;
let target = port.map_or(addr, |p| SocketAddr::from(([127, 0, 0, 1], p)));
let args = substitute_args(&config.args, port, root);
let mut cmd = tokio::process::Command::new(binary);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(&args)
.current_dir(root)
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
let mut child =
cmd.spawn().map_err(|e| LaunchError::Failed(format!("failed to start {}: {e}", binary.display())))?;
tracing::info!("{}: started {} {}, waiting for {target}", config.name, binary.display(), args.join(" "));
let tail: Arc<Mutex<VecDeque<String>>> = Arc::default();
let on_line: Arc<dyn Fn(String) + Send + Sync> = {
let tail = tail.clone();
Arc::new(move |line: String| {
{
let mut t = tail.lock();
if t.len() == TAIL_LINES {
t.pop_front();
}
t.push_back(line.clone());
}
on_stderr(line);
})
};
if let Some(out) = child.stdout.take() {
pump_lines(out, on_line.clone());
}
if let Some(err) = child.stderr.take() {
pump_lines(err, on_line);
}
let failed = |message: String| {
let tail: Vec<String> = tail.lock().iter().cloned().collect();
LaunchError::Failed(if tail.is_empty() { message } else { format!("{message}:\n{}", tail.join("\n")) })
};
let deadline = Instant::now() + START_TIMEOUT;
loop {
if cancel.is_cancelled() {
let _ = child.start_kill();
return Err(LaunchError::Failed(format!("{}: start cancelled", config.name)));
}
if let Some(stream) = probe(&target) {
let (r, w) = into_tokio(stream).map_err(|e| LaunchError::Failed(e.to_string()))?.into_split();
return Ok(Peer::connect_with_child(r, w, handler, child));
}
if let Ok(Some(status)) = child.try_wait() {
return Err(failed(format!("{} exited before accepting connections on {target} ({status})", config.name)));
}
if Instant::now() >= deadline {
let _ = child.start_kill();
return Err(failed(format!(
"{} did not accept connections on {target} within {}s",
config.name,
START_TIMEOUT.as_secs()
)));
}
std::thread::sleep(POLL);
}
}
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(stream: R, on_line: Arc<dyn Fn(String) + Send + Sync>) {
tokio::spawn(async move {
let mut lines = BufReader::new(stream).lines();
while let Ok(Some(line)) = lines.next_line().await {
on_line(line);
}
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn placeholders_are_substituted() {
let args: Vec<String> =
["--path", "${root}", "--lsp-port", "${port}", "--x=${port}"].iter().map(|s| s.to_string()).collect();
assert_eq!(
substitute_args(&args, Some(6010), Path::new("/p/game")),
["--path", "/p/game", "--lsp-port", "6010", "--x=6010"]
);
assert_eq!(substitute_args(&args, None, Path::new("/p"))[3], "${port}");
}
#[test]
fn addresses_resolve() {
assert_eq!(resolve_addr("127.0.0.1:6005").unwrap().port(), 6005);
assert!(matches!(resolve_addr("nonsense"), Err(LaunchError::Config(_))));
}
}
+93
Переглянути файл
@@ -0,0 +1,93 @@
//! Vue Language Server (Volar 3) runs in "hybrid mode": TypeScript work goes to
//! tsserver with `@vue/typescript-plugin`, through the client. It sends
//! `tsserver/request` `[id, command, args]` and waits for `tsserver/response`
//! `[id, body]`; the client forwards the command to vtsls, whose tsserver has the
//! plugin loaded (`typescript.tsserverRequest`). Without an answer the server
//! waits forever, so every request is answered — `null` when vtsls can't.
use crate::LspManager;
use crate::server::Server;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
/// The server that hosts tsserver for the bridge.
pub(crate) const TSSERVER_HOST: &str = "vtsls";
const HOST_START_WAIT: Duration = Duration::from_secs(60);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
/// `[id, command, args]` items of a `tsserver/request` notification
/// (vscode-jsonrpc wraps the single array argument: `[[id, command, args]]`).
pub(crate) fn parse_requests(params: &Value) -> Vec<(Value, String, Value)> {
let one = |v: &Value| {
let a = v.as_array()?;
let command = a.get(1)?.as_str()?.to_owned();
Some((a.first()?.clone(), command, a.get(2).cloned().unwrap_or(Value::Null)))
};
match params.as_array() {
Some(items) if items.first().is_some_and(Value::is_array) => items.iter().filter_map(one).collect(),
Some(_) => one(params).into_iter().collect(),
None => Vec::new(),
}
}
impl LspManager {
/// Answers `tsserver/request`s of `from` (instance `generation`) via [`TSSERVER_HOST`].
pub(crate) fn forward_tsserver_requests(&self, from: Arc<Server>, generation: u64, params: Value) {
let Some(me) = self.me.upgrade() else { return };
for (id, command, args) in parse_requests(&params) {
let me = me.clone();
let from = from.clone();
self.runtime.spawn(async move {
let body = me.tsserver_request(&from, &command, args).await.unwrap_or(Value::Null);
if let Some(run) = from.running_gen(generation)
&& let Err(e) = run.peer.notify("tsserver/response", json!([[id, body]]))
{
tracing::debug!("{}: tsserver/response: {e}", from.name);
}
});
}
}
async fn tsserver_request(&self, from: &Server, command: &str, args: Value) -> Option<Value> {
let host = self
.servers
.lock()
.iter()
.filter(|s| s.name == TSSERVER_HOST)
.min_by_key(|s| s.root != from.root)
.cloned()?;
let run = host.wait_ready(HOST_START_WAIT).await?;
let params = json!({
"command": "typescript.tsserverRequest",
"arguments": [command, args, { "isAsync": true, "lowPriority": true }],
});
let request = run.peer.request::<_, Value>("workspace/executeCommand", params, None);
match tokio::time::timeout(REQUEST_TIMEOUT, request).await {
Ok(Ok(result)) => result.get("body").cloned(),
Ok(Err(e)) => {
tracing::debug!("{TSSERVER_HOST}: {command}: {e}");
None
}
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_wrapped_and_bare_requests() {
let wrapped = json!([[1, "_vue:projectInfo", { "file": "/p/App.vue" }]]);
assert_eq!(
parse_requests(&wrapped),
vec![(json!(1), "_vue:projectInfo".to_owned(), json!({ "file": "/p/App.vue" }))]
);
let bare = json!([2, "_vue:getComponentNames", ["/p/App.vue"]]);
assert_eq!(parse_requests(&bare), vec![(json!(2), "_vue:getComponentNames".to_owned(), json!(["/p/App.vue"]))]);
assert!(parse_requests(&json!({ "id": 1 })).is_empty());
assert!(parse_requests(&json!([[3]])).is_empty());
}
}
+17
Переглянути файл
@@ -322,3 +322,20 @@ pub struct FileRenameEdits {
/// Servers that failed; their references are not updated.
pub errors: Vec<String>,
}
/// Why a references search may have missed usages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ReferencesIncomplete {
/// A language server was still indexing.
Indexing,
/// More project files mention the name than were checked.
TooManyFiles,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct References {
pub locations: Vec<Location>,
pub incomplete: Option<ReferencesIncomplete>,
}
+384 -4
Переглянути файл
@@ -27,9 +27,13 @@ struct MockState {
/// uri → text as reconstructed by the mock from didOpen/didChange.
docs: Mutex<HashMap<String, String>>,
responses: Mutex<HashMap<String, Value>>,
/// Computes a response from the request and the open documents (before `responses`).
responder: Mutex<Option<Responder>>,
peer: Mutex<Option<Peer>>,
}
type Responder = Arc<dyn Fn(&MockState, &str, &Value) -> Option<Value> + Send + Sync>;
impl MockState {
fn notified(&self, method: &str) -> Vec<Value> {
self.notifications.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
@@ -111,11 +115,17 @@ impl Handler for MockHandler {
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
let s = &self.0;
s.requests.lock().push((method.to_owned(), params));
s.requests.lock().push((method.to_owned(), params.clone()));
match method {
"initialize" => Ok(json!({ "capabilities": s.caps.lock().clone(), "serverInfo": { "name": "mock" } })),
"shutdown" => Ok(Value::Null),
_ => Ok(s.responses.lock().get(method).cloned().unwrap_or(Value::Null)),
_ => {
let responder = s.responder.lock().clone();
if let Some(v) = responder.and_then(|f| f(s, method, &params)) {
return Ok(v);
}
Ok(s.responses.lock().get(method).cloned().unwrap_or(Value::Null))
}
}
}
}
@@ -192,6 +202,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
root_markers: vec!["mock.toml".into()],
initialization_options: Some(toml::Value::Table(toml::toml! { flag = true nested = { deep = 1 } })),
install_hint: Some(format!("install {name}")),
connect: None,
fallback: false,
launch_error: None,
}
@@ -800,7 +811,7 @@ async fn navigation_rename_format_and_decorations() {
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
s.respond("textDocument/references", json!([{ "uri": uri, "range": r(0,3,0,6) }, { "uri": uri, "range": r(1,0,1,3) }, { "uri": uri, "range": r(1,0,1,3) }]));
let refs = h.mgr.references(doc, Pos::new(1, 1), true).await.unwrap();
let refs = h.mgr.references(doc, Pos::new(1, 1), true, true, Default::default()).await.unwrap().locations;
assert_eq!(refs.len(), 2);
assert_eq!(s.requested("textDocument/references")[0]["context"]["includeDeclaration"], true);
@@ -986,7 +997,7 @@ async fn virtual_locations_and_text_document_content() {
"textDocument/references",
json!([{ "uri": uri_of(&path), "range": r(0, 4, 0, 9) }, { "uri": lib, "range": r(2, 4, 2, 9) }]),
);
let refs = h.mgr.references(doc, Pos::new(0, 5), true).await.unwrap();
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap().locations;
assert_eq!(refs.iter().map(|l| l.uri.is_some()).collect::<Vec<_>>(), vec![false, true]);
s.respond(
"textDocument/prepareTypeHierarchy",
@@ -1266,3 +1277,372 @@ async fn inspect_reports_files_without_a_server() {
let results = inspect(&h, "plaintext", vec![txt]).await;
assert!(matches!(results[0].1, ide_lsp::FileInspection::NoServer));
}
#[tokio::test(flavor = "multi_thread")]
async fn css_family_configuration_returns_default_objects() {
for language in ["css", "scss", "less"] {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_path_buf();
let registry = Arc::new(LanguageRegistry::load(None).unwrap());
let launcher = Arc::new(MockLauncher::default());
let state = launcher.state("vscode-css-language-server");
*state.caps.lock() = incremental_caps();
let mgr = LspManager::with_launcher(root.clone(), registry, Arc::new(|_| {}), launcher);
let path = root.join(format!("a.{language}"));
let text = ".qa { colr: red; }";
std::fs::write(&path, text).unwrap();
mgr.did_open(DocId::next(), &path, &LanguageId::new(language), 1, text);
eventually(|| !state.notified("textDocument/didOpen").is_empty()).await;
let reply: Value = state
.peer()
.request(
"workspace/configuration",
json!({ "items": [
{ "section": "css", "scopeUri": uri_of(&path) },
{ "section": "scss", "scopeUri": uri_of(&path) },
{ "section": "less", "scopeUri": uri_of(&path) },
{ "section": "unknown" }
] }),
None,
)
.await
.unwrap();
assert_eq!(reply, json!([{}, {}, {}, null]), "{language}");
assert_eq!(state.requested("initialize")[0]["initializationOptions"]["provideFormatter"], true);
}
}
// ------------------------------------------------------------------ references beyond the analysis scope
const WORD: &str = "target";
/// Locations of [`WORD`] in `text` (ASCII, so UTF-16 columns are byte offsets).
fn occurrences(uri: &str, text: &str) -> Vec<Value> {
let mut out = Vec::new();
for (line, l) in text.lines().enumerate() {
for (col, _) in l.match_indices(WORD) {
let end = col + WORD.len();
out.push(json!({ "uri": uri, "range": {
"start": { "line": line, "character": col }, "end": { "line": line, "character": end } } }));
}
}
out
}
/// A server that only analyses its open documents (minus `blind` URIs), like
/// Pyright for files outside its `include`.
fn open_files_only(blind: Vec<String>) -> Responder {
Arc::new(move |s, method, _| {
let docs: Vec<(String, String)> =
s.docs.lock().iter().filter(|(u, _)| !blind.contains(u)).map(|(u, t)| (u.clone(), t.clone())).collect();
let locs = || docs.iter().flat_map(|(u, t)| occurrences(u, t));
match method {
"textDocument/references" => Some(Value::Array(locs().collect())),
"textDocument/rename" => {
let mut changes = serde_json::Map::new();
for loc in locs() {
let edits = changes.entry(loc["uri"].as_str().unwrap()).or_insert_with(|| json!([]));
edits.as_array_mut().unwrap().push(json!({ "range": loc["range"], "newText": "renamed" }));
}
Some(json!({ "changes": changes }))
}
_ => None,
}
})
}
/// Candidate files: those directly under the root that contain the word; records the queries.
fn grep_candidates(h: &Harness) -> Arc<Mutex<Vec<ide_lsp::CandidateQuery>>> {
let seen = Arc::new(Mutex::new(Vec::new()));
let log = seen.clone();
h.mgr.set_candidates_hook(Box::new(move |q, _| {
log.lock().push(q.clone());
let mut files: Vec<PathBuf> = std::fs::read_dir(&q.root)
.unwrap()
.flatten()
.map(|e| e.path())
.filter(|p| std::fs::read_to_string(p).is_ok_and(|t| t.contains(&q.word)))
.collect();
files.sort();
ide_lsp::CandidateFiles { files, limit_hit: false }
}));
seen
}
fn uris(params: &[Value]) -> Vec<String> {
params.iter().map(|p| p["textDocument"]["uri"].as_str().unwrap().to_owned()).collect()
}
fn diagnostics_for(h: &Harness, path: &Path) -> usize {
h.events.lock().iter().filter(|e| matches!(e, IdeEvent::Diagnostics { path: p, .. } if p == path)).count()
}
fn scope_harness() -> (Harness, Arc<MockState>) {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
*s.responder.lock() = Some(open_files_only(vec![]));
(h, s)
}
#[tokio::test(flavor = "multi_thread")]
async fn references_open_unopened_files_that_mention_the_name() {
let (h, s) = scope_harness();
let seen = grep_candidates(&h);
let b = h.root.join("b.mk");
let c = h.root.join("c.mk");
std::fs::write(&b, "call target\n").unwrap();
std::fs::write(&c, "nothing here\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
let (_, d) = h.open("d.mk", "use target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 2).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
let mut paths: Vec<PathBuf> = refs.locations.iter().map(|l| l.path.to_path_buf()).collect();
paths.sort();
assert_eq!(paths, vec![a.clone(), b.clone(), d.clone()]);
assert_eq!(refs.incomplete, None);
let q = seen.lock()[0].clone();
assert_eq!((q.word.as_str(), q.root.as_path(), q.limit), (WORD, h.root.as_path(), ide_lsp::MAX_CANDIDATES));
assert_eq!(q.languages, vec![h.lang.clone()]);
// Only the unopened candidate was opened (from disk), then closed again.
let opens = s.notified("textDocument/didOpen");
let temp: Vec<&Value> = opens.iter().filter(|p| p["textDocument"]["uri"] == uri_of(&b)).collect();
assert_eq!(temp.len(), 1);
assert_eq!(temp[0]["textDocument"]["version"], 0);
assert_eq!(temp[0]["textDocument"]["text"], "call target\n");
assert!(!uris(&opens).contains(&uri_of(&c)));
assert_eq!(uris(&opens).iter().filter(|u| **u == uri_of(&d)).count(), 1);
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
assert_eq!(s.requested("textDocument/references").len(), 2);
assert_eq!(s.docs.lock().len(), 2);
// When every candidate file is already in the answer, no second request is made.
std::fs::remove_file(&b).unwrap();
h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(s.requested("textDocument/references").len(), 3);
// Without project_wide only the server's scope counts: no project search.
std::fs::write(&b, "call target\n").unwrap();
let refs = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
assert_eq!(seen.lock().len(), 2);
}
#[tokio::test(flavor = "multi_thread")]
async fn references_never_reopen_or_close_the_users_files() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let (doc, _) = h.open("a.mk", "def target\n");
// Open, mentions the name, but the server does not report it.
let (_, d) = h.open("d.mk", "use target\n");
*s.responder.lock() = Some(open_files_only(vec![uri_of(&d)]));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 2).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 1);
assert_eq!(uris(&s.notified("textDocument/didOpen")).iter().filter(|u| **u == uri_of(&d)).count(), 1);
assert!(s.notified("textDocument/didClose").is_empty());
assert_eq!(s.requested("textDocument/references").len(), 1);
assert!(s.docs.lock().contains_key(&uri_of(&d)));
}
#[tokio::test(flavor = "multi_thread")]
async fn references_report_a_capped_candidate_search() {
let (h, s) = scope_harness();
h.mgr.set_candidates_hook(Box::new(|q, _| ide_lsp::CandidateFiles {
files: vec![q.root.join("b.mk")],
limit_hit: true,
}));
std::fs::write(h.root.join("b.mk"), "target\n").unwrap();
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::TooManyFiles));
}
#[tokio::test(flavor = "multi_thread")]
async fn cancelling_a_references_search_stops_the_candidate_search_and_closes_files() {
let (h, s) = scope_harness();
h.mgr.set_candidates_hook(Box::new(|_, cancel| {
while !cancel.is_cancelled() {
std::thread::sleep(Duration::from_millis(5));
}
ide_lsp::CandidateFiles::default()
}));
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let cancel = ide_core::CancellationToken::new();
let later = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(100)).await;
later.cancel();
});
let err = h.mgr.references(doc, Pos::new(0, 5), true, true, cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
// Cancelled while the server answers with a file opened for the search.
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
grep_candidates(&h);
let slow = uri_of(&b);
let inner = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().contains_key(&slow) {
std::thread::sleep(Duration::from_millis(600));
}
inner(s, method, params)
}));
let cancel = ide_core::CancellationToken::new();
let later = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
later.cancel();
});
let started = std::time::Instant::now();
let err = h.mgr.references(doc, Pos::new(0, 5), true, true, cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
assert!(started.elapsed() < Duration::from_millis(550));
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn diagnostics_of_files_opened_for_a_search_stay_out_of_problems() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
let diag = json!([{ "range": {"start":{"line":0,"character":0},"end":{"line":0,"character":1}}, "message": "e" }]);
let inner = open_files_only(vec![]);
let (temp, user, d) = (uri_of(&b), uri_of(&a), diag.clone());
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().contains_key(&temp) {
for uri in [&temp, &user] {
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri, "diagnostics": d })).unwrap();
}
}
inner(s, method, params)
}));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
// Published right after the didClose (analysis still running): dropped too.
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&b), "diagnostics": diag })).unwrap();
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&a), "diagnostics": [] })).unwrap();
eventually(|| diagnostics_for(&h, &a) == 2).await;
assert_eq!(diagnostics_for(&h, &b), 0);
}
#[tokio::test(flavor = "multi_thread")]
async fn opening_a_file_during_a_search_takes_it_over() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, _) = h.open("a.mk", "def target\n");
let slow = uri_of(&b);
let inner = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().get(&slow).is_some_and(|t| t.starts_with("call")) {
std::thread::sleep(Duration::from_millis(400));
}
inner(s, method, params)
}));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let mgr = h.mgr.clone();
let search = tokio::spawn(async move { mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await });
eventually(|| s.docs.lock().contains_key(&uri_of(&b))).await;
let user_doc = DocId::next();
h.mgr.did_open(user_doc, &b, &h.lang, 7, "edited target\n");
search.await.unwrap().unwrap();
// The temporary copy was closed before the user's didOpen, and the user's stays open.
let events: Vec<(String, Value)> = s
.notifications
.lock()
.iter()
.filter(|(m, p)| m.starts_with("textDocument/did") && p["textDocument"]["uri"] == uri_of(&b))
.map(|(m, p)| (m.clone(), p["textDocument"]["version"].clone()))
.collect();
assert_eq!(
events,
vec![
("textDocument/didOpen".to_owned(), json!(0)),
("textDocument/didClose".to_owned(), Value::Null),
("textDocument/didOpen".to_owned(), json!(7)),
]
);
assert_eq!(s.docs.lock().get(&uri_of(&b)).map(String::as_str), Some("edited target\n"));
// Its diagnostics are the user's again.
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&b), "diagnostics": [] })).unwrap();
eventually(|| diagnostics_for(&h, &b) == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn an_empty_answer_while_indexing_is_retried_when_indexing_ends() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
let (doc, path) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let peer = s.peer();
peer.notify("$/progress", json!({ "token": "idx", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
let (state, uri) = (s.clone(), uri_of(&path));
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
state.respond("textDocument/references", Value::Array(occurrences(&uri, "def target\n")));
peer.notify("$/progress", json!({ "token": "idx", "value": { "kind": "end" } })).unwrap();
});
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 1);
assert_eq!(refs.incomplete, None);
assert_eq!(s.requested("textDocument/references").len(), 2);
// While the server works, results are taken as they are; finding nothing is flagged.
s.peer()
.notify("$/progress", json!({ "token": "again", "value": { "kind": "begin", "title": "Indexing" } }))
.unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!((refs.locations.len(), refs.incomplete), (1, None));
s.respond("textDocument/references", json!([]));
let refs = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 0);
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::Indexing));
}
#[tokio::test(flavor = "multi_thread")]
async fn rename_edits_files_outside_the_analysis_scope() {
let (h, s) = scope_harness();
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let edit = h.mgr.rename(doc, Pos::new(0, 5), "renamed".into()).await.unwrap();
let mut paths: Vec<PathBuf> = edit
.files
.iter()
.map(|f| match f {
FileEdit::Edit { path, .. } => path.to_path_buf(),
_ => panic!("unexpected {f:?}"),
})
.collect();
paths.sort();
assert_eq!(paths, vec![a, b.clone()]);
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
}
+75
Переглянути файл
@@ -71,6 +71,7 @@ async fn missing_binary_is_reported_with_install_hint() {
root_markers: vec![],
initialization_options: None,
install_hint: Some("npm i -g nope-ls".into()),
connect: None,
fallback: false,
launch_error: None,
};
@@ -198,6 +199,7 @@ async fn typescript_language_server_end_to_end() {
root_markers: vec!["tsconfig.json".into()],
initialization_options: None,
install_hint: None,
connect: None,
fallback: false,
launch_error: None,
};
@@ -227,3 +229,76 @@ async fn typescript_language_server_end_to_end() {
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
const APP_VUE: &str = "<script setup lang=\"ts\">\nconst count: number = 1\n</script>\n\n<template>\n <div>{{ count }}</div>\n</template>\n";
fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Value>) -> LanguageServerConfig {
LanguageServerConfig {
name: name.into(),
command: tools.join("node_modules/.bin").join(bin).to_string_lossy().into_owned(),
args: vec!["--stdio".into()],
env: Default::default(),
root_markers: vec!["package.json".into()],
initialization_options: init.map(|v| toml::Value::try_from(v).unwrap()),
install_hint: None,
connect: None,
fallback: false,
launch_error: None,
}
}
/// Vue Language Server 3 in hybrid mode: its `tsserver/request`s go through the
/// client to vtsls with `@vue/typescript-plugin` (issue #25). Set
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vue/language-server typescript@"<7" @vtsls/language-server`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vue/language-server and @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
async fn vue_hybrid_mode_end_to_end() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
std::fs::write(root.join("tsconfig.json"), "{\"compilerOptions\":{\"strict\":true},\"include\":[\"src/**/*\"]}")
.unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
let file = root.join("src/App.vue");
std::fs::write(&file, APP_VUE).unwrap();
let plugin = serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [{
"name": "@vue/typescript-plugin",
"location": tools.join("node_modules/@vue/language-server").to_string_lossy(),
"languages": ["vue"],
"configNamespace": "typescript",
"enableForWorkspaceTypeScriptVersions": true,
}] } } });
for with_vtsls in [false, true] {
let mut vue = lang("vue", "vue", npm_server(&tools, "vue-language-server", "vue-language-server", None));
if with_vtsls {
vue.language_servers.push(npm_server(&tools, "vtsls", "vtsls", Some(plugin.clone())));
}
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![vue]));
let doc = DocId::next();
mgr.did_open(doc, &file, &LanguageId::new("vue"), 1, APP_VUE);
// `count` in `{{ count }}`.
let pos = Pos::new(5, 12);
if with_vtsls {
let hover = retry("hover", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.hover(doc, pos, Default::default()).await.ok().flatten() }
})
.await;
assert!(hover.contents.value.contains("count: number"), "{}", hover.contents.value);
}
retry("vue-language-server ready", Duration::from_secs(30), || {
let s = last_status(&events, "vue-language-server");
async move { matches!(s, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
// Every request of vue-language-server waits for a tsserver answer (the
// project info); without vtsls it is `null` and the server falls back.
let symbols = tokio::time::timeout(Duration::from_secs(20), mgr.document_symbols(doc)).await;
assert!(matches!(symbols, Ok(Ok(_))), "vue-language-server did not answer: {symbols:?}");
let crashed = matches!(last_status(&events, "vue-language-server"), Some((ServerStatus::Crashed, _)));
assert!(!crashed, "{:?}", last_status(&events, "vue-language-server"));
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
}
+243
Переглянути файл
@@ -0,0 +1,243 @@
//! Language servers reached over TCP (`connect`, the Godot editor's GDScript
//! server) against a mock LSP server on a local socket.
use ide_core::event::ServerStatus;
use ide_core::{CancellationToken, DocId, IdeEvent, LanguageId, Pos};
use ide_jsonrpc::{Handler, Peer};
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
#[cfg(unix)]
use ide_lsp::{LaunchError, Launcher};
use ide_lsp::{LspManager, ProcessLauncher};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
#[derive(Default)]
struct ServerLog {
requests: Mutex<Vec<String>>,
notifications: Mutex<Vec<String>>,
/// Server ends of the accepted connections.
peers: Mutex<Vec<Peer>>,
}
struct MockHandler(Arc<ServerLog>);
impl Handler for MockHandler {
fn on_notification(&self, method: &str, _params: Value) {
self.0.notifications.lock().push(method.to_owned());
}
fn on_request(&self, method: &str, _params: Value) -> Result<Value, (i64, String)> {
self.0.requests.lock().push(method.to_owned());
match method {
"initialize" => Ok(json!({
"capabilities": { "textDocumentSync": 1, "hoverProvider": true },
"serverInfo": { "name": "mock-godot" }
})),
"textDocument/hover" => Ok(json!({ "contents": { "kind": "markdown", "value": "**Node2D**" } })),
_ => Ok(Value::Null),
}
}
}
/// Accepts LSP connections on a local port, like the Godot editor on 6005.
async fn mock_server() -> (u16, Arc<ServerLog>, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(ServerLog::default());
let accept = {
let log = log.clone();
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let (r, w) = stream.into_split();
let peer = Peer::connect(r, w, Arc::new(MockHandler(log.clone())));
log.peers.lock().push(peer);
}
})
};
(port, log, accept)
}
fn godot_cfg(port: u16, command: &str) -> LanguageServerConfig {
toml::from_str(&format!(
"name = \"godot\"\ncommand = \"{command}\"\nconnect = \"127.0.0.1:{port}\"\nroot-markers = [\"project.godot\"]\ninstall-hint = \"Open the project in the Godot editor\""
))
.unwrap()
}
struct Harness {
_dir: tempfile::TempDir,
root: PathBuf,
mgr: Arc<LspManager>,
events: Arc<Mutex<Vec<IdeEvent>>>,
}
fn harness(server: LanguageServerConfig) -> Harness {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_path_buf();
std::fs::write(root.join("project.godot"), "config_version=5\n").unwrap();
let lang: LanguageConfig = toml::from_str("id = \"gdscript\"\nname = \"GDScript\"\nextensions = [\"gd\"]").unwrap();
let lang = LanguageConfig { language_servers: vec![server], ..lang };
let registry = Arc::new(LanguageRegistry::from_configs(vec![lang]));
let events = Arc::new(Mutex::new(Vec::new()));
let sink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let mgr = LspManager::with_launcher(root.clone(), registry, sink, Arc::new(ProcessLauncher));
Harness { _dir: dir, root, mgr, events }
}
impl Harness {
fn open(&self, name: &str, text: &str) -> DocId {
let path = self.root.join(name);
std::fs::write(&path, text).unwrap();
let doc = DocId::next();
self.mgr.did_open(doc, &path, &LanguageId::new("gdscript"), 1, text);
doc
}
fn statuses(&self) -> Vec<(ServerStatus, Option<String>)> {
self.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::LanguageServer { status, message, .. } => Some((*status, message.clone())),
_ => None,
})
.collect()
}
async fn wait_status(&self, status: ServerStatus, count: usize) {
eventually(|| self.statuses().iter().filter(|(s, _)| *s == status).count() >= count).await;
}
}
async fn eventually(mut f: impl FnMut() -> bool) {
for _ in 0..1000 {
if f() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("condition not reached in time");
}
#[tokio::test(flavor = "multi_thread")]
async fn connects_to_a_running_server_requests_and_reconnects() {
let (port, log, _accept) = mock_server().await;
let h = harness(godot_cfg(port, "openidea-no-such-godot"));
let doc = h.open("player.gd", "extends Node2D\n");
h.wait_status(ServerStatus::Ready, 1).await;
assert_eq!(log.requests.lock().first().map(String::as_str), Some("initialize"));
eventually(|| log.notifications.lock().iter().any(|m| m == "textDocument/didOpen")).await;
let hover = h.mgr.hover(doc, Pos::new(0, 9), CancellationToken::new()).await.unwrap().unwrap();
assert!(format!("{hover:?}").contains("Node2D"), "{hover:?}");
// Attached to a server it didn't start: no process id.
assert_eq!(h.mgr.servers()[0].pid, None);
// The editor drops the connection (closed or restarted): the client reconnects and reopens.
log.peers.lock().remove(0).kill();
h.wait_status(ServerStatus::Crashed, 1).await;
let (_, message) = h.statuses().into_iter().rfind(|(s, _)| *s == ServerStatus::Crashed).unwrap();
assert!(message.unwrap().contains(&format!("127.0.0.1:{port}")));
h.wait_status(ServerStatus::Ready, 2).await;
eventually(|| log.notifications.lock().iter().filter(|m| *m == "textDocument/didOpen").count() == 2).await;
assert_eq!(log.requests.lock().iter().filter(|m| *m == "initialize").count(), 2);
// Shutting down leaves a server it didn't start running: no `shutdown` / `exit`.
h.mgr.shutdown_all().await;
eventually(|| log.peers.lock().iter().all(Peer::is_closed)).await;
assert!(!log.requests.lock().iter().any(|m| m == "shutdown"));
assert!(!log.notifications.lock().iter().any(|m| m == "exit"));
}
#[tokio::test(flavor = "multi_thread")]
async fn nothing_listening_and_no_executable_reports_how_to_fix_it() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let h = harness(godot_cfg(port, "openidea-no-such-godot"));
h.open("player.gd", "extends Node\n");
h.wait_status(ServerStatus::Missing, 1).await;
let (_, message) = h.statuses().into_iter().rfind(|(s, _)| *s == ServerStatus::Missing).unwrap();
assert_eq!(message.as_deref(), Some("Open the project in the Godot editor"));
}
/// The command is started when nothing listens yet, the client waits until the
/// port accepts, and the started process belongs to the connection.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn starts_the_command_and_waits_until_it_listens() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let cfg = LanguageServerConfig { args: vec!["30".into()], ..godot_cfg(port, "sleep") };
let root = tempfile::tempdir().unwrap();
// The "server" (`sleep`) never listens itself; a listener comes up a moment later.
let log = Arc::new(ServerLog::default());
let server = {
let log = log.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(400)).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
let (stream, _) = listener.accept().await.unwrap();
let (r, w) = stream.into_split();
log.peers.lock().push(Peer::connect(r, w, Arc::new(MockHandler(log.clone()))));
})
};
let path = root.path().to_path_buf();
let peer = tokio::task::spawn_blocking(move || {
ProcessLauncher.launch(&cfg, &path, Arc::new(ide_jsonrpc::NoopHandler), Box::new(|_| {}))
})
.await
.unwrap()
.unwrap_or_else(|e| panic!("{e:?}"));
server.await.unwrap();
let pid = peer.pid().expect("owns the started process");
let init: Value = peer.request("initialize", json!({}), None).await.unwrap();
assert_eq!(init["serverInfo"]["name"], "mock-godot");
peer.kill();
peer.closed().await;
eventually(|| !process_alive(pid)).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_command_that_exits_without_listening_fails_and_cancel_stops_waiting() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let root = tempfile::tempdir().unwrap();
let path = root.path().to_path_buf();
let cfg = godot_cfg(port, "false");
let err = tokio::task::spawn_blocking(move || {
ProcessLauncher.launch(&cfg, &path, Arc::new(ide_jsonrpc::NoopHandler), Box::new(|_| {}))
})
.await
.unwrap()
.err()
.expect("fails");
assert!(matches!(&err, LaunchError::Failed(m) if m.contains("exited before accepting connections")), "{err:?}");
let cfg = LanguageServerConfig { args: vec!["30".into()], ..godot_cfg(port, "sleep") };
let path = root.path().to_path_buf();
let cancel = CancellationToken::new();
let token = cancel.clone();
let started = std::time::Instant::now();
let waiting = tokio::task::spawn_blocking(move || {
ProcessLauncher.launch_cancellable(&cfg, &path, Arc::new(ide_jsonrpc::NoopHandler), Box::new(|_| {}), &token)
});
tokio::time::sleep(Duration::from_millis(300)).await;
cancel.cancel();
let err = waiting.await.unwrap().err().expect("cancelled");
assert!(matches!(&err, LaunchError::Failed(m) if m.contains("cancelled")), "{err:?}");
assert!(started.elapsed() < Duration::from_secs(10));
}
#[cfg(unix)]
fn process_alive(pid: u32) -> bool {
std::process::Command::new("kill")
.args(["-0", &pid.to_string()])
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|s| s.success())
}
+76 -4
Переглянути файл
@@ -20,21 +20,27 @@ mod sandbox;
mod theme;
mod types;
pub use manifest::{API_VERSION, CommandDecl, Contributions, FileDecl, MANIFEST_FILE, Permission, PluginManifest};
pub use manifest::{
API_VERSION, CommandDecl, Contributions, FileDecl, MANIFEST_FILE, Permission, PluginManifest, ThemeDecl,
};
pub use sandbox::resolve_in_root;
pub use theme::{ThemeDef, ThemeKind};
pub use types::*;
use ide_core::{IdeError, IdeResult};
use ide_language::LanguageConfig;
use parking_lot::{Mutex, RwLock};
use parking_lot::{Condvar, Mutex, RwLock};
use runtime::{CallEffects, CallError, PluginEngine, Registrations, Runtime, RuntimeSetup};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
const STATE_FILE: &str = "state.json";
/// Top-level files copied with a package on install besides those the manifest references.
const LICENSE_FILES: &[&str] =
&["LICENSE", "LICENSE.md", "LICENSE.txt", "NOTICE", "NOTICE.md", "NOTICE.txt", "COPYING"];
/// Dev plugins live here, relative to a project root.
pub const DEV_PLUGINS_DIR: &str = ".openidea/plugins";
@@ -50,6 +56,10 @@ struct PersistedState {
struct ThemeRef {
plugin: String,
theme: String,
/// The theme's window frame colour as the UI resolved it (`#rrggbb[aa]`), so
/// new windows open in it before the plugin is loaded.
#[serde(default, skip_serializing_if = "Option::is_none")]
frame: Option<String>,
}
struct Meta {
@@ -93,6 +103,8 @@ pub struct PluginHost {
active_files: Arc<Mutex<HashMap<String, String>>>,
/// Serializes loading / unloading so concurrent windows can't race.
lifecycle: Mutex<()>,
/// Set once the first [`load_all`](Self::load_all) has finished.
initial_load: (Mutex<bool>, Condvar),
}
impl PluginHost {
@@ -112,6 +124,7 @@ impl PluginHost {
state: Mutex::new(state),
active_files: Arc::default(),
lifecycle: Mutex::new(()),
initial_load: (Mutex::new(false), Condvar::new()),
})
}
@@ -127,9 +140,24 @@ impl PluginHost {
self.load_dir(&dir, PluginSource::Installed, None);
}
}
let (done, cv) = &self.initial_load;
*done.lock() = true;
cv.notify_all();
self.emit(None, PluginEvent::CommandsChanged);
}
/// Waits (at most `timeout`) for the first [`load_all`](Self::load_all), so a
/// listing made at startup already holds the installed plugins and the
/// selected theme. Returns whether loading has finished.
pub fn wait_initial_load(&self, timeout: Duration) -> bool {
let (done, cv) = &self.initial_load;
let mut done = done.lock();
if !*done {
cv.wait_while_for(&mut done, |d| !*d, timeout);
}
*done
}
/// Loads new dev plugins from `<root>/.openidea/plugins/` and unloads vanished ones.
pub fn sync_project(&self, root: &Path) {
let _guard = self.lifecycle.lock();
@@ -249,6 +277,11 @@ impl PluginHost {
}
std::fs::copy(src.join(file), to)?;
}
for name in LICENSE_FILES {
if src.join(name).is_file() {
std::fs::copy(src.join(name), staging.join(name))?;
}
}
if target.exists() {
std::fs::remove_dir_all(&target)?;
}
@@ -343,13 +376,45 @@ impl PluginHost {
}
}
self.state.lock().theme =
selection.map(|(plugin, theme)| ThemeRef { plugin: plugin.into(), theme: theme.into() });
selection.map(|(plugin, theme)| ThemeRef { plugin: plugin.into(), theme: theme.into(), frame: None });
self.save_state();
let active = self.active_theme();
self.emit(None, PluginEvent::ThemeChanged { theme: active.clone() });
Ok(active)
}
/// Records the selected theme's resolved window frame colour (`#rgb`,
/// `#rrggbb` or `#rrggbbaa`); ignored without a selected theme.
pub fn set_theme_frame(&self, frame: Option<&str>) -> IdeResult<()> {
if let Some(f) = frame
&& !is_hex_color(f)
{
return Err(IdeError::invalid(format!("not a hex colour: {f:?}")));
}
let changed = match self.state.lock().theme.as_mut() {
Some(t) if t.frame.as_deref() != frame => {
t.frame = frame.map(str::to_owned);
true
}
_ => false,
};
if changed {
self.save_state();
}
Ok(())
}
/// Frame colour for a new window: the recorded one of the selected theme,
/// unless its plugin is disabled. Available before plugins are loaded.
pub fn startup_frame(&self) -> Option<String> {
let state = self.state.lock();
let t = state.theme.as_ref()?;
if state.disabled.contains(&t.plugin) {
return None;
}
t.frame.clone()
}
/// The selected plugin theme, when its plugin is enabled and running.
pub fn active_theme(&self) -> Option<ActiveTheme> {
let sel = self.state.lock().theme.clone()?;
@@ -566,6 +631,10 @@ impl Drop for PluginHost {
}
}
fn is_hex_color(s: &str) -> bool {
s.strip_prefix('#').is_some_and(|h| matches!(h.len(), 3 | 6 | 8) && h.bytes().all(|b| b.is_ascii_hexdigit()))
}
/// Plugin packages found in `dirs` (first occurrence of an id wins). Invalid
/// manifests are skipped; packages with missing files carry a `problem`.
pub fn scan_catalog(dirs: &[PathBuf]) -> Vec<CatalogPlugin> {
@@ -627,7 +696,10 @@ fn static_contributions(dir: &Path, m: &PluginManifest) -> Result<Registrations,
regs.add_language(cfg);
}
for f in &m.contributes.themes {
let theme = ThemeDef::parse(&read(&f.path)?).map_err(|e| format!("{}: {e}", f.path.display()))?;
let mut theme = ThemeDef::parse(&read(&f.path)?).map_err(|e| format!("{}: {e}", f.path.display()))?;
if let Some(scheme) = &f.editor_scheme {
theme.merge_editor_scheme(&read(scheme)?).map_err(|e| format!("{}: {e}", scheme.display()))?;
}
regs.add_theme(theme);
}
Ok(regs)
+25 -5
Переглянути файл
@@ -64,7 +64,7 @@ pub struct Contributions {
#[serde(default)]
pub languages: Vec<FileDecl>,
#[serde(default)]
pub themes: Vec<FileDecl>,
pub themes: Vec<ThemeDecl>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -83,6 +83,16 @@ pub struct FileDecl {
pub path: PathBuf,
}
/// A contributed theme: the UI theme file plus an optional editor colour scheme
/// whose tokens are merged over it (IntelliJ's `.theme.json` + `.icls`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ThemeDecl {
pub path: PathBuf,
#[serde(default)]
pub editor_scheme: Option<PathBuf>,
}
impl PluginManifest {
pub fn parse(src: &str) -> Result<Self, String> {
let manifest: Self = toml::from_str(src).map_err(|e| e.to_string())?;
@@ -123,8 +133,9 @@ impl PluginManifest {
return Err(format!("command {:?} has an empty title", c.id));
}
}
for f in self.contributes.languages.iter().chain(&self.contributes.themes) {
check_relative(&f.path, "contributes path")?;
let theme_files = self.contributes.themes.iter().flat_map(|t| std::iter::once(&t.path).chain(&t.editor_scheme));
for path in self.contributes.languages.iter().map(|f| &f.path).chain(theme_files) {
check_relative(path, "contributes path")?;
}
Ok(())
}
@@ -133,7 +144,10 @@ impl PluginManifest {
pub fn files(&self) -> Vec<&Path> {
let mut files: Vec<&Path> = self.wasm.iter().map(PathBuf::as_path).collect();
files.extend(self.contributes.languages.iter().map(|f| f.path.as_path()));
files.extend(self.contributes.themes.iter().map(|f| f.path.as_path()));
for t in &self.contributes.themes {
files.push(t.path.as_path());
files.extend(t.editor_scheme.as_deref());
}
files
}
@@ -202,6 +216,7 @@ mod tests {
[[contributes.themes]]
path = "themes/dark.json"
editor-scheme = "themes/dark.scheme.json"
"#;
#[test]
@@ -210,7 +225,10 @@ mod tests {
assert_eq!(m.id, "hello");
assert_eq!(m.permissions, vec![Permission::ProjectRead, Permission::EditorWrite]);
assert_eq!(m.contributes.commands[0].category.as_deref(), Some("Hello"));
assert_eq!(m.files(), vec![Path::new("dist/plugin.wasm"), Path::new("themes/dark.json")]);
assert_eq!(
m.files(),
vec![Path::new("dist/plugin.wasm"), Path::new("themes/dark.json"), Path::new("themes/dark.scheme.json")]
);
assert!(m.has(Permission::EditorWrite) && !m.has(Permission::EditorRead));
}
@@ -242,6 +260,8 @@ mod tests {
assert!(err(&base(dup, "ok", "0.1")).contains("duplicate command"));
let traversal = "[[contributes.languages]]\npath = \"a/../../x.toml\"";
assert!(err(&base(traversal, "ok", "0.1")).contains("relative path"));
let scheme_escape = "[[contributes.themes]]\npath = \"t.json\"\neditor-scheme = \"../s.json\"";
assert!(err(&base(scheme_escape, "ok", "0.1")).contains("relative path"));
assert!(err("id = \"ok\"\nname = \"N\"\nversion = \"1.0\"\nopenidea-api = \"0.1\"").contains("version"));
assert!(err("id = \"ok\"\nname = \" \"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"").contains("name"));
}
+94 -1
Переглянути файл
@@ -1,4 +1,5 @@
//! Theme contributions: design-token overrides applied as CSS variables on `:root`.
//! Theme and editor-scheme files are JSON that may contain `//` and `/* */` comments.
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -24,13 +25,28 @@ pub struct ThemeDef {
pub tokens: BTreeMap<String, String>,
}
/// `{"name"?, "tokens": {...}}`: an editor colour scheme merged over a theme.
#[derive(Deserialize)]
struct EditorScheme {
tokens: BTreeMap<String, String>,
}
impl ThemeDef {
pub fn parse(src: &str) -> Result<Self, String> {
let theme: Self = serde_json::from_str(src).map_err(|e| format!("invalid theme JSON: {e}"))?;
let theme: Self =
serde_json::from_str(&strip_json_comments(src)).map_err(|e| format!("invalid theme JSON: {e}"))?;
theme.validate()?;
Ok(theme)
}
/// Merges an editor colour scheme file over the theme's tokens (the scheme wins).
pub fn merge_editor_scheme(&mut self, src: &str) -> Result<(), String> {
let scheme: EditorScheme =
serde_json::from_str(&strip_json_comments(src)).map_err(|e| format!("invalid editor scheme JSON: {e}"))?;
self.tokens.extend(scheme.tokens);
self.validate()
}
pub fn validate(&self) -> Result<(), String> {
crate::manifest::validate_command_id(&self.id).map_err(|e| e.replace("command id", "theme id"))?;
if self.name.trim().is_empty() {
@@ -55,6 +71,53 @@ impl ThemeDef {
}
}
/// Blanks out `//` and `/* */` comments outside strings, keeping newlines so
/// parse errors still point at the right line.
fn strip_json_comments(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let mut chars = src.chars().peekable();
let (mut in_str, mut escaped) = (false, false);
while let Some(c) = chars.next() {
if in_str {
out.push(c);
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == '"' {
in_str = false;
}
continue;
}
match (c, chars.peek()) {
('/', Some('/')) => {
if chars.by_ref().any(|c| c == '\n') {
out.push('\n');
}
}
('/', Some('*')) => {
chars.next();
let mut prev = ' ';
for c in chars.by_ref() {
if c == '\n' {
out.push('\n');
}
if prev == '*' && c == '/' {
break;
}
prev = c;
}
out.push(' ');
}
_ => {
in_str = c == '"';
out.push(c);
}
}
}
out
}
/// Values are plain CSS values (colours, lengths, font stacks). Anything that
/// could break out of the declaration or fetch resources is rejected.
fn is_safe_value(v: &str) -> bool {
@@ -95,4 +158,34 @@ mod tests {
assert!(mk("--bg", " ").is_err());
assert!(ThemeDef::parse("{\"id\":\"x\"}").is_err());
}
#[test]
fn allows_comments_outside_strings() {
let src = r##"{
// line comment
"id": "c", "name": "C // not a comment", "kind": "dark",
/* block
comment */
"tokens": { "--bg-app": "#000" /* inline */, "--font-ui": "\"a/*b\", sans-serif" }
}"##;
let t = ThemeDef::parse(src).unwrap();
assert_eq!(t.name, "C // not a comment");
assert_eq!(t.tokens["--font-ui"], "\"a/*b\", sans-serif");
assert!(ThemeDef::parse("{\n // x\n \"id\": 1\n}").unwrap_err().contains("line 3"));
}
#[test]
fn merges_editor_scheme_over_theme() {
let mut t = ThemeDef::parse(
r##"{"id":"m","name":"M","kind":"dark","tokens":{"--bg-app":"#111","--syn-keyword":"#222"}}"##,
)
.unwrap();
t.merge_editor_scheme(r##"{"name":"M", /* editor */ "tokens":{"--syn-keyword":"#333","--caret":"#fff"}}"##)
.unwrap();
assert_eq!(t.tokens["--bg-app"], "#111");
assert_eq!(t.tokens["--syn-keyword"], "#333");
assert_eq!(t.tokens["--caret"], "#fff");
assert!(t.clone().merge_editor_scheme(r#"{"tokens":{"--caret":"url(x)"}}"#).is_err());
assert!(t.merge_editor_scheme(r#"{"name":"no tokens"}"#).is_err());
}
}
+95 -9
Переглянути файл
@@ -217,10 +217,11 @@ fn runtime_language_and_theme_registration() {
#[test]
fn contribution_only_plugins() {
let f = fixture(Limits::default());
let theme = f.host.install_from_dir(&sample("theme-solarized-dark")).unwrap();
let theme = f.host.install_from_dir(&sample("theme-solarized")).unwrap();
assert_eq!(theme.status, PluginStatus::Static);
assert!(!theme.has_code);
assert_eq!(theme.themes[0].id, "solarized-dark");
let ids: Vec<&str> = theme.themes.iter().map(|t| t.id.as_str()).collect();
assert_eq!(ids, ["solarized-light", "solarized-dark"]);
let lang = f.host.install_from_dir(&sample("language-toy")).unwrap();
assert_eq!(lang.status, PluginStatus::Static);
assert_eq!(lang.languages[0].id, "toy");
@@ -228,13 +229,14 @@ fn contribution_only_plugins() {
assert!(f.run("language-toy", "x", None).unwrap_err().contains("no code"));
f.take_events();
let active = f.host.set_theme(Some(("theme-solarized-dark", "solarized-dark"))).unwrap().unwrap();
let active = f.host.set_theme(Some(("theme-solarized", "solarized-dark"))).unwrap().unwrap();
assert_eq!(active.theme.tokens["--bg-app"], "#002b36");
assert_eq!(active.theme.tokens["--syn-string"], "#2aa198");
assert!(f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::ThemeChanged { theme: Some(_) })));
assert_eq!(f.host.list(None).active_theme, Some(active));
// Disabling the plugin withdraws its theme and language.
f.host.set_enabled("theme-solarized-dark", false).unwrap();
f.host.set_enabled("theme-solarized", false).unwrap();
assert!(f.host.active_theme().is_none());
assert!(f.take_events().iter().any(|(_, e)| *e == PluginEvent::ThemeChanged { theme: None }));
f.host.set_enabled("language-toy", false).unwrap();
@@ -242,16 +244,100 @@ fn contribution_only_plugins() {
assert_eq!(f.status("language-toy"), PluginStatus::Disabled);
}
#[test]
fn theme_template_installs_with_its_editor_scheme() {
let f = fixture(Limits::default());
let info = f.host.install_from_dir(&repo().join("templates/theme-plugin")).unwrap();
assert_eq!(info.status, PluginStatus::Static);
assert!(!info.has_code);
assert_eq!(info.themes[0].id, "harbor-night");
assert_eq!(info.themes[0].kind, ThemeKind::Dark);
// The scheme file is copied with the package and merged over the UI tokens.
assert!(f.plugins_dir.join("theme-harbor-night/themes/harbor-night.scheme.json").is_file());
let active = f.host.set_theme(Some(("theme-harbor-night", "harbor-night"))).unwrap().unwrap();
let tokens = &active.theme.tokens;
assert!(
tokens.contains_key("--bg-app") && tokens.contains_key("--syn-keyword") && tokens.contains_key("--ansi-red")
);
assert!(tokens.len() > 150);
}
#[test]
fn bundled_theme_plugins_install_with_their_licence() {
let f = fixture(Limits::default());
for (pkg, themes) in
[("theme-solarized", ["solarized-light", "solarized-dark"]), ("theme-one", ["one-light", "one-dark"])]
{
let info = f.host.install_from_dir(&sample(pkg)).unwrap();
assert_eq!(info.status, PluginStatus::Static, "{pkg}: {:?}", info.error);
assert!(info.authors.iter().any(|a| a.starts_with("bghtyu")));
let license = std::fs::read_to_string(f.plugins_dir.join(pkg).join("LICENSE")).unwrap();
assert!(license.contains("MIT License"));
for (theme, kind) in themes.iter().zip([ThemeKind::Light, ThemeKind::Dark]) {
let active = f.host.set_theme(Some((pkg, theme))).unwrap().unwrap();
assert_eq!(active.theme.kind, kind);
let tokens = &active.theme.tokens;
assert!(["--bg-frame", "--syn-keyword", "--ansi-red"].iter().all(|t| tokens.contains_key(*t)));
}
}
}
#[test]
fn theme_frame_follows_the_selection() {
let f = fixture(Limits::default());
f.host.install_from_dir(&sample("theme-one")).unwrap();
// Nothing to attach it to without a selected theme.
f.host.set_theme_frame(Some("#21252b")).unwrap();
assert_eq!(f.host.startup_frame(), None);
f.host.set_theme(Some(("theme-one", "one-dark"))).unwrap();
assert!(f.host.set_theme_frame(Some("hsl(220, 13%, 15%)")).is_err());
f.host.set_theme_frame(Some("#21252b")).unwrap();
assert_eq!(f.host.startup_frame().as_deref(), Some("#21252b"));
f.host.set_enabled("theme-one", false).unwrap();
assert_eq!(f.host.startup_frame(), None);
f.host.set_enabled("theme-one", true).unwrap();
assert_eq!(f.host.startup_frame().as_deref(), Some("#21252b"));
// A new selection drops the old theme's colour until the UI reports the new one.
f.host.set_theme(Some(("theme-one", "one-light"))).unwrap();
assert_eq!(f.host.startup_frame(), None);
f.host.set_theme_frame(Some("#eaeaeb")).unwrap();
f.host.set_theme(None).unwrap();
assert_eq!(f.host.startup_frame(), None);
}
#[test]
fn theme_with_broken_editor_scheme_fails_to_load() {
let f = fixture(Limits::default());
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("t")).unwrap();
std::fs::write(
dir.path().join("plugin.toml"),
"id = \"bad-scheme\"\nname = \"B\"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"\n\
[[contributes.themes]]\npath = \"t/a.json\"\neditor-scheme = \"t/a.scheme.json\"\n",
)
.unwrap();
std::fs::write(dir.path().join("t/a.json"), r##"{"id":"a","name":"A","kind":"light","tokens":{}}"##).unwrap();
std::fs::write(dir.path().join("t/a.scheme.json"), "{\n \"tokens\": { \"--caret\": \"url(x)\" }\n}").unwrap();
let info = f.host.install_from_dir(dir.path()).unwrap();
assert_eq!(info.status, PluginStatus::Failed);
assert!(info.error.unwrap_or_default().contains("a.scheme.json"));
}
#[test]
fn state_persists_across_restarts() {
let f = fixture(Limits::default());
f.host.install_from_dir(&sample("hello")).unwrap();
f.host.install_from_dir(&sample("theme-solarized-dark")).unwrap();
f.host.install_from_dir(&sample("theme-solarized")).unwrap();
f.host.set_enabled("hello", false).unwrap();
f.host.set_theme(Some(("theme-solarized-dark", "solarized-dark"))).unwrap();
f.host.set_theme(Some(("theme-solarized", "solarized-dark"))).unwrap();
f.host.set_theme_frame(Some("#073642")).unwrap();
let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap();
// Known before the plugins are loaded: new windows open in the theme's frame colour.
assert_eq!(again.startup_frame().as_deref(), Some("#073642"));
assert!(!again.wait_initial_load(Duration::from_millis(1)));
again.load_all();
assert!(again.wait_initial_load(Duration::ZERO));
let list = again.list(None);
let hello = list.plugins.iter().find(|p| p.id == "hello").unwrap();
assert!(!hello.enabled);
@@ -352,14 +438,14 @@ fn catalog_lists_sample_packages() {
let catalog = scan_catalog(&[repo().join("plugins"), tmp.path().to_path_buf()]);
let ids: Vec<&str> = catalog.iter().map(|c| c.id.as_str()).collect();
for id in ["hello", "theme-solarized-dark", "language-toy", "x"] {
for id in ["hello", "theme-solarized", "theme-one", "language-toy", "x"] {
assert!(ids.contains(&id), "{id} missing from {ids:?}");
}
let hello = catalog.iter().find(|c| c.id == "hello").unwrap();
assert!(hello.has_code && hello.problem.is_none() && hello.change_notes.is_some());
assert_eq!(hello.commands.len(), 2);
let theme = catalog.iter().find(|c| c.id == "theme-solarized-dark").unwrap();
assert_eq!((theme.theme_count, theme.has_code), (1, false));
let theme = catalog.iter().find(|c| c.id == "theme-solarized").unwrap();
assert_eq!((theme.theme_count, theme.has_code), (2, false));
let x = catalog.iter().find(|c| c.id == "x").unwrap();
assert!(x.problem.as_deref().unwrap().contains("plugin.wasm"));
}
+1
Переглянути файл
@@ -17,6 +17,7 @@ tokio.workspace = true
portable-pty.workspace = true
parking_lot.workspace = true
tracing.workspace = true
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
+19
Переглянути файл
@@ -19,6 +19,7 @@ pub(crate) fn detect(root: &Path) -> Vec<RunConfig> {
detect_python(root, &mut out);
detect_make(root, &mut out);
detect_just(root, &mut out);
detect_godot(root, &mut out);
let mut seen = HashSet::new();
out.retain(|c| seen.insert(c.id.clone()));
@@ -799,6 +800,24 @@ pub(crate) fn just_recipes(src: &str) -> Vec<String> {
recipes
}
// ---------------------------------------------------------------- godot
/// Godot projects (`project.godot`) at the root or one level down: "Godot Project"
/// runs the main scene (`godot --path .`), debuggable through the editor's adapter.
fn detect_godot(root: &Path, out: &mut Vec<RunConfig>) {
let dirs = std::iter::once(root.to_path_buf()).chain(subdirs(root));
for dir in dirs.filter(|d| d.join("project.godot").is_file()) {
let rel = relative(root, &dir);
let (id, name, cwd) = if rel.as_os_str().is_empty() {
("godot:project".to_owned(), "Godot Project".to_owned(), None)
} else {
let r = rel.to_string_lossy();
(format!("godot:project:{r}"), format!("Godot Project ({r})"), Some(rel.clone()))
};
out.push(config(id, name, "godot", "godot", &["--path", "."]).debug("godot").in_dir(cwd));
}
}
fn detect_just(root: &Path, out: &mut Vec<RunConfig>) {
let Some(path) = first_existing(root, &["justfile", "Justfile", ".justfile"]) else { return };
let Some(src) = read(&path) else { return };
+537
Переглянути файл
@@ -0,0 +1,537 @@
//! IDEA's "Shorten command line" for `java` launches: a classpath too long for
//! the platform's command-line limit (Windows `CreateProcessW`: 32767 chars,
//! `os error 206`) moves into an `@argfile` (JDK 9+) or a pathing jar whose
//! manifest `Class-Path` lists the entries (any JDK, the only option on JDK 8).
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// `CreateProcessW` takes at most 32767 chars including the NUL; leave slack for quoting.
pub const WINDOWS_LIMIT: usize = 32_000;
/// Linux caps one argument at 128 KiB (`MAX_ARG_STRLEN`); macOS the whole `ARG_MAX` (1 MiB, env included).
pub const UNIX_LIMIT: usize = 120_000;
/// How a long `java` command line is shortened (java-debug's `shortenCommandLine` values).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Shortening {
None,
/// A temporary jar whose manifest `Class-Path` lists the classpath.
JarManifest,
/// A temporary `@argfile` holding `-cp` (and `--module-path`), JDK 9+.
ArgFile,
}
impl Shortening {
pub fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::JarManifest => "jarmanifest",
Self::ArgFile => "argfile",
}
}
}
pub fn command_line_limit(windows: bool) -> usize {
if windows { WINDOWS_LIMIT } else { UNIX_LIMIT }
}
/// Length of the command line as the OS receives it (quotes and separators included).
pub fn command_line_length(program: &str, args: &[String]) -> usize {
std::iter::once(program).chain(args.iter().map(String::as_str)).map(|a| a.len() + 3).sum()
}
/// Whether the longest single argument or the whole line exceeds the platform limit.
fn too_long(program: &str, args: &[String], windows: bool) -> bool {
let limit = command_line_limit(windows);
command_line_length(program, args) > limit || (!windows && args.iter().any(|a| a.len() > limit))
}
/// IDEA's automatic choice: nothing when the line fits; else an `@argfile` on JDK 9+
/// when every path is ASCII (the launcher reads argfiles in the platform charset),
/// else a pathing jar (works on every JDK; manifest URLs are percent-encoded UTF-8).
pub fn choose(too_long: bool, java_major: Option<u32>, classpath: &str) -> Shortening {
if !too_long {
Shortening::None
} else if java_major.is_some_and(|v| v >= 9) && classpath.is_ascii() {
Shortening::ArgFile
} else {
Shortening::JarManifest
}
}
/// Room left for VM options and program arguments when only the paths are known.
const OTHER_ARGS_RESERVE: usize = 4_096;
/// The shortening a launcher that builds the command line itself (java-debug's
/// `shortenCommandLine`) should use for `java -cp <class_paths> [--module-path …] …`.
pub fn shortening_for(java: &Path, class_paths: &[String], module_paths: &[String], windows: bool) -> Shortening {
let sep = if windows { ";" } else { ":" };
let (cp, mp) = (class_paths.join(sep), module_paths.join(sep));
let len = java.as_os_str().len() + cp.len() + mp.len() + 64 + OTHER_ARGS_RESERVE;
let limit = command_line_limit(windows);
choose(len > limit || cp.len() > limit || mp.len() > limit, java_feature_version(java), &format!("{cp}{mp}"))
}
/// `JAVA_VERSION="21.0.3"` (or `"1.8.0_372"`) from a JDK's `release` file.
pub fn parse_release(release: &str) -> Option<u32> {
let line = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?;
let mut parts = line.trim().trim_matches('"').split(['.', '_', '-', '+']);
let first: u32 = parts.next()?.parse().ok()?;
if first == 1 { parts.next()?.parse().ok() } else { Some(first) }
}
/// Feature version of the JDK a `java` launcher belongs to (`<home>/bin/java`, or
/// JDK 8's `<home>/jre/bin/java`), following symlinks; `None` when unknown.
pub fn java_feature_version(java: &Path) -> Option<u32> {
let java = std::fs::canonicalize(java).unwrap_or_else(|_| java.to_path_buf());
java.ancestors()
.skip(2)
.take(2)
.find_map(|home| std::fs::read_to_string(home.join("release")).ok())
.and_then(|r| parse_release(&r))
}
/// `java`, `java.exe`, `javaw.exe`.
pub fn is_java_launcher(program: &Path) -> bool {
let name = crate::wrap::program_name(&program.to_string_lossy()).to_ascii_lowercase();
name == "java" || name == "javaw"
}
/// `java` options whose value is the next argument.
const WITH_VALUE: &[&str] = &[
"-cp",
"-classpath",
"--class-path",
"-p",
"--module-path",
"--upgrade-module-path",
"--add-modules",
"--add-opens",
"--add-exports",
"--add-reads",
"--patch-module",
"--limit-modules",
"--enable-native-access",
];
/// Indices of the `-cp` and `--module-path` values among the VM options (before the main class).
fn path_options(args: &[String]) -> (Option<usize>, Option<usize>) {
let (mut cp, mut mp) = (None, None);
let mut i = 0;
while i < args.len() {
let a = args[i].as_str();
if matches!(a, "-jar" | "-m" | "--module") || !a.starts_with('-') {
break;
}
if WITH_VALUE.contains(&a) {
if i + 1 < args.len() {
match a {
"-cp" | "-classpath" | "--class-path" => cp = Some(i + 1),
"-p" | "--module-path" => mp = Some(i + 1),
_ => {}
}
}
i += 2;
} else {
i += 1;
}
}
(cp, mp)
}
/// A shortened command line and the temporary file it refers to (delete it once the process exits).
#[derive(Debug)]
pub struct Shortened {
pub args: Vec<String>,
pub file: PathBuf,
pub how: Shortening,
}
/// Shortens `java [options] -cp <classpath> Main …` when it is too long for the platform:
/// `None` for other programs, lines that fit, or no classpath option.
pub fn shorten(
program: &Path,
args: &[String],
cwd: &Path,
windows: bool,
temp_dir: &Path,
) -> std::io::Result<Option<Shortened>> {
if !is_java_launcher(program) || !too_long(&program.to_string_lossy(), args, windows) {
return Ok(None);
}
let (cp, mp) = path_options(args);
let Some(cp) = cp else { return Ok(None) };
let how = choose(true, java_feature_version(program), &args[cp]);
std::fs::create_dir_all(temp_dir)?;
let mut out = args.to_vec();
let file = match how {
Shortening::ArgFile => {
let file = temp_file(temp_dir, "argfile");
let mut moved = vec![cp - 1, cp];
if let Some(mp) = mp {
moved.extend([mp - 1, mp]);
}
moved.sort_unstable();
let text = argfile_text(&moved.iter().map(|&i| args[i].clone()).collect::<Vec<_>>());
std::fs::write(&file, text)?;
for &i in moved.iter().rev() {
out.remove(i);
}
out.insert(moved[0], format!("@{}", file.display()));
file
}
_ => {
let file = temp_file(temp_dir, "jar");
let entries = classpath_entries(&args[cp], cwd, windows);
write_pathing_jar(&entries, &file)?;
out[cp] = file.to_string_lossy().into_owned();
file
}
};
Ok(Some(Shortened { args: out, file, how }))
}
/// Where launches put their pathing jars / argfiles.
pub fn default_temp_dir() -> PathBuf {
std::env::temp_dir().join("openidea-classpath")
}
fn temp_file(dir: &Path, ext: &str) -> PathBuf {
static NEXT: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
let n = NEXT.fetch_add(1, Ordering::Relaxed);
dir.join(format!("classpath-{}-{nanos}-{n}.{ext}", std::process::id()))
}
/// Argument file lines: every argument quoted, `\` and `"` escaped (the launcher's argfile syntax).
pub fn argfile_text(args: &[String]) -> String {
let mut out = String::new();
for a in args {
out.push('"');
for c in a.chars() {
if c == '\\' || c == '"' {
out.push('\\');
}
out.push(c);
}
out.push_str("\"\n");
}
out
}
/// Classpath entries as absolute paths: relative ones against `cwd`, `dir/*` expanded to its jars.
pub fn classpath_entries(classpath: &str, cwd: &Path, windows: bool) -> Vec<PathBuf> {
let mut out = Vec::new();
for e in classpath.split(if windows { ';' } else { ':' }).filter(|e| !e.is_empty()) {
let wildcard = e.strip_suffix("/*").or_else(|| e.strip_suffix("\\*"));
let path = cwd.join(wildcard.unwrap_or(e));
if wildcard.is_some() {
let mut jars: Vec<PathBuf> = std::fs::read_dir(&path)
.map(|rd| {
rd.flatten()
.map(|d| d.path())
.filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")))
.collect()
})
.unwrap_or_default();
jars.sort();
out.extend(jars);
} else {
out.push(path);
}
}
out
}
/// `file:` URL of a classpath entry: percent-encoded UTF-8, `/` separators, a trailing `/` on directories.
pub fn file_url(path: &str, dir: bool) -> String {
let mut p = path.replace('\\', "/");
if !p.starts_with('/') {
p.insert(0, '/'); // `C:/x` → `/C:/x`
} else if p.starts_with("//") {
p.insert_str(0, "//"); // UNC `//server/share` → `file:////server/share`, as `File.toURI` does
}
if dir && !p.ends_with('/') {
p.push('/');
}
let mut url = String::from("file:");
for b in p.bytes() {
if b.is_ascii_alphanumeric() || b"-._~/:".contains(&b) {
url.push(b as char);
} else {
url.push_str(&format!("%{b:02X}"));
}
}
url
}
/// `META-INF/MANIFEST.MF` listing `entries`, lines wrapped at 72 bytes (continuations start with a space).
pub fn manifest(entries: &[PathBuf]) -> String {
let urls: Vec<String> = entries.iter().map(|e| file_url(&e.to_string_lossy(), e.is_dir())).collect();
let mut out = String::from("Manifest-Version: 1.0\r\nCreated-By: OpenIDEA\r\n");
out.push_str(&wrap_header(&format!("Class-Path: {}", urls.join(" "))));
out.push_str("\r\n");
out
}
/// One manifest header in lines of at most 72 bytes; `line` is ASCII (URLs are percent-encoded).
fn wrap_header(line: &str) -> String {
let mut out = String::new();
let mut rest = line;
let mut width = 72;
while !rest.is_empty() {
let (head, tail) = rest.split_at(width.min(rest.len()));
if width == 71 {
out.push(' ');
}
out.push_str(head);
out.push_str("\r\n");
rest = tail;
width = 71;
}
out
}
/// A jar holding only a manifest whose `Class-Path` is `entries` (IDEA's "JAR manifest").
pub fn write_pathing_jar(entries: &[PathBuf], out: &Path) -> std::io::Result<()> {
let mut zip = zip::ZipWriter::new(std::fs::File::create(out)?);
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
zip.start_file("META-INF/MANIFEST.MF", opts).map_err(std::io::Error::other)?;
zip.write_all(manifest(entries).as_bytes())?;
zip.finish().map_err(std::io::Error::other)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn strings(a: &[&str]) -> Vec<String> {
a.iter().map(|s| (*s).to_owned()).collect()
}
#[test]
fn chooses_like_idea() {
assert_eq!(choose(false, Some(8), "a.jar"), Shortening::None);
assert_eq!(choose(true, Some(8), "a.jar"), Shortening::JarManifest);
assert_eq!(choose(true, None, "a.jar"), Shortening::JarManifest);
assert_eq!(choose(true, Some(9), "a.jar"), Shortening::ArgFile);
assert_eq!(choose(true, Some(21), "a.jar"), Shortening::ArgFile);
assert_eq!(choose(true, Some(21), "C:\\用户\\a.jar"), Shortening::JarManifest);
}
#[test]
fn debugger_launches_get_the_same_choice() {
let dir = tempfile::tempdir().unwrap();
let jdk = dir.path().join("jdk11");
std::fs::create_dir_all(jdk.join("bin")).unwrap();
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"11.0.18\"").unwrap();
let java = jdk.join("bin/java");
let few = vec!["/r/a.jar".to_owned(); 10];
let many = vec![r"C:\Users\dev\.m2\repository\org\x\lib\1.0\lib-1.0.jar".to_owned(); 600];
assert_eq!(shortening_for(&java, &few, &[], true), Shortening::None);
assert_eq!(shortening_for(&java, &many, &[], true), Shortening::ArgFile);
assert_eq!(shortening_for(&java, &many, &[], false), Shortening::None);
assert_eq!(shortening_for(Path::new("java"), &many, &[], true), Shortening::JarManifest);
}
#[test]
fn release_versions() {
assert_eq!(parse_release("JAVA_VERSION=\"1.8.0_372\"\n"), Some(8));
assert_eq!(parse_release("IMPLEMENTOR=x\nJAVA_VERSION=\"21.0.3\""), Some(21));
assert_eq!(parse_release("JAVA_VERSION=\"25\""), Some(25));
assert_eq!(parse_release("nothing"), None);
}
#[test]
fn feature_version_from_the_jdk_layout() {
let dir = tempfile::tempdir().unwrap();
let jdk8 = dir.path().join("jdk8");
std::fs::create_dir_all(jdk8.join("jre/bin")).unwrap();
std::fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"").unwrap();
assert_eq!(java_feature_version(&jdk8.join("jre/bin/java")), Some(8));
let jdk21 = dir.path().join("jdk21");
std::fs::create_dir_all(jdk21.join("bin")).unwrap();
std::fs::write(jdk21.join("release"), "JAVA_VERSION=\"21.0.3\"").unwrap();
assert_eq!(java_feature_version(&jdk21.join("bin/java")), Some(21));
assert_eq!(java_feature_version(Path::new("java")), None);
}
#[test]
fn launchers() {
for p in ["java", "/usr/bin/java", r"C:\jdk\bin\java.exe", r"C:\jdk\bin\javaw.exe", "JAVA.EXE"] {
assert!(is_java_launcher(Path::new(p)), "{p}");
}
for p in ["javac", "kotlin", "/usr/bin/mvn", "java-agent"] {
assert!(!is_java_launcher(Path::new(p)), "{p}");
}
}
#[test]
fn finds_classpath_among_vm_options_only() {
let a = strings(&["-Xmx1g", "--add-opens", "a/b=ALL", "-cp", "x.jar", "Main", "-cp", "y"]);
assert_eq!(path_options(&a), (Some(4), None));
let a = strings(&["-p", "mods", "-classpath", "x.jar", "Main"]);
assert_eq!(path_options(&a), (Some(3), Some(1)));
assert_eq!(path_options(&strings(&["-jar", "app.jar", "-cp", "x"])), (None, None));
assert_eq!(path_options(&strings(&["Main", "-cp", "x"])), (None, None));
}
#[test]
fn urls_are_encoded_and_directories_end_with_a_slash() {
assert_eq!(file_url("/p/a b/x.jar", false), "file:/p/a%20b/x.jar");
assert_eq!(file_url("/p/classes", true), "file:/p/classes/");
assert_eq!(file_url("/p/classes/", true), "file:/p/classes/");
assert_eq!(file_url(r"C:\Users\me\.m2\a+b#c.jar", false), "file:/C:/Users/me/.m2/a%2Bb%23c.jar");
assert_eq!(file_url(r"\\srv\share\x.jar", false), "file:////srv/share/x.jar");
assert_eq!(file_url("/p/用户/x.jar", false), "file:/p/%E7%94%A8%E6%88%B7/x.jar");
assert_eq!(file_url("/p/100%/x.jar", false), "file:/p/100%25/x.jar");
}
#[test]
fn manifest_lines_are_at_most_72_bytes() {
let entries: Vec<PathBuf> = (0..300)
.map(|i| PathBuf::from(format!("/home/u/.m2/repository/org/x/lib-{i}/1.0/lib {i}-1.0.jar")))
.collect();
let m = manifest(&entries);
assert!(m.starts_with("Manifest-Version: 1.0\r\n"));
assert!(m.ends_with("\r\n\r\n"));
for line in m.split("\r\n") {
assert!(line.len() <= 72, "{line:?}");
}
// Unwrapping restores the header exactly.
let joined = m.replace("\r\n ", "");
let joined = joined.lines().find_map(|l| l.strip_prefix("Class-Path: ")).unwrap();
let urls: Vec<&str> = joined.split(' ').collect();
assert_eq!(urls.len(), 300);
assert_eq!(urls[7], "file:/home/u/.m2/repository/org/x/lib-7/1.0/lib%207-1.0.jar");
}
#[test]
fn argfile_quotes_and_escapes() {
assert_eq!(
argfile_text(&strings(&["-cp", r#"C:\a b\x.jar;C:\q"y.jar"#])),
"\"-cp\"\n\"C:\\\\a b\\\\x.jar;C:\\\\q\\\"y.jar\"\n"
);
}
#[test]
fn short_lines_and_other_programs_are_left_alone() {
let dir = tempfile::tempdir().unwrap();
let args = strings(&["-cp", "a.jar", "Main"]);
assert!(shorten(Path::new("java"), &args, dir.path(), true, dir.path()).unwrap().is_none());
let long = strings(&["-cp", &"x".repeat(40_000), "Main"]);
assert!(shorten(Path::new("node"), &long, dir.path(), true, dir.path()).unwrap().is_none());
// Fits the Unix limit; too long for Windows.
assert!(shorten(Path::new("java"), &long, dir.path(), false, dir.path()).unwrap().is_none());
}
/// The reporter's case: JDK 8, ~270 jars, past 32767 chars on Windows.
#[test]
fn jdk8_gets_a_pathing_jar() {
let dir = tempfile::tempdir().unwrap();
let jdk = dir.path().join("jdk8");
std::fs::create_dir_all(jdk.join("bin")).unwrap();
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"1.8.0_372\"").unwrap();
let java = jdk.join("bin/java.exe");
let cp: Vec<String> = (0..270)
.map(|i| format!(r"C:\Users\developer01\.m2\repository\org\springframework\boot\spring-boot-starter-lib-{i}\2.7.18\spring-boot-starter-lib-{i}-2.7.18.jar"))
.collect();
let cp = format!(r"C:\work\demo\target\classes;{}", cp.join(";"));
assert!(cp.len() > 32_767);
let args =
strings(&["-Dspring.profiles.active=dev", "-cp", &cp, "com.example.DemoApplication", "--port", "8080"]);
let tmp = dir.path().join("tmp");
let s = shorten(&java, &args, dir.path(), true, &tmp).unwrap().unwrap();
assert_eq!(s.how, Shortening::JarManifest);
assert_eq!(s.args[0], "-Dspring.profiles.active=dev");
assert_eq!(s.args[1], "-cp");
assert_eq!(s.args[2], s.file.to_string_lossy());
assert_eq!(&s.args[3..], ["com.example.DemoApplication", "--port", "8080"]);
assert!(command_line_length(&java.to_string_lossy(), &s.args) < 1_000);
let mut jar = zip::ZipArchive::new(std::fs::File::open(&s.file).unwrap()).unwrap();
let mut text = String::new();
std::io::Read::read_to_string(&mut jar.by_name("META-INF/MANIFEST.MF").unwrap(), &mut text).unwrap();
let text = text.replace("\r\n ", "");
let urls: Vec<&str> = text.lines().find_map(|l| l.strip_prefix("Class-Path: ")).unwrap().split(' ').collect();
assert_eq!(urls.len(), 271);
assert!(urls.iter().all(|u| u.starts_with("file:/") && u.ends_with(".jar") || u.ends_with("classes")));
}
#[test]
fn jdk9_plus_gets_an_argfile_with_the_module_path() {
let dir = tempfile::tempdir().unwrap();
let jdk = dir.path().join("jdk17");
std::fs::create_dir_all(jdk.join("bin")).unwrap();
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"17.0.6\"").unwrap();
let cp = vec!["/r/lib.jar"; 3_000].join(":");
let args = strings(&["-Xmx1g", "--module-path", "/r/mods", "-cp", &cp, "a.Main", "x"]);
let s = shorten(&jdk.join("bin/java"), &args, dir.path(), true, dir.path()).unwrap().unwrap();
assert_eq!(s.how, Shortening::ArgFile);
assert_eq!(s.args, ["-Xmx1g".to_owned(), format!("@{}", s.file.display()), "a.Main".into(), "x".into()]);
let text = std::fs::read_to_string(&s.file).unwrap();
assert_eq!(text, format!("\"--module-path\"\n\"/r/mods\"\n\"-cp\"\n\"{cp}\"\n"));
}
#[test]
fn wildcards_and_relative_entries() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("lib")).unwrap();
for f in ["b.jar", "a.JAR", "notes.txt"] {
std::fs::write(dir.path().join("lib").join(f), "").unwrap();
}
// An absolute entry stays as is; built from the temp dir so it is absolute on every platform.
let abs = dir.path().join("abs").join("x.jar");
let sep = if cfg!(windows) { ";" } else { ":" };
let cp = ["classes", "lib/*", &abs.to_string_lossy()].join(sep);
let e = classpath_entries(&cp, dir.path(), cfg!(windows));
assert_eq!(e, [dir.path().join("classes"), dir.path().join("lib/a.JAR"), dir.path().join("lib/b.jar"), abs]);
}
/// A pathing jar really loads classes (and resources from directories) with this machine's JDKs.
#[test]
fn pathing_jar_runs_with_a_local_jdk() {
let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from).or_else(|| {
let java = crate::which::find_executable("java", &std::env::var_os("PATH").unwrap_or_default())?;
std::fs::canonicalize(java).ok()?.parent()?.parent().map(Path::to_path_buf)
}) else {
return;
};
let bin = |t: &str| home.join("bin").join(if cfg!(windows) { format!("{t}.exe") } else { t.to_owned() });
if !bin("javac").is_file() {
return;
}
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src dir");
let classes = dir.path().join("out classes");
std::fs::create_dir_all(src.join("p")).unwrap();
std::fs::create_dir_all(&classes).unwrap();
std::fs::write(
src.join("p/Main.java"),
"package p; public class Main { public static void main(String[] a) { System.out.println(\"hello \" + a[0]); } }",
)
.unwrap();
let ok = std::process::Command::new(bin("javac"))
.args(["--release", "8", "-d"])
.arg(&classes)
.arg(src.join("p/Main.java"))
.status()
.is_ok_and(|s| s.success())
|| std::process::Command::new(bin("javac"))
.arg("-d")
.arg(&classes)
.arg(src.join("p/Main.java"))
.status()
.is_ok_and(|s| s.success());
assert!(ok, "javac failed");
let mut entries: Vec<PathBuf> = (0..400).map(|i| dir.path().join(format!("missing {i}.jar"))).collect();
entries.push(classes.clone());
let jar = dir.path().join("cp.jar");
write_pathing_jar(&entries, &jar).unwrap();
let out =
std::process::Command::new(bin("java")).arg("-cp").arg(&jar).args(["p.Main", "world"]).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello world");
}
}
+1
Переглянути файл
@@ -3,6 +3,7 @@
mod config;
mod detect;
pub mod envfile;
pub mod java_cmdline;
pub mod junit;
mod process;
mod utf8;
+50 -2
Переглянути файл
@@ -144,6 +144,44 @@ pub(crate) fn invocation(config: &RunConfig, cwd: &Path) -> Invocation {
Invocation { program, args: config.args.clone(), raw_args: false, display }
}
/// "Shorten command line" for a `java` launch too long for the platform (see
/// [`crate::java_cmdline`]): rewrites `inv` and returns the temporary file to delete on exit.
fn shorten_java(inv: &mut Invocation, config: &RunConfig, cwd: &Path) -> IdeResult<TempFile> {
if inv.raw_args || !crate::java_cmdline::is_java_launcher(&inv.program) {
return Ok(TempFile(None));
}
let java = if inv.program.components().count() == 1 {
crate::which::find_executable(&inv.program.to_string_lossy(), &crate::wrap::search_path(config))
.unwrap_or_else(|| inv.program.clone())
} else {
inv.program.clone()
};
let dir = crate::java_cmdline::default_temp_dir();
let shortened = crate::java_cmdline::shorten(&java, &inv.args, cwd, cfg!(windows), &dir)
.map_err(|e| IdeError::internal(format!("cannot shorten the command line: {e}")))?;
let Some(s) = shortened else { return Ok(TempFile(None)) };
tracing::debug!(how = s.how.as_str(), file = %s.file.display(), "java command line shortened");
let mut display = quote(config.command.trim());
for a in &s.args {
display.push(' ');
display.push_str(&quote(a));
}
inv.args = s.args;
inv.display = display;
Ok(TempFile(Some(s.file)))
}
/// A launch's pathing jar / argfile, deleted when dropped (the process exited, or never started).
struct TempFile(Option<PathBuf>);
impl Drop for TempFile {
fn drop(&mut self) {
if let Some(f) = self.0.take() {
let _ = std::fs::remove_file(f);
}
}
}
/// `command` as one line for the platform shell: `/bin/sh -c`, or `cmd /D /S /C "…"`
/// (`/S` strips exactly the outer quotes, so the line's own quoting survives).
fn shell_invocation(command: &str, windows: bool, comspec: Option<String>) -> Invocation {
@@ -232,7 +270,7 @@ impl ProcessManager {
if !cwd.is_dir() {
return Err(IdeError::not_found(format!("working directory does not exist: {}", cwd.display())));
}
let inv = invocation(config, &cwd);
let mut inv = invocation(config, &cwd);
let extras = &config.extras;
if extras.emulate_terminal && extras.stdin_file.is_some() {
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
@@ -248,8 +286,9 @@ impl ProcessManager {
cwd: cwd.clone(),
env: env.clone(),
});
let temp = shorten_java(&mut inv, config, &cwd)?;
if extras.emulate_terminal {
return self.start_pty(config, &inv, &cwd, &env, stop, options, sink, on_output);
return self.start_pty(config, &inv, &cwd, &env, stop, options, sink, on_output, temp);
}
let mut cmd = Command::new(&inv.program);
@@ -336,6 +375,7 @@ impl ProcessManager {
.name(format!("openidea-run-wait-{}", id.0))
.spawn(move || {
let status = child.wait();
drop(temp);
let _ = waiter_tx.send(Msg::Exited(Exit::Pipes(status)));
})
.map_err(|e| IdeError::internal(format!("failed to start waiter thread: {e}")))?;
@@ -356,6 +396,7 @@ impl ProcessManager {
options: &StartOptions,
sink: SharedSink,
on_output: OutputFn,
temp: TempFile,
) -> IdeResult<RunInfo> {
let pair = native_pty_system()
.openpty(pty_size(DEFAULT_PTY.0, DEFAULT_PTY.1))
@@ -365,6 +406,10 @@ impl ProcessManager {
cmd.cwd(cwd);
if env.clear {
cmd.env_clear();
} else {
for (k, v) in ide_core::process::shell_env() {
cmd.env(k, v);
}
}
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
@@ -413,6 +458,7 @@ impl ProcessManager {
.name(format!("openidea-run-wait-{}", id.0))
.spawn(move || {
let status = child.wait();
drop(temp);
let _ = tx.send(Msg::Exited(Exit::Pty(status)));
})
.map_err(|e| IdeError::internal(format!("failed to start waiter thread: {e}")))?;
@@ -568,6 +614,8 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
if env.clear {
cmd.env_clear();
} else {
cmd.envs(ide_core::process::shell_env());
}
cmd.envs(&env.vars);
}
+15
Переглянути файл
@@ -294,6 +294,21 @@ fn deno_tasks() {
assert!(c[1].is_test);
}
#[test]
fn godot_projects_run_their_main_scene() {
let dir = project(&[("project.godot", "config_version=5\n"), ("demo/project.godot", "config_version=5\n")]);
let c = detect(dir.path());
let root = find(&c, "godot:project");
assert_eq!((root.name.as_str(), root.kind.as_str()), ("Godot Project", "godot"));
assert_eq!(cmdline(root), "godot --path .");
assert_eq!(root.cwd, None);
assert_eq!(root.debug_adapter.as_deref(), Some("godot"));
let demo = find(&c, "godot:project:demo");
assert_eq!(demo.name, "Godot Project (demo)");
assert_eq!(demo.cwd, Some(std::path::PathBuf::from("demo").into()));
assert!(detect(project(&[("main.gd", "extends Node\n")]).path()).is_empty());
}
#[test]
fn just_recipes() {
let justfile = "\
+35
Переглянути файл
@@ -379,3 +379,38 @@ fn stop_command_runs_first_with_the_run_environment() {
assert!(h.root.path().join("stopped").exists(), "stop command did not run");
assert!(text(&chunks, system).contains("touch \"$OPENIDEA_MARKER\""));
}
/// A `java` command line past the platform limit starts through a pathing jar
/// (JDK 8) or an `@argfile` (JDK 9+), which is deleted once the JVM exits.
#[test]
fn long_java_classpath_is_shortened() {
let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from) else { return };
let (java, javac) = (home.join("bin/java"), home.join("bin/javac"));
if !javac.is_file() {
return;
}
let h = harness();
let classes = h.root.path().join("out classes");
std::fs::create_dir_all(classes.join("p")).unwrap();
let src = h.root.path().join("Main.java");
std::fs::write(&src, "package p; public class Main { public static void main(String[] a) { System.out.println(\"hello \" + a[0]); } }").unwrap();
let ok = std::process::Command::new(&javac).arg("-d").arg(&classes).arg(&src).status().unwrap().success();
assert!(ok, "javac failed");
let mut cp: Vec<String> = (0..3_000).map(|i| format!("/no/such/repository/lib-{i}/1.0/lib-{i}-1.0.jar")).collect();
cp.push(classes.to_string_lossy().into_owned());
let cp = cp.join(":");
assert!(cp.len() > ide_run::java_cmdline::UNIX_LIMIT);
let config = cfg("t:java", &java.to_string_lossy(), &["-cp", &cp, "p.Main", "world"]);
let (id, chunks) = start(&h, &config);
assert_eq!(wait_exit(&h, id, Duration::from_secs(30)), Some(0), "{}", text(&chunks, stderr));
assert_eq!(text(&chunks, stdout).trim(), "hello world");
let echo = text(&chunks, system);
let first = echo.lines().next().unwrap();
assert!(first.len() < 1_000, "{first}");
let file = first
.split(' ')
.map(|a| a.trim_matches('\'').trim_start_matches('@'))
.find(|a| a.contains("openidea-classpath"))
.unwrap_or_else(|| panic!("no pathing jar / argfile in {first}"));
assert!(!Path::new(file).exists(), "{file} not deleted");
}
+1
Переглянути файл
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
dunce.workspace = true
ignore.workspace = true
ide-core.workspace = true
ide-language.workspace = true
ide-run.workspace = true
+55 -2
Переглянути файл
@@ -2,8 +2,9 @@
//! language servers, run configurations and terminals.
use crate::discover::{project_venv_python, workspace_tsdk};
use crate::exec::path_with;
use crate::exec::{path_with, search_path};
use crate::{bin_dir, exe, venv_of};
use crate::{godot, vue};
use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use ide_run::RunConfig;
@@ -168,8 +169,28 @@ pub(crate) fn merge_init_options(cfg: &mut LanguageServerConfig, layer: Value) {
/// paths, toolchain `PATH`, env (`GOROOT`, `RUST_SRC_PATH`, `VIRTUAL_ENV`) and
/// server settings (`python.pythonPath`, rust-analyzer `check.command`, `typescript.tsdk`).
/// `root` is the project root, `server_root` the server's workspace root.
/// The executable to launch for `command`: the one chosen in settings, else for
/// commands with well-known install locations (Godot) the one found there.
pub fn tool_command(root: &Path, s: &Settings, command: &str) -> Option<PathBuf> {
let custom = s.tool_path(command).and_then(|p| setting_path(root, p));
if command == godot::COMMAND {
return godot::find(custom);
}
custom
}
/// Points a run configuration launching a bare tool name at the executable from
/// [`tool_command`] (Godot apps live outside the search path).
pub fn resolve_run_command(config: &mut RunConfig, root: &Path, s: &Settings) {
if config.command == godot::COMMAND
&& let Some(path) = tool_command(root, s, &config.command)
{
config.command = path.to_string_lossy().into_owned();
}
}
pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
if let Some(custom) = s.tool_path(&cfg.command).and_then(|p| setting_path(root, p)) {
if let Some(custom) = tool_command(root, s, &cfg.command) {
cfg.command = custom.to_string_lossy().into_owned();
}
let mut path_dirs: Vec<PathBuf> = Vec::new();
@@ -258,6 +279,17 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
_ => {}
}
}
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
if name == "vtsls"
&& let Some(vue) = vue::server_package(&vue_command, &search_path())
{
let plugin = vue::tsserver_plugin(&vue);
merge_init_options(cfg, json!({ "vtsls": { "tsserver": { "globalPlugins": [plugin] } } }));
}
if name == vue::SERVER {
configure_vue_typescript(cfg, root, server_root, s);
}
// Node-based servers (`#!/usr/bin/env node`) run on the selected Node.js.
if let Some(dir) = node_dir(root, s) {
@@ -270,6 +302,26 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
}
}
/// vue-language-server loads TypeScript as a library (`--tsdk`, else its own
/// `require('typescript')`): the selected version, else its own, else the
/// project's — whichever still has the language-service API.
fn configure_vue_typescript(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
let selected = tsdk(server_root, s).or_else(|| tsdk(root, s)).filter(|l| vue::has_ts_api(l));
let package = vue::server_package(&cfg.command, &search_path());
let own = package.as_deref().and_then(vue::own_typescript);
let workspace = || workspace_tsdk(server_root).or_else(|| workspace_tsdk(root)).filter(|l| vue::has_ts_api(l));
let lib = match selected {
Some(lib) => Some(lib),
None if own.is_some() => None,
None => workspace(),
};
match lib {
Some(lib) => cfg.args.push(format!("--tsdk={}", lib.to_string_lossy())),
None if own.is_none() && package.is_some() => cfg.launch_error = Some(vue::missing_typescript_message()),
None => {}
}
}
fn is_python_command(cmd: &str) -> bool {
let name = Path::new(cmd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let name = name.strip_suffix(".exe").unwrap_or(&name);
@@ -297,6 +349,7 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
let mvn_options = maven_options(root, s);
for c in configs.iter_mut() {
resolve_run_command(c, root, s);
let mut path_dirs: Vec<PathBuf> = Vec::new();
match c.kind.as_str() {
"python" | "pytest" => {
+26 -20
Переглянути файл
@@ -394,27 +394,33 @@ fn release_value(release: &str, key: &str) -> Option<String> {
}
fn jdk() -> Vec<Sdk> {
crate::java::rescan_jdks().iter().map(jdk_sdk).collect()
}
/// A JDK as the SDK pickers list it (`Eclipse Adoptium 25.0.1`).
pub fn jdk_sdk(j: &crate::java::Jdk) -> Sdk {
let java_home = std::env::var_os("JAVA_HOME").and_then(|h| dunce::canonicalize(h).ok());
crate::java::rescan_jdks()
.iter()
.map(|j| {
let release = std::fs::read_to_string(j.home.join("release")).unwrap_or_default();
let version = release_value(&release, "JAVA_VERSION").unwrap_or_else(|| j.major.to_string());
let name = match release_value(&release, "IMPLEMENTOR") {
Some(vendor) => format!("{vendor} {version}"),
None => format!("JDK {version}"),
};
let source = if java_home.as_ref() == Some(&j.home) { "JAVA_HOME" } else { "system" };
Sdk {
path: j.home.clone().into(),
name,
version: Some(version),
source: source.to_owned(),
home: Some(j.home.clone().into()),
extra: None,
}
})
.collect()
let release = std::fs::read_to_string(j.home.join("release")).unwrap_or_default();
let version = release_value(&release, "JAVA_VERSION").unwrap_or_else(|| j.major.to_string());
let name = match release_value(&release, "IMPLEMENTOR") {
Some(vendor) => format!("{vendor} {version}"),
None => format!("JDK {version}"),
};
let source = if java_home.as_ref() == Some(&j.home) {
"JAVA_HOME"
} else if crate::java::is_downloaded(&j.home) {
"downloaded"
} else {
"system"
};
Sdk {
path: j.home.clone().into(),
name,
version: Some(version),
source: source.to_owned(),
home: Some(j.home.clone().into()),
extra: None,
}
}
// ------------------------------------------------------------------ maven
+109
Переглянути файл
@@ -0,0 +1,109 @@
//! Locating the Godot editor executable: the GDScript language server and debug
//! adapter run inside it, and run configurations launch games with it.
//!
//! Order: the executable chosen in settings (`tools.godot`), the search path
//! (`godot`, `godot4`, distro names), then the usual install locations per OS
//! (app bundles, Flatpak / Snap exports, Steam, Scoop / WinGet).
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
/// The command language definitions and run configurations launch.
pub const COMMAND: &str = "godot";
pub const NOT_FOUND: &str = "Godot was not found. Install Godot 4 (https://godotengine.org/download), or set \
the Godot executable in Settings › Languages & Frameworks › Language Servers › godot.";
/// Names Godot is installed under on the search path.
const PATH_NAMES: &[&str] = &["godot", "godot4", "godot-4", "Godot", "godot-mono", "godot4-mono"];
/// The Godot executable: `custom` (from settings) when set, else the search path,
/// else a well-known install location.
pub fn find(custom: Option<PathBuf>) -> Option<PathBuf> {
if let Some(p) = custom {
return Some(p);
}
find_in(&crate::search_path(), &install_locations(crate::home_dir().as_deref()))
}
pub(crate) fn find_in(search: &OsStr, locations: &[PathBuf]) -> Option<PathBuf> {
PATH_NAMES
.iter()
.find_map(|n| ide_run::which::find_executable(n, search))
.or_else(|| locations.iter().find(|p| p.is_file()).cloned())
}
/// Well-known install locations, most specific first.
pub(crate) fn install_locations(home: Option<&Path>) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = Vec::new();
let home_join = |rel: &str| home.map(|h| h.join(rel));
if cfg!(target_os = "macos") {
for app in ["Godot.app", "Godot_mono.app", "Godot 4.app"] {
let rel = format!("{app}/Contents/MacOS/Godot");
out.push(Path::new("/Applications").join(&rel));
out.extend(home_join(&format!("Applications/{rel}")));
}
out.extend(home_join(
"Library/Application Support/Steam/steamapps/common/Godot Engine/Godot.app/Contents/MacOS/Godot",
));
} else if cfg!(windows) {
out.extend(home_join("scoop/shims/godot.exe"));
if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
out.push(local.join("Microsoft/WinGet/Links/godot.exe"));
out.push(local.join("Programs/Godot/godot.exe"));
}
for base in ["C:/Program Files", "C:/Program Files (x86)"] {
out.push(Path::new(base).join("Godot/godot.exe"));
out.push(Path::new(base).join("Steam/steamapps/common/Godot Engine/godot.windows.opt.tools.64.exe"));
}
} else {
out.extend(home_join(".local/share/flatpak/exports/bin/org.godotengine.Godot"));
out.push("/var/lib/flatpak/exports/bin/org.godotengine.Godot".into());
out.push("/snap/bin/godot-4".into());
out.push("/snap/bin/godot".into());
out.extend(home_join(".local/share/Steam/steamapps/common/Godot Engine/godot.x11.opt.tools.64"));
}
out
}
/// A Godot project directory: it holds `project.godot`.
pub fn is_project(dir: &Path) -> bool {
dir.join("project.godot").is_file()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn search_path_wins_over_install_locations() {
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("bin");
let app = tmp.path().join("Godot.app/Contents/MacOS");
std::fs::create_dir_all(&bin).unwrap();
std::fs::create_dir_all(&app).unwrap();
let installed = app.join("Godot");
std::fs::write(&installed, "").unwrap();
let search = std::env::join_paths([&bin]).unwrap();
assert_eq!(find_in(&search, std::slice::from_ref(&installed)), Some(installed.clone()));
let on_path = bin.join(if cfg!(windows) { "godot4.exe" } else { "godot4" });
std::fs::write(&on_path, "").unwrap();
assert_eq!(find_in(&search, std::slice::from_ref(&installed)), Some(on_path));
assert_eq!(find_in(OsStr::new(""), &[tmp.path().join("missing")]), None);
}
#[test]
fn custom_path_is_used_as_is() {
assert_eq!(find(Some("/opt/godot/bin/godot".into())), Some(PathBuf::from("/opt/godot/bin/godot")));
}
#[test]
fn install_locations_cover_the_platform() {
let locations = install_locations(Some(Path::new("/home/u")));
assert!(!locations.is_empty());
if cfg!(target_os = "macos") {
assert!(locations.contains(&PathBuf::from("/Applications/Godot.app/Contents/MacOS/Godot")));
assert!(locations.contains(&PathBuf::from("/home/u/Applications/Godot.app/Contents/MacOS/Godot")));
}
}
}
+108 -8
Переглянути файл
@@ -49,9 +49,26 @@ fn children(dir: &Path) -> Vec<PathBuf> {
const WINDOWS_VENDORS: &[&str] =
&["Java", "Eclipse Adoptium", "Microsoft", "Zulu", "Amazon Corretto", "BellSoft", "Semeru", "OpenJDK"];
/// Folders the IDE downloads JDKs into ([`add_jdk_root`]).
static EXTRA_ROOTS: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Scans the JDKs in `dir` (one per subfolder) too, e.g. where Download JDK puts them.
pub fn add_jdk_root(dir: &Path) {
let mut roots = EXTRA_ROOTS.lock().unwrap_or_else(|e| e.into_inner());
if !roots.iter().any(|r| r == dir) {
roots.push(dir.to_path_buf());
}
}
/// Whether `home` lies in a folder registered with [`add_jdk_root`].
pub fn is_downloaded(home: &Path) -> bool {
let roots = EXTRA_ROOTS.lock().unwrap_or_else(|e| e.into_inner());
roots.iter().any(|r| home.starts_with(r) || dunce::canonicalize(r).is_ok_and(|r| home.starts_with(r)))
}
/// JDK homes in the usual install locations (macOS `JavaVirtualMachines`,
/// `/usr/lib/jvm`, SDKMAN, IDEA's `~/.jdks`, Homebrew, Windows vendor
/// directories), `JAVA_HOME` first, then the `java` on `PATH`.
/// directories, the IDE's downloads), `JAVA_HOME` first, then the `java` on `PATH`.
fn scan() -> Vec<Jdk> {
let mut homes: Vec<PathBuf> = Vec::new();
if let Some(h) = std::env::var_os("JAVA_HOME") {
@@ -74,6 +91,7 @@ fn scan() -> Vec<Jdk> {
if let Some(h) = &home {
roots.extend([h.join("Library/Java/JavaVirtualMachines"), h.join(".jdks"), h.join(".sdkman/candidates/java")]);
}
roots.extend(EXTRA_ROOTS.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned());
if cfg!(windows) {
let bases = ["ProgramFiles", "ProgramW6432", "LOCALAPPDATA"].into_iter().filter_map(|v| {
let dir = PathBuf::from(std::env::var_os(v)?);
@@ -343,31 +361,54 @@ pub fn configure_jdtls(
}
}
fn missing_runtime_message(jdks: &[Jdk], min_java: u32) -> String {
/// Where the JDK that runs jdtls is chosen, named as the settings dialog shows it.
const SERVER_JDK_SETTING: &str = "Settings › Languages & Frameworks › Java › Language Server › JDK";
/// `found JDK 8, 17` / `no JDK was found`.
fn found_jdks(jdks: &[Jdk]) -> String {
let mut found: Vec<u32> = jdks.iter().map(|j| j.major).collect();
found.sort_unstable();
found.dedup();
let found = if found.is_empty() {
if found.is_empty() {
"no JDK was found".to_owned()
} else {
let list: Vec<String> = found.iter().map(u32::to_string).collect();
format!("found JDK {}", list.join(", "))
};
}
}
// The UI offers "Download JDK N" for messages saying "needs JDK N or newer".
fn missing_runtime_message(jdks: &[Jdk], min_java: u32) -> String {
format!(
"jdtls needs JDK {min_java} or newer to run ({found}). Install one (or point JAVA_HOME at it) and \
restart the server; the project can still target an older Java version."
"jdtls needs JDK {min_java} or newer to run ({}). Download JDK {min_java}, or pick an installed one in \
{SERVER_JDK_SETTING} (it restarts automatically); the project can still target an older Java version.",
found_jdks(jdks)
)
}
fn server_jdk_too_old_message(jdk: &Jdk, min_java: u32) -> String {
format!(
"The language server JDK ({}, JDK {}) is too old: jdtls needs JDK {min_java} or newer. Choose another \
one in Settings › Languages & Frameworks › Java, or set it to Auto.",
"The language server JDK ({}, JDK {}) is too old: jdtls needs JDK {min_java} or newer. Download JDK \
{min_java}, choose another one in {SERVER_JDK_SETTING}, or set it to Auto.",
jdk.home.display(),
jdk.major
)
}
/// Why a module targeting Java `release` can't be built or run with the installed
/// JDKs (none is that new), or `None` when one is (or the release is unknown).
pub fn missing_jdk_message(jdks: &[Jdk], release: Option<u32>) -> Option<String> {
let release = release?;
if jdks.iter().any(|j| j.major >= release) {
return None;
}
Some(format!(
"This project targets Java {release}: it needs JDK {release} or newer ({}). Download JDK {release}, or \
choose a Project JDK in Settings › Languages & Frameworks › Java.",
found_jdks(jdks)
))
}
/// The `java` launcher of a JDK home.
pub fn java_executable(home: &Path) -> PathBuf {
home.join("bin").join(crate::exe("java"))
@@ -570,6 +611,8 @@ mod tests {
assert!(!cfg.env.contains_key("JAVA_HOME"));
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 21 or newer") && err.contains("found JDK 8, 17"), "{err}");
// The user cannot be sent to JAVA_HOME alone: the language server JDK is a setting.
assert!(err.contains(SERVER_JDK_SETTING) && !err.contains("point JAVA_HOME at it"), "{err}");
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
@@ -589,6 +632,62 @@ mod tests {
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, None, None, 25, &[], None);
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 25 or newer") && err.contains("found JDK 17, 21"), "{err}");
assert!(err.contains("Download JDK 25"), "offers the download: {err}");
}
#[test]
fn issue_49_jdtls_needs_25_with_8_17_21_installed() {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let installed = [
Jdk { major: 21, home: PathBuf::from("/jdk21") },
Jdk { major: 17, home: PathBuf::from("/jdk17") },
Jdk { major: 8, home: PathBuf::from("/jdk8") },
];
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &installed, None, None, 25, &[], None);
let err = cfg.launch_error.unwrap();
assert!(err.starts_with("jdtls needs JDK 25 or newer to run (found JDK 8, 17, 21)"), "{err}");
assert!(err.contains("Download JDK 25"), "{err}");
// Once a JDK 25 has been downloaded, Auto runs jdtls on it.
let downloaded =
[installed.as_slice(), &[Jdk { major: 25, home: PathBuf::from("/tools/jdks/temurin-25") }]].concat();
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &downloaded, None, None, 25, &[], None);
assert_eq!(cfg.launch_error, None);
assert_eq!(cfg.env["JAVA_HOME"], Path::new("/tools/jdks/temurin-25").to_string_lossy());
}
#[test]
fn missing_jdk_for_the_project_release() {
let jdks = [Jdk { major: 17, home: PathBuf::from("/jdk17") }, Jdk { major: 8, home: PathBuf::from("/jdk8") }];
assert_eq!(missing_jdk_message(&jdks, Some(17)), None);
assert_eq!(missing_jdk_message(&jdks, Some(11)), None);
assert_eq!(missing_jdk_message(&jdks, None), None);
let msg = missing_jdk_message(&jdks, Some(21)).unwrap();
assert!(msg.contains("needs JDK 21 or newer (found JDK 8, 17)") && msg.contains("Download JDK 21"), "{msg}");
assert!(missing_jdk_message(&[], Some(8)).unwrap().contains("no JDK was found"));
}
#[test]
fn downloaded_jdks_are_found() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("jdks/temurin-25.0.1");
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("release"), "JAVA_VERSION=\"25.0.1\"\n").unwrap();
std::fs::write(home.join("bin").join(crate::exe("java")), "").unwrap();
// macOS bundles: <dir>/Contents/Home
let bundle = tmp.path().join("jdks/temurin-21.0.5/Contents/Home");
std::fs::create_dir_all(bundle.join("bin")).unwrap();
std::fs::write(bundle.join("release"), "JAVA_VERSION=\"21.0.5\"\n").unwrap();
std::fs::write(bundle.join("bin").join(crate::exe("java")), "").unwrap();
add_jdk_root(&tmp.path().join("jdks"));
let found = rescan_jdks();
let home = dunce::canonicalize(&home).unwrap();
let bundle = dunce::canonicalize(&bundle).unwrap();
assert!(found.iter().any(|j| j.home == home && j.major == 25), "{found:?}");
assert!(found.iter().any(|j| j.home == bundle && j.major == 21), "{found:?}");
assert!(is_downloaded(&home) && !is_downloaded(Path::new("/elsewhere")));
}
#[test]
@@ -633,6 +732,7 @@ mod tests {
assert!(!cfg.env.contains_key("JAVA_HOME"));
let err = cfg.launch_error.unwrap();
assert!(err.contains("/jdk21") && err.contains("JDK 25 or newer"), "{err}");
assert!(err.contains(SERVER_JDK_SETTING), "both messages point at the same setting: {err}");
}
#[test]
+3 -1
Переглянути файл
@@ -8,17 +8,19 @@
pub mod apply;
mod discover;
mod exec;
pub mod godot;
pub mod java;
pub mod libraries;
pub mod locate;
pub mod lombok;
pub mod python;
mod vue;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
pub use discover::detect;
pub use discover::{detect, jdk_sdk};
pub use exec::search_path;
/// What [`detect`] looks for.
+36 -1
Переглянути файл
@@ -85,7 +85,12 @@ pub fn locate_tools_in(names: &[String], near: Option<&Path>, search: &std::ffi:
.iter()
.map(|name| {
let path = valid_name(name)
.then(|| near.and_then(|n| local_bin(n, name)).or_else(|| on_path(name, search)))
.then(|| {
near.and_then(|n| local_bin(n, name))
.or_else(|| on_path(name, search))
.or_else(|| jdk_tool(name, &crate::java::installed_jdks()))
.or_else(|| (name == crate::godot::COMMAND).then(|| crate::godot::find(None)).flatten())
})
.flatten();
LocatedTool { name: name.clone(), path: path.map(Into::into), version: None }
})
@@ -106,6 +111,16 @@ pub fn locate_tools_in(names: &[String], near: Option<&Path>, search: &std::ffi:
})
}
/// `java` / `javac` / `jshell` of the newest installed JDK when none is on the
/// search path (JDKs installed without `PATH` changes, or downloaded by the IDE).
fn jdk_tool(name: &str, jdks: &[crate::java::Jdk]) -> Option<PathBuf> {
if !["java", "javac", "jshell"].contains(&name) {
return None;
}
let jdk = jdks.iter().max_by_key(|j| j.major)?;
Some(jdk.home.join("bin").join(crate::exe(name))).filter(|p| p.is_file())
}
/// Directory for binaries compiled from single source files (`rustc`, `clang`).
pub fn compile_dir() -> PathBuf {
std::env::temp_dir().join("openidea-run")
@@ -124,6 +139,26 @@ mod tests {
assert_eq!(parse_tool_version("no version here"), None);
}
#[test]
fn java_falls_back_to_the_newest_installed_jdk() {
let tmp = tempfile::tempdir().unwrap();
let jdk = |major: u32| {
let home = tmp.path().join(format!("jdk{major}"));
std::fs::create_dir_all(home.join("bin")).unwrap();
for t in ["java", "javac"] {
std::fs::write(home.join("bin").join(crate::exe(t)), "").unwrap();
}
crate::java::Jdk { major, home }
};
let jdks = [jdk(17), jdk(25), jdk(21)];
let newest = tmp.path().join("jdk25/bin");
assert_eq!(jdk_tool("java", &jdks), Some(newest.join(crate::exe("java"))));
assert_eq!(jdk_tool("javac", &jdks), Some(newest.join(crate::exe("javac"))));
assert_eq!(jdk_tool("jshell", &jdks), None, "not in this JDK");
assert_eq!(jdk_tool("node", &jdks), None);
assert_eq!(jdk_tool("java", &[]), None);
}
#[test]
fn rejects_paths_and_shell_syntax() {
assert!(valid_name("ts-node"));
+303 -21
Переглянути файл
@@ -64,7 +64,8 @@ pub fn agent_in_args<'a>(args: impl IntoIterator<Item = &'a str>) -> Option<Path
}
/// The Lombok agent for the project at `root`: the user's own (`own`, from the JVM
/// options) wins, then `managed` (the IDE-installed jar), then the build caches
/// options) wins, then `managed` (the IDE-installed jar, always attached: it is inert
/// without Lombok on the classpath), then, for a project using Lombok, the build caches
/// (`maven_repo`, the configured Maven local repository, else the default one).
pub fn lombok_agent(
root: &Path,
@@ -80,15 +81,16 @@ pub fn lombok_agent(
.map(str::to_owned);
return LombokAgent::Found { jar, version };
}
if !uses_lombok(root) {
return LombokAgent::Unused;
}
if let Some(jar) = managed {
return LombokAgent::Found { jar, version: None };
}
let home = home_dir();
let maven_repo = maven_repo.or_else(|| maven_repository(home.as_deref()));
if !uses_lombok(root, maven_repo.as_deref()) {
return LombokAgent::Unused;
}
let mut dirs = Vec::new();
if let Some(repo) = maven_repo.or_else(|| maven_repository(home.as_deref())) {
if let Some(repo) = maven_repo {
dirs.push(repo.join("org").join("projectlombok").join("lombok"));
}
if let Some(gradle) =
@@ -102,11 +104,31 @@ pub fn lombok_agent(
}
}
/// Build files under `root` (a few levels, for multi-module builds) mentioning Lombok.
pub fn uses_lombok(root: &Path) -> bool {
const FILES: [&str; 4] = ["pom.xml", "build.gradle", "build.gradle.kts", "libs.versions.toml"];
const SKIP: [&str; 7] = ["target", "build", "node_modules", "out", "bin", "src", ".gradle"];
fn walk(dir: &Path, depth: usize) -> bool {
/// Whether the project at `root` uses Lombok. It often arrives through inheritance the
/// project's own build files don't show (a parent POM up the tree or only in the local
/// repository `maven_repo`, an enclosing Gradle build, a convention plugin), so besides
/// those this follows Maven `<parent>` chains, checks an enclosing Gradle build and, last,
/// looks for Java sources importing Lombok, a signal independent of the build.
pub fn uses_lombok(root: &Path, maven_repo: Option<&Path>) -> bool {
let mut poms = Vec::new();
build_files_mention_lombok(root, &mut poms)
|| root.ancestors().skip(1).any(|d| d.join("lombok.config").is_file())
|| parents_mention_lombok(&poms, maven_repo)
|| enclosing_gradle_build_mentions_lombok(root)
|| sources_import_lombok(root)
}
const BUILD_FILES: [&str; 4] = ["pom.xml", "build.gradle", "build.gradle.kts", "libs.versions.toml"];
const OUTPUT_DIRS: [&str; 6] = ["target", "build", "node_modules", "out", "bin", ".gradle"];
fn mentions_lombok(file: &Path) -> bool {
std::fs::read_to_string(file).is_ok_and(|t| t.contains("lombok"))
}
/// Build files under `root` (a few levels, for multi-module builds) mentioning Lombok;
/// the POMs seen go to `poms`.
fn build_files_mention_lombok(root: &Path, poms: &mut Vec<PathBuf>) -> bool {
fn walk(dir: &Path, depth: usize, poms: &mut Vec<PathBuf>) -> bool {
if dir.join("lombok.config").is_file() {
return true;
}
@@ -117,19 +139,133 @@ pub fn uses_lombok(root: &Path) -> bool {
let name = name.to_string_lossy();
let Ok(ty) = e.file_type() else { continue };
if ty.is_dir() {
if depth > 0 && !name.starts_with('.') && !SKIP.contains(&name.as_ref()) {
if depth > 0 && !name.starts_with('.') && name != "src" && !OUTPUT_DIRS.contains(&name.as_ref()) {
subdirs.push(e.path());
}
} else if FILES.contains(&name.as_ref())
&& std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("lombok"))
{
return true;
} else if BUILD_FILES.contains(&name.as_ref()) {
if mentions_lombok(&e.path()) {
return true;
}
if name == "pom.xml" {
poms.push(e.path());
}
}
}
subdirs.iter().any(|d| walk(d, depth - 1))
subdirs.iter().any(|d| walk(d, depth - 1, poms))
}
// `gradle/libs.versions.toml` sits one level down, modules usually no deeper than three.
walk(root, 3)
walk(root, 3, poms)
}
/// Maven inherits dependencies along `<parent>`: whether an ancestor POM of `poms`
/// mentions Lombok.
fn parents_mention_lombok(poms: &[PathBuf], maven_repo: Option<&Path>) -> bool {
const MAX_HOPS: usize = 8;
let mut seen = std::collections::HashSet::new();
for pom in poms {
let Ok(mut text) = std::fs::read_to_string(pom) else { continue };
let mut current = pom.clone();
for _ in 0..MAX_HOPS {
let Some(parent) = parent_pom(&current, &text, maven_repo) else { break };
if !seen.insert(parent.clone()) {
break;
}
let Ok(parent_text) = std::fs::read_to_string(&parent) else { break };
if parent_text.contains("lombok") {
return true;
}
(current, text) = (parent, parent_text);
}
}
false
}
/// The parent of `pom` (content `text`) as Maven resolves it: the POM at `<relativePath>`
/// (default `../pom.xml`, none when empty) if it is that parent, else
/// `<groupId>/<artifactId>/<version>/<artifactId>-<version>.pom` in the local repository.
fn parent_pom(pom: &Path, text: &str, maven_repo: Option<&Path>) -> Option<PathBuf> {
let text = strip_xml_comments(text);
let (block, _) = split_parent(&text)?;
let coord = |tag| crate::java::xml_value(block, tag).filter(|v| !v.is_empty());
let (group, artifact) = (coord("groupId")?, coord("artifactId")?);
let relative = if block.contains("<relativePath/>") || block.contains("<relativePath />") {
String::new()
} else {
crate::java::xml_value(block, "relativePath").unwrap_or_else(|| "../pom.xml".to_owned())
};
if !relative.is_empty() {
let mut local = pom.parent()?.join(relative.replace('\\', "/"));
if local.is_dir() {
local = local.join("pom.xml");
}
let is_parent = std::fs::read_to_string(&local)
.is_ok_and(|t| own_artifact_id(&strip_xml_comments(&t)).as_deref() == Some(artifact.as_str()));
if is_parent {
return Some(dunce::canonicalize(&local).unwrap_or(local));
}
}
let version = coord("version").filter(|v| !v.contains("${"))?;
let dir = group.split('.').fold(maven_repo?.to_path_buf(), |d, part| d.join(part));
let file = dir.join(&artifact).join(&version).join(format!("{artifact}-{version}.pom"));
file.is_file().then_some(file)
}
/// A POM's `<parent>…</parent>` element and the text without it.
fn split_parent(text: &str) -> Option<(&str, String)> {
let start = text.find("<parent>")?;
let end = start + text[start..].find("</parent>")? + "</parent>".len();
Some((&text[start..end], format!("{}{}", &text[..start], &text[end..])))
}
/// A POM's own `<artifactId>`, not its parent's.
fn own_artifact_id(text: &str) -> Option<String> {
match split_parent(text) {
Some((_, rest)) => crate::java::xml_value(&rest, "artifactId"),
None => crate::java::xml_value(text, "artifactId"),
}
}
/// A Gradle subproject opened on its own: the enclosing build (the nearest ancestor with
/// `settings.gradle[.kts]`) may apply Lombok from its root build file or version catalog.
fn enclosing_gradle_build_mentions_lombok(root: &Path) -> bool {
const MAX_LEVELS: usize = 4;
let settings = |d: &Path| d.join("settings.gradle").is_file() || d.join("settings.gradle.kts").is_file();
root.ancestors().skip(1).take(MAX_LEVELS).find(|d| settings(d)).is_some_and(|build| {
["build.gradle", "build.gradle.kts", "gradle/libs.versions.toml"]
.iter()
.any(|f| mentions_lombok(&build.join(f)))
})
}
/// Java sources under `root` importing Lombok. Bounded (the heads of the first files),
/// honouring ignore files and skipping build output.
fn sources_import_lombok(root: &Path) -> bool {
use std::io::Read;
const MAX_ENTRIES: usize = 50_000;
const MAX_FILES: usize = 2000;
// Imports precede the first type, after at most a license header.
const HEAD: u64 = 8 * 1024;
let mut walker = ignore::WalkBuilder::new(root);
walker.require_git(false).follow_links(false).filter_entry(|e| {
e.depth() == 0
|| !e.file_type().is_some_and(|t| t.is_dir())
|| !OUTPUT_DIRS.contains(&e.file_name().to_string_lossy().as_ref())
});
let imports_lombok = |path: &Path| {
let mut head = Vec::new();
let read = std::fs::File::open(path).and_then(|f| f.take(HEAD).read_to_end(&mut head));
let head = String::from_utf8_lossy(&head);
read.is_ok()
&& (head.contains("@lombok.")
|| head.lines().any(|l| l.trim_start().starts_with("import ") && l.contains(" lombok.")))
};
walker
.build()
.take(MAX_ENTRIES)
.flatten()
.filter(|e| e.file_type().is_some_and(|t| t.is_file()) && e.path().extension().is_some_and(|x| x == "java"))
.take(MAX_FILES)
.any(|e| imports_lombok(e.path()))
}
/// `<localRepository>` of `~/.m2/settings.xml`, else `~/.m2/repository`.
@@ -203,18 +339,164 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
fs::write(root.join("pom.xml"), "<project><modules><module>api</module></modules></project>").unwrap();
assert!(!uses_lombok(root));
assert!(!uses_lombok(root, None));
fs::create_dir_all(root.join("api/src/main")).unwrap();
fs::write(root.join("api/src/main/pom.xml"), "<artifactId>lombok</artifactId>").unwrap();
assert!(!uses_lombok(root), "sources are not scanned");
assert!(!uses_lombok(root, None), "build files under src are not scanned");
fs::write(root.join("api/pom.xml"), "<artifactId>lombok</artifactId>").unwrap();
assert!(uses_lombok(root));
assert!(uses_lombok(root, None));
let gradle = tempfile::tempdir().unwrap();
fs::create_dir_all(gradle.path().join("gradle")).unwrap();
fs::write(gradle.path().join("gradle/libs.versions.toml"), "lombok = \"org.projectlombok:lombok:1.18.30\"")
.unwrap();
assert!(uses_lombok(gradle.path()));
assert!(uses_lombok(gradle.path(), None));
}
const LOMBOK_DEP: &str = "<dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies>";
fn pom(own: &str, parent: &str) -> String {
format!("<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>{own}</artifactId></project>")
}
fn parent(artifact: &str, extra: &str) -> String {
format!(
"<parent><groupId>com.acme</groupId><artifactId>{artifact}</artifactId><version>1.0</version>{extra}</parent>"
)
}
#[test]
fn parent_pom_only_in_the_local_repository() {
// #33: the module's parent was `mvn install`ed, its directory isn't on disk.
let tmp = tempfile::tempdir().unwrap();
let (module, repo) = (tmp.path().join("module-a"), tmp.path().join("m2"));
fs::create_dir_all(&module).unwrap();
fs::write(module.join("pom.xml"), pom("module-a", &parent("acme-parent", ""))).unwrap();
assert!(!uses_lombok(&module, Some(&repo)));
let dir = repo.join("com/acme/acme-parent/1.0");
fs::create_dir_all(&dir).unwrap();
// The dependency comes from the grandparent.
fs::write(dir.join("acme-parent-1.0.pom"), pom("acme-parent", &parent("acme-root", ""))).unwrap();
assert!(!uses_lombok(&module, Some(&repo)));
let root = repo.join("com/acme/acme-root/1.0");
fs::create_dir_all(&root).unwrap();
fs::write(
root.join("acme-root-1.0.pom"),
format!("<project><artifactId>acme-root</artifactId>{LOMBOK_DEP}</project>"),
)
.unwrap();
assert!(uses_lombok(&module, Some(&repo)));
assert!(!uses_lombok(&module, None), "no repository, no parent");
let agent = lombok_agent(&module, None, None, Some(repo.clone()));
assert_ne!(agent, LombokAgent::Unused, "missing, or a jar from the Gradle cache");
}
#[test]
fn parent_pom_via_relative_path_outside_the_root() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("project");
let module = project.join("modules/api");
fs::create_dir_all(&module).unwrap();
fs::create_dir_all(tmp.path().join("platform")).unwrap();
fs::write(
module.join("pom.xml"),
pom("api", &parent("platform", "<relativePath>../../../platform</relativePath>")),
)
.unwrap();
fs::write(
tmp.path().join("platform/pom.xml"),
format!("<project><artifactId>platform</artifactId>{LOMBOK_DEP}</project>"),
)
.unwrap();
assert!(uses_lombok(&module, None));
assert!(uses_lombok(&project, None), "modules' parents are followed too");
// The default `../pom.xml`, but it is another project's POM: not the parent.
let other = tempfile::tempdir().unwrap();
let child = other.path().join("child");
fs::create_dir_all(&child).unwrap();
fs::write(child.join("pom.xml"), pom("child", &parent("acme-parent", ""))).unwrap();
fs::write(
other.path().join("pom.xml"),
format!("<project><artifactId>unrelated</artifactId>{LOMBOK_DEP}</project>"),
)
.unwrap();
assert!(!uses_lombok(&child, None));
fs::write(
other.path().join("pom.xml"),
format!("<project><artifactId>acme-parent</artifactId>{LOMBOK_DEP}</project>"),
)
.unwrap();
assert!(uses_lombok(&child, None));
// An empty relativePath means: from the repository only.
fs::write(child.join("pom.xml"), pom("child", &parent("acme-parent", "<relativePath/>"))).unwrap();
assert!(!uses_lombok(&child, None));
}
#[test]
fn parent_cycles_terminate() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a");
fs::create_dir_all(&a).unwrap();
fs::write(a.join("pom.xml"), pom("a", &parent("root", ""))).unwrap();
fs::write(tmp.path().join("pom.xml"), pom("root", &parent("root", "<relativePath>pom.xml</relativePath>")))
.unwrap();
assert!(!uses_lombok(&a, None));
}
#[test]
fn enclosing_gradle_build() {
let tmp = tempfile::tempdir().unwrap();
let sub = tmp.path().join("services/billing");
fs::create_dir_all(&sub).unwrap();
fs::write(sub.join("build.gradle.kts"), "plugins { java }").unwrap();
fs::write(tmp.path().join("settings.gradle.kts"), "include(\"services:billing\")").unwrap();
assert!(!uses_lombok(&sub, None));
fs::write(
tmp.path().join("build.gradle.kts"),
"subprojects { dependencies { \"compileOnly\"(\"org.projectlombok:lombok:1.18.36\") } }",
)
.unwrap();
assert!(uses_lombok(&sub, None));
}
#[test]
fn sources_importing_lombok() {
// E.g. a Gradle convention plugin in buildSrc/src or an included build adds it.
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let pkg = root.join("app/src/main/java/com/acme");
fs::create_dir_all(&pkg).unwrap();
fs::write(root.join("build.gradle"), "plugins { id 'acme.java-conventions' }").unwrap();
fs::write(pkg.join("Plain.java"), "package com.acme;\n\nimport java.util.List;\n\nclass Plain {}\n").unwrap();
assert!(!uses_lombok(root, None));
// Build output and ignored files don't count.
fs::create_dir_all(root.join("app/build/generated")).unwrap();
fs::write(root.join("app/build/generated/G.java"), "import lombok.Data;\n").unwrap();
fs::write(root.join(".ignore"), "vendor/\n").unwrap();
fs::create_dir_all(root.join("vendor")).unwrap();
fs::write(root.join("vendor/V.java"), "import lombok.Value;\n").unwrap();
assert!(!uses_lombok(root, None));
fs::write(
pkg.join("User.java"),
"/* License */\npackage com.acme;\n\nimport lombok.Data;\n\n@Data\nclass User {}\n",
)
.unwrap();
assert!(uses_lombok(root, None));
fs::write(pkg.join("User.java"), "package com.acme;\n\n@lombok.Getter\nclass User {}\n").unwrap();
assert!(uses_lombok(root, None));
fs::write(pkg.join("User.java"), "package com.acme;\nimport static lombok.AccessLevel.PRIVATE;\n").unwrap();
assert!(uses_lombok(root, None));
}
#[test]
fn the_installed_agent_applies_without_detection() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("m2");
assert_eq!(lombok_agent(tmp.path(), None, None, Some(repo.clone())), LombokAgent::Unused);
let managed = lombok_agent(tmp.path(), None, Some("/managed/lombok.jar".into()), Some(repo));
assert_eq!(managed.jar(), Some(Path::new("/managed/lombok.jar")));
assert_eq!(managed.problem(), None);
}
#[test]
+83
Переглянути файл
@@ -29,6 +29,7 @@ fn server(name: &str) -> LanguageServerConfig {
root_markers: vec![],
initialization_options: None,
install_hint: None,
connect: None,
fallback: false,
launch_error: None,
}
@@ -292,6 +293,36 @@ fn custom_tool_path_replaces_the_command() {
assert_eq!(cfg.command, "zls");
}
#[test]
fn the_godot_setting_applies_to_server_debugger_and_run_configurations() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Settings::default();
s.tools.insert("godot".into(), ide_core::settings::ToolSettings { path: "~/Godot/godot".into() });
let expected = crate::home_dir().unwrap().join("Godot/godot");
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "godot"), Some(expected.clone()));
let mut cfg = LanguageServerConfig { command: "godot".into(), ..server("godot") };
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(Path::new(&cfg.command), expected);
let mut run = RunConfig {
id: "godot:project".into(),
name: "Godot Project".into(),
kind: "godot".into(),
command: "godot".into(),
args: vec!["--path".into(), ".".into()],
cwd: None,
env: BTreeMap::new(),
detected: true,
is_test: false,
debug_adapter: Some("godot".into()),
allow_parallel: false,
extras: Default::default(),
};
apply_to_run_configs(std::slice::from_mut(&mut run), tmp.path(), &s);
assert_eq!(Path::new(&run.command), expected);
// Other commands keep their name without a setting.
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "zls"), None);
}
#[test]
fn python_library_paths_are_parsed_and_deduplicated() {
let tmp = tempfile::tempdir().unwrap();
@@ -461,3 +492,55 @@ fn no_ecosystem_libraries_without_manifests() {
std::fs::create_dir_all(tmp.path().join("node_modules/react")).unwrap();
assert!(crate::libraries::project_libraries(tmp.path(), &Settings::default(), &[]).is_empty());
}
/// Tools dir with vue-language-server and the given TypeScript files, plus a
/// project; returns (tools, project).
fn vue_setup(tmp: &Path, tools_ts: &str, project_ts: &str) -> (std::path::PathBuf, std::path::PathBuf) {
let tools = tmp.join("tools/node_modules");
let project = tmp.join("app");
for (p, content) in [
(tools.join(".bin/vue-language-server"), ""),
(tools.join("@vue/language-server/package.json"), "{}"),
(tools.join("typescript/lib").join(tools_ts), ""),
(project.join("node_modules/typescript/lib").join(project_ts), ""),
(project.join("node_modules/typescript/lib/tsserver.js"), ""),
] {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, content).unwrap();
}
(tools, project)
}
#[test]
fn vue_language_server_gets_a_typescript_with_the_language_service_api() {
// Issue #25: `typescript@latest` (7.x) in the tools dir has no `ts.server`.
let s = Settings::default();
let cases = [
// (tools TypeScript, project TypeScript, expected --tsdk = project lib, launch error)
("typescript.js", "typescript.js", false, false), // own TypeScript 5/6 works
("tsc.js", "typescript.js", true, false), // own TS 7: the project's
("tsc.js", "tsc.js", false, true), // nothing usable: clear error
];
for (tools_ts, project_ts, uses_project, error) in cases {
let tmp = tempfile::tempdir().unwrap();
let (tools, project) = vue_setup(tmp.path(), tools_ts, project_ts);
let mut cfg = server("vue-language-server");
cfg.command = tools.join(".bin/vue-language-server").to_string_lossy().into_owned();
configure_server(&mut cfg, &project, &project, &s);
let tsdk = cfg.args.iter().find_map(|a| a.strip_prefix("--tsdk=")).map(std::path::PathBuf::from);
let project_lib = project.join("node_modules/typescript/lib");
assert_eq!(tsdk, uses_project.then_some(project_lib), "{tools_ts} / {project_ts}");
assert_eq!(cfg.launch_error.is_some(), error, "{tools_ts} / {project_ts}");
}
// A selected version wins over the server's own.
let tmp = tempfile::tempdir().unwrap();
let (tools, project) = vue_setup(tmp.path(), "typescript.js", "typescript.js");
let mut s = Settings::default();
s.languages.typescript.version = "workspace".into();
let mut cfg = server("vue-language-server");
cfg.command = tools.join(".bin/vue-language-server").to_string_lossy().into_owned();
configure_server(&mut cfg, &project, &project, &s);
let lib = project.join("node_modules/typescript/lib");
assert_eq!(cfg.args, [format!("--tsdk={}", lib.to_string_lossy())]);
}
+121
Переглянути файл
@@ -0,0 +1,121 @@
//! Vue Language Server (Volar 3): the TypeScript it loads as a library, and the
//! `@vue/typescript-plugin` that vtsls' tsserver hosts for it (hybrid mode).
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
pub(crate) const SERVER: &str = "vue-language-server";
const PACKAGE: &str = "@vue/language-server";
const PLUGIN: &str = "@vue/typescript-plugin";
/// The TypeScript `lib` directory has the language-service API (`typescript.js`).
/// TypeScript 7, the native port, ships only `tsc`.
pub(crate) fn has_ts_api(lib: &Path) -> bool {
lib.join("typescript.js").is_file()
}
/// `command` as given (a path) or found on `path`, npm shims included.
fn find_command(command: &str, path: &OsStr) -> Option<PathBuf> {
let p = Path::new(command);
if p.is_absolute() {
return p.is_file().then(|| p.to_path_buf());
}
let exts: &[&str] = if cfg!(windows) { &[".cmd", ".exe", ""] } else { &[""] };
std::env::split_paths(path)
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{command}{e}"))))
.find(|c| c.is_file())
}
/// The npm package an executable comes from: next to a `node_modules/.bin` shim
/// (the IDE's tools dir, a project), a Windows global shim (`%APPDATA%\npm`), a
/// Unix global `<prefix>/bin` or a symlink into the package.
fn package_dir(bin: &Path, package: &str) -> Option<PathBuf> {
let dir = bin.parent()?;
let mut candidates = vec![dir.join("node_modules").join(package)];
if dir.file_name() == Some(OsStr::new(".bin"))
&& let Some(node_modules) = dir.parent()
{
candidates.push(node_modules.join(package));
}
if let Ok(real) = dunce::canonicalize(bin) {
candidates.extend(real.ancestors().filter(|a| a.ends_with(package)).map(Path::to_path_buf));
}
if let Some(prefix) = dir.parent() {
candidates.push(prefix.join("lib").join("node_modules").join(package));
}
candidates.into_iter().find(|c| c.join("package.json").is_file())
}
/// `@vue/language-server`'s directory for the `vue-language-server` command.
pub(crate) fn server_package(command: &str, path: &OsStr) -> Option<PathBuf> {
package_dir(&find_command(command, path)?, PACKAGE)
}
/// The TypeScript `require('typescript')` resolves to from `package`, when usable.
pub(crate) fn own_typescript(package: &Path) -> Option<PathBuf> {
package.ancestors().map(|a| a.join("node_modules").join("typescript").join("lib")).find(|l| has_ts_api(l))
}
/// vtsls `globalPlugins` entry loading the Vue plugin shipped with `package`.
pub(crate) fn tsserver_plugin(package: &Path) -> serde_json::Value {
serde_json::json!({
"name": PLUGIN,
"location": package.to_string_lossy(),
"languages": ["vue"],
"configNamespace": "typescript",
"enableForWorkspaceTypeScriptVersions": true,
})
}
pub(crate) fn missing_typescript_message() -> String {
"Vue Language Server needs TypeScript 5 or 6 (TypeScript 7 has no language service API). \
Reinstall it in Settings › Languages & Frameworks › Language Servers, add typescript@\"<7\" \
to the project, or pick a TypeScript version in Settings › Languages & Frameworks › TypeScript."
.to_owned()
}
#[cfg(test)]
mod tests {
use super::*;
fn touch(p: &Path) {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "{}").unwrap();
}
#[test]
fn finds_the_package_of_every_npm_install_layout() {
let tmp = tempfile::tempdir().unwrap();
let t = tmp.path();
// (executable, package.json) per layout.
let layouts = [
// The IDE's tools dir / a project: node_modules/.bin shim.
("tools/node_modules/.bin/vue-language-server", "tools/node_modules/@vue/language-server/package.json"),
// Windows global: %APPDATA%\npm\vue-language-server(.cmd) + %APPDATA%\npm\node_modules.
("npm/vue-language-server", "npm/node_modules/@vue/language-server/package.json"),
// Unix global prefix: <prefix>/bin + <prefix>/lib/node_modules.
("prefix/bin/vue-language-server", "prefix/lib/node_modules/@vue/language-server/package.json"),
];
for (bin, pkg) in layouts {
touch(&t.join(bin));
touch(&t.join(pkg));
let found = server_package(&t.join(bin).to_string_lossy(), OsStr::new(""));
assert_eq!(found, Some(t.join(pkg).parent().unwrap().to_path_buf()), "{bin}");
}
let path = std::env::join_paths([t.join("tools/node_modules/.bin")]).unwrap();
assert_eq!(server_package(SERVER, &path), Some(t.join("tools/node_modules/@vue/language-server")));
assert_eq!(server_package("not-installed", &path), None);
}
#[test]
fn own_typescript_skips_typescript_7() {
let tmp = tempfile::tempdir().unwrap();
let pkg = tmp.path().join("node_modules/@vue/language-server");
touch(&pkg.join("package.json"));
// TypeScript 7 ships only `tsc`.
touch(&tmp.path().join("node_modules/typescript/lib/tsc.js"));
assert_eq!(own_typescript(&pkg), None);
touch(&tmp.path().join("node_modules/typescript/lib/typescript.js"));
assert_eq!(own_typescript(&pkg), Some(tmp.path().join("node_modules/typescript/lib")));
}
}
+2
Переглянути файл
@@ -14,6 +14,7 @@ mod mask;
mod pattern;
mod query;
mod replace;
mod words;
pub use files::{ScopeFile, scope_files};
pub use mask::FileMask;
@@ -22,6 +23,7 @@ pub use replace::{
ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview,
replace_files, replacement_edits,
};
pub use words::{WordFiles, WordQuery, files_with_word};
use grep_matcher::{Captures, Matcher};
use ide_core::{CancellationToken, IdeError, IdeResult};
+118
Переглянути файл
@@ -0,0 +1,118 @@
//! Files that mention an identifier: the candidates a reference search checks.
use crate::{Overlay, PathFilter, SearchContext, SearchQuery, SearchScope};
use ide_core::{CancellationToken, IdeResult};
use std::path::PathBuf;
use std::sync::Mutex;
#[derive(Clone, Debug)]
pub struct WordQuery {
/// Matched as a whole word, case-sensitively.
pub word: String,
/// Directory searched (absolute, or relative to the search root).
pub dir: PathBuf,
/// File masks never searched (excluded roots, ignored names).
pub exclude: Vec<String>,
/// Files returned at most.
pub limit: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WordFiles {
pub files: Vec<PathBuf>,
/// More files matched than `limit`; the search stopped early.
pub limit_hit: bool,
}
/// Files under `query.dir` containing `query.word` as a whole word, in walk
/// order (unsaved buffers through `overlay`, `.gitignore`d and hidden files
/// skipped like Find in Files). Stops at `query.limit` files or when cancelled.
pub fn files_with_word(
root: &std::path::Path,
query: &WordQuery,
filter: Option<PathFilter<'_>>,
overlay: Overlay<'_>,
cancel: &CancellationToken,
) -> IdeResult<WordFiles> {
let search = SearchQuery {
pattern: query.word.clone(),
is_regex: false,
case_sensitive: true,
whole_word: true,
include: Vec::new(),
exclude: query.exclude.clone(),
scope: SearchScope::Directory { path: query.dir.clone().into() },
max_matches: u32::MAX,
context: SearchContext::Any,
};
let stop = cancel.child_token();
let found = Mutex::new(WordFiles::default());
crate::search_filtered(root, &search, filter, overlay, &stop, &|file| {
let mut found = found.lock().unwrap_or_else(|e| e.into_inner());
if found.files.len() < query.limit {
found.files.push(file.path.into_path_buf());
} else {
found.limit_hit = true;
stop.cancel();
}
})?;
Ok(found.into_inner().unwrap_or_else(|e| e.into_inner()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn query(word: &str, limit: usize) -> WordQuery {
WordQuery { word: word.into(), dir: PathBuf::from("."), exclude: vec!["build/**".into()], limit }
}
#[test]
fn whole_word_matches_in_kept_files_only() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
fs::create_dir_all(root.join("pkg/ignored")).unwrap();
fs::create_dir_all(root.join("build")).unwrap();
fs::write(root.join(".gitignore"), "ignored/\n").unwrap();
fs::write(root.join("pkg/use.py"), "x.get_value(1)\n").unwrap();
fs::write(root.join("pkg/longer.py"), "get_values()\n").unwrap();
fs::write(root.join("pkg/case.py"), "Get_Value()\n").unwrap();
fs::write(root.join("pkg/notes.txt"), "get_value\n").unwrap();
fs::write(root.join("pkg/ignored/gen.py"), "get_value\n").unwrap();
fs::write(root.join("build/out.py"), "get_value\n").unwrap();
fs::write(root.join("pkg/open.py"), "nothing on disk\n").unwrap();
let unsaved = root.join("pkg/open.py");
let overlay = |p: &std::path::Path| (p == unsaved).then(|| "get_value()".to_owned());
let py = |rel: &str| rel.ends_with(".py");
let mut found =
files_with_word(root, &query("get_value", 10), Some(&py), &overlay, &CancellationToken::new()).unwrap();
found.files.sort();
assert_eq!(
found,
WordFiles { files: vec![root.join("pkg/open.py"), root.join("pkg/use.py")], limit_hit: false }
);
}
#[test]
fn stops_at_the_limit() {
let dir = tempfile::tempdir().unwrap();
for i in 0..5 {
fs::write(dir.path().join(format!("f{i}.py")), "name\n").unwrap();
}
let found = files_with_word(dir.path(), &query("name", 2), None, &|_| None, &CancellationToken::new()).unwrap();
assert_eq!((found.files.len(), found.limit_hit), (2, true));
let all = files_with_word(dir.path(), &query("name", 5), None, &|_| None, &CancellationToken::new()).unwrap();
assert_eq!((all.files.len(), all.limit_hit), (5, false));
}
#[test]
fn a_cancelled_search_finds_nothing() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("a.py"), "name\n").unwrap();
let cancel = CancellationToken::new();
cancel.cancel();
let found = files_with_word(dir.path(), &query("name", 5), None, &|_| None, &cancel).unwrap();
assert!(found.files.is_empty());
}
}
+3
Переглянути файл
@@ -13,3 +13,6 @@ tracing.workspace = true
spellbook = "0.4"
serde.workspace = true
specta.workspace = true
[dev-dependencies]
serde_json.workspace = true
+42
Переглянути файл
@@ -461,3 +461,45 @@ workspaces
xml
yaml
yml
# Python (IDEA's Python plugin bundles a similar dictionary)
asyncio
awaitable
classmethod
contextmanager
dataclass
dataclasses
dtype
dtypes
dunder
elif
kwarg
ndarray
nonlocal
numpy
pydantic
pyproject
pytest
setuptools
staticmethod
venv
virtualenv
# Services and infrastructure
checkpointing
dockerfile
embeddings
healthcheck
hotfix
kubectl
kubernetes
llm
llms
mysql
postgres
postgresql
rollout
subnet
upsert
webhook
webhooks
websocket
websockets
+278 -18
Переглянути файл
@@ -2,6 +2,8 @@
//! comments, string literals and declared names (regions come from the
//! syntax layer), checked against the bundled en_US Hunspell dictionary, a
//! list of programming terms and the user's accepted words and dictionaries.
//! Regular agent nouns of known words (`checkpointer`) pass everywhere; in
//! identifiers so do closed compounds of known words (`codebase`).
mod words;
@@ -35,12 +37,62 @@ pub struct Region {
pub kind: RegionKind,
}
/// What a typo is part of: correcting one in `Code` (a declared name) must
/// rename the symbol; the others may replace the word in place.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TypoContext {
Code,
Literal,
Comment,
Prose,
}
impl From<RegionKind> for TypoContext {
fn from(kind: RegionKind) -> Self {
match kind {
RegionKind::Name => Self::Code,
RegionKind::String => Self::Literal,
RegionKind::Comment => Self::Comment,
RegionKind::Prose => Self::Prose,
}
}
}
/// A misspelt word.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct Typo {
/// UTF-16 range of the word.
pub range: Range,
pub word: String,
pub context: TypoContext,
}
/// The Typo inspection's options (IDEA's "Process code / literals / comments");
/// plain text and Markdown are always checked.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SpellScope {
pub code: bool,
pub literals: bool,
pub comments: bool,
}
impl Default for SpellScope {
fn default() -> Self {
Self { code: true, literals: true, comments: true }
}
}
impl SpellScope {
pub fn includes(&self, kind: RegionKind) -> bool {
match kind {
RegionKind::Name => self.code,
RegionKind::String => self.literals,
RegionKind::Comment => self.comments,
RegionKind::Prose => true,
}
}
}
/// At most this many typos are reported per text.
@@ -55,6 +107,50 @@ fn english() -> &'static spellbook::Dictionary {
})
}
/// Lowercase entries of the dictionary as listed (no affixes applied, no proper nouns).
fn lemmas() -> &'static HashSet<&'static str> {
static LEMMAS: OnceLock<HashSet<&'static str>> = OnceLock::new();
LEMMAS.get_or_init(|| {
include_str!("dict/en_US.dic")
.lines()
.skip(1)
.map(|l| l.split('/').next().unwrap_or(l).trim())
.filter(|w| !w.is_empty() && w.chars().all(|c| c.is_ascii_lowercase()))
.collect()
})
}
/// Common misspellings made of two words; never accepted as compounds.
const NOT_COMPOUNDS: &[&str] = &["eachother", "everytime", "publically", "aswell", "infact", "atleast", "alot"];
/// Shortest dictionary word in a derivation or compound (programming terms: 3).
const MIN_PART: usize = 4;
/// Whether English doubles the final consonant before `-er` (`program` →
/// `programmer`): the stem ends consonant, single vowel, consonant (not w/x/y).
fn doubles_final_consonant(stem: &str) -> bool {
let vowel = |c: u8| b"aeiou".contains(&c);
match stem.as_bytes() {
[.., a, b, c] => !vowel(*a) && vowel(*b) && !vowel(*c) && !b"wxy".contains(c),
_ => false,
}
}
/// Whether dropping one letter or swapping two adjacent ones gives a dictionary
/// word: then a compound (`writ`+`ting`) is more likely a typo of
/// it (`writing`), as Hunspell's CHECKCOMPOUNDREP reasons.
fn near_word(lower: &str) -> bool {
let b = lower.as_bytes();
let dict = english();
let check = |v: &[u8]| std::str::from_utf8(v).is_ok_and(|w| dict.check(w));
(0..b.len()).any(|i| check(&[&b[..i], &b[i + 1..]].concat()))
|| (0..b.len().saturating_sub(1)).any(|i| {
let mut v = b.to_vec();
v.swap(i, i + 1);
v != b && check(&v)
})
}
fn software_terms() -> &'static HashSet<&'static str> {
static TERMS: OnceLock<HashSet<&'static str>> = OnceLock::new();
TERMS.get_or_init(|| {
@@ -118,23 +214,71 @@ impl Speller {
}
}
/// Whether `word` is spelt correctly. Case is forgiven the way identifiers
/// need it: `url` passes for `URL`, `paris` for `Paris`.
/// Whether `word` (of prose, a comment or a string) is spelt correctly.
/// Case is forgiven the way identifiers need it: `url` passes for `URL`,
/// `paris` for `Paris`. Regular agent nouns of known words pass too
/// (`checkpointer`, `serializers`).
pub fn is_correct(&self, word: &str) -> bool {
let lower = word.to_lowercase();
if self.accepted.contains(&lower)
|| software_terms().contains(lower.as_str())
|| self.custom.iter().any(|d| d.contains(&lower))
{
self.listed(word, &lower) || self.agent_noun(&lower)
}
/// [`Self::is_correct`] for a part of an identifier, which may also be two
/// known words run together (`codebase`, `urlpath`), as identifiers often are.
pub fn is_correct_identifier(&self, word: &str) -> bool {
self.is_correct(word) || self.compound(&word.to_lowercase())
}
fn user_word(&self, lower: &str) -> bool {
self.accepted.contains(lower)
|| software_terms().contains(lower)
|| self.custom.iter().any(|d| d.contains(lower))
}
/// In a dictionary, in any case style.
fn listed(&self, word: &str, lower: &str) -> bool {
if self.user_word(lower) {
return true;
}
let dict = english();
if dict.check(word) || dict.check(&lower) {
return true;
dict.check(word) || dict.check(lower) || dict.check(&capitalize(lower)) || dict.check(&lower.to_uppercase())
}
/// `<stem>er(s)` / `<stem>r(s)` of a listed stem: `checkpointer`
/// (checkpoint), `serializers` (serialize), `queriers` (query). Not when
/// English doubles the final consonant (`programer`) or the `-or` noun is
/// the word (`processer`, `generater`).
fn agent_noun(&self, lower: &str) -> bool {
if !lower.bytes().all(|c| c.is_ascii_lowercase()) {
return false;
}
let mut chars = lower.chars();
let capitalized: String = chars.next().into_iter().flat_map(char::to_uppercase).chain(chars).collect();
dict.check(&capitalized) || dict.check(&lower.to_uppercase())
let singular = lower.strip_suffix('s').unwrap_or(lower);
let Some(before_r) = singular.strip_suffix('r') else { return false };
let Some(before_er) = before_r.strip_suffix('e') else { return false };
// (stem, root the `-or` noun would be built on)
let mut stems = vec![(before_r.to_string(), before_er)];
if let Some(y) = before_er.strip_suffix('i') {
stems.push((format!("{y}y"), before_er));
} else if !before_er.ends_with('e') && !doubles_final_consonant(before_er) {
stems.push((before_er.to_string(), before_er));
}
stems.into_iter().any(|(stem, root)| {
stem.len() >= MIN_PART
&& (lemmas().contains(stem.as_str()) || self.user_word(&stem))
&& !english().check(&format!("{root}or"))
})
}
/// Two known words run together, each at least [`MIN_PART`] letters (or a
/// 3-letter programming term: `urlpath`). Proper nouns don't count.
fn compound(&self, lower: &str) -> bool {
if lower.len() < 6 || !lower.bytes().all(|c| c.is_ascii_lowercase()) || NOT_COMPOUNDS.contains(&lower) {
return false;
}
let part = |p: &str| {
(p.len() >= 3 && self.user_word(p)) || (p.len() >= MIN_PART && (english().check(p) || self.agent_noun(p)))
};
(3..=lower.len() - 3).any(|i| part(&lower[..i]) && part(&lower[i..])) && !near_word(lower)
}
/// Replacements for `word`, best first, in the word's case style.
@@ -155,19 +299,22 @@ impl Speller {
/// `cancelled` fires.
pub fn check(&self, text: &str, regions: &[Region], cancelled: &dyn Fn() -> bool) -> Option<Vec<Typo>> {
let mut spans = Vec::new();
let mut verdicts: HashMap<&str, bool> = HashMap::new();
let mut bad: Vec<WordSpan> = Vec::new();
let mut verdicts: HashMap<(&str, bool), bool> = HashMap::new();
let mut bad: Vec<(WordSpan, RegionKind)> = Vec::new();
for (i, r) in regions.iter().enumerate() {
if i % 64 == 0 && cancelled() {
return None;
}
spans.clear();
words(text, r.start, r.end, r.kind, &mut spans);
let name = r.kind == RegionKind::Name;
for w in &spans {
let word = &text[w.start..w.end];
let ok = *verdicts.entry(word).or_insert_with(|| self.is_correct(word));
let ok = *verdicts
.entry((word, name))
.or_insert_with(|| if name { self.is_correct_identifier(word) } else { self.is_correct(word) });
if !ok {
bad.push(*w);
bad.push((*w, r.kind));
}
}
if bad.len() >= MAX_TYPOS {
@@ -175,14 +322,15 @@ impl Speller {
break;
}
}
bad.sort_by_key(|w| w.start);
bad.dedup();
bad.sort_by_key(|(w, _)| w.start);
bad.dedup_by_key(|(w, _)| *w);
let mut index = Utf16Walker::new(text);
Some(
bad.into_iter()
.map(|w| Typo {
.map(|(w, kind)| Typo {
range: Range::new(index.pos(w.start), index.pos(w.end)),
word: text[w.start..w.end].to_string(),
context: kind.into(),
})
.collect(),
)
@@ -291,6 +439,118 @@ mod tests {
assert!(!s.is_correct("lenght"));
}
#[test]
fn agent_nouns_of_known_words() {
let s = Speller::default();
for ok in ["checkpointer", "Checkpointers", "serializer", "queriers", "tokenizer", "serializers", "pointer"] {
assert!(s.is_correct(ok), "{ok}");
}
// Real misspellings of the same shape stay flagged.
for bad in ["programer", "processer", "generater", "writter", "mesager", "begginer"] {
assert!(!s.is_correct(bad), "{bad}");
}
}
#[test]
fn compounds_only_in_identifiers() {
let s = Speller::default();
for ok in ["filepath", "dataframe", "username", "codebase", "pathname", "urlpath", "timestampfile"] {
assert!(s.is_correct_identifier(ok), "{ok}");
}
assert!(!s.is_correct("dataframe"));
for bad in ["eachother", "everytime", "publically", "mesage", "lenght", "recieve", "comming", "withold"] {
assert!(!s.is_correct_identifier(bad), "{bad}");
}
}
/// Common English misspellings must survive the derivation and compound rules.
#[test]
fn common_misspellings_stay_flagged() {
let s = Speller::default();
let typos = [
"accomodate",
"acheive",
"accross",
"adress",
"arguement",
"becuase",
"beleive",
"begining",
"calender",
"comming",
"commited",
"concious",
"definately",
"dependancy",
"enviroment",
"existance",
"explaination",
"fucntion",
"funtion",
"goverment",
"heigth",
"independant",
"intial",
"lenght",
"maintainance",
"mesage",
"neccessary",
"occured",
"occurence",
"paramter",
"persistant",
"posession",
"programer",
"recieve",
"refrence",
"relevent",
"retreive",
"seperate",
"seperator",
"succesful",
"tommorow",
"truely",
"untill",
"wich",
"widht",
"wierd",
"writting",
];
let accepted: Vec<_> = typos
.iter()
.filter(|t| s.is_correct(t) || s.is_correct_identifier(t))
.filter(|t| **t != "calender")
.collect();
assert!(accepted.is_empty(), "accepted: {accepted:?}");
}
#[test]
fn issue_42_python_example() {
let s = Speller::default();
let text = "# Initialize the checkpointer connection pool.\ncheckpointer_pool = None\nmemory_checkpointer = None\nmesage = 'hello'\n";
let regions = vec![
Region { start: 0, end: 46, kind: RegionKind::Comment },
Region { start: 47, end: 64, kind: RegionKind::Name },
Region { start: 72, end: 91, kind: RegionKind::Name },
Region { start: 99, end: 105, kind: RegionKind::Name },
];
assert_eq!(&text[99..105], "mesage");
let typos = s.check(text, &regions, &|| false).unwrap();
let found: Vec<_> = typos.iter().map(|t| (t.word.as_str(), t.context)).collect();
assert_eq!(found, [("mesage", TypoContext::Code)]);
}
#[test]
fn scope_filters_region_kinds() {
let comments_only = SpellScope { code: false, literals: false, comments: true };
assert!(comments_only.includes(RegionKind::Comment));
assert!(comments_only.includes(RegionKind::Prose));
assert!(!comments_only.includes(RegionKind::Name));
assert!(!comments_only.includes(RegionKind::String));
let parsed: SpellScope = serde_json::from_str(r#"{"literals":false}"#).unwrap();
assert_eq!(parsed, SpellScope { code: true, literals: false, comments: true });
}
#[test]
fn accepted_words_and_custom_dictionaries() {
let dir = std::env::temp_dir().join(format!("ide-spell-{}", std::process::id()));
+477
Переглянути файл
@@ -0,0 +1,477 @@
//! JDK downloads (IDEA's Download JDK): Eclipse Temurin builds from the
//! Adoptium API, unpacked into `<tools>/jdks/<vendor>-<version>` (or a chosen
//! location) where JDK discovery finds them. Parsing is pure so it is testable
//! without network.
use crate::platform::{Arch, Os, Platform};
use crate::process::{Emit, Http};
use crate::sources::Download;
use crate::{InstallEvent, InstallGuard, Tools, archive, clear_quarantine, fetch_verified};
use ide_core::error::ErrorKind;
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
const ADOPTIUM_API: &str = "https://api.adoptium.net/v3";
/// A JDK distribution the IDE can download.
#[derive(Clone, Debug, PartialEq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JdkVendor {
pub id: String,
pub name: String,
}
pub const TEMURIN: &str = "temurin";
pub fn vendors() -> Vec<JdkVendor> {
vec![JdkVendor { id: TEMURIN.into(), name: "Eclipse Temurin".into() }]
}
/// Java versions a vendor publishes.
#[derive(Clone, Debug, PartialEq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JdkReleases {
/// Feature versions, newest first.
pub versions: Vec<u32>,
/// The long-term-support ones among them.
pub lts: Vec<u32>,
/// The version offered first (the newest LTS).
pub recommended: u32,
}
/// A JDK the IDE downloaded.
#[derive(Clone, Debug, PartialEq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DownloadedJdk {
pub home: ide_core::IpcPath,
/// Full version, e.g. `25.0.1`.
pub version: String,
pub major: u32,
}
/// Where downloaded JDKs go by default.
pub fn jdks_dir(app_data: &Path) -> PathBuf {
crate::tools_dir(app_data).join("jdks")
}
fn proto(msg: impl Into<String>) -> IdeError {
IdeError::new(ErrorKind::Protocol, msg)
}
fn vendor_or_err(vendor: &str) -> IdeResult<()> {
if vendor == TEMURIN { Ok(()) } else { Err(IdeError::invalid(format!("unknown JDK vendor `{vendor}`"))) }
}
pub fn adoptium_releases_url() -> String {
format!("{ADOPTIUM_API}/info/available_releases")
}
#[derive(Deserialize)]
struct AvailableReleases {
available_releases: Vec<u32>,
#[serde(default)]
available_lts_releases: Vec<u32>,
#[serde(default)]
most_recent_lts: Option<u32>,
}
pub fn parse_releases(json: &str) -> IdeResult<JdkReleases> {
let r: AvailableReleases =
serde_json::from_str(json).map_err(|e| proto(format!("unexpected Adoptium response: {e}")))?;
let mut versions = r.available_releases;
versions.sort_unstable_by(|a, b| b.cmp(a));
versions.dedup();
let recommended = r
.most_recent_lts
.or_else(|| r.available_lts_releases.iter().copied().max())
.or_else(|| versions.first().copied())
.ok_or_else(|| proto("Adoptium lists no Java versions"))?;
Ok(JdkReleases { versions, lts: r.available_lts_releases, recommended })
}
fn adoptium_os(os: Os) -> &'static str {
match os {
Os::Mac => "mac",
Os::Linux => "linux",
Os::Windows => "windows",
}
}
fn adoptium_arch(arch: Arch) -> &'static str {
match arch {
Arch::X64 => "x64",
Arch::Arm64 => "aarch64",
}
}
/// The latest Temurin JDK build of Java `feature` for `platform`.
pub fn adoptium_assets_url(feature: u32, platform: Platform) -> String {
format!(
"{ADOPTIUM_API}/assets/latest/{feature}/hotspot?architecture={}&image_type=jdk&os={}&vendor=eclipse",
adoptium_arch(platform.arch),
adoptium_os(platform.os),
)
}
#[derive(Deserialize)]
struct Asset {
binary: Binary,
version: AssetVersion,
}
#[derive(Deserialize)]
struct Binary {
#[serde(default)]
image_type: Option<String>,
#[serde(default)]
heap_size: Option<String>,
#[serde(default)]
os: Option<String>,
package: Package,
}
#[derive(Deserialize)]
struct Package {
name: String,
link: String,
#[serde(default)]
checksum: Option<String>,
#[serde(default)]
size: Option<u64>,
}
#[derive(Deserialize)]
struct AssetVersion {
major: u32,
#[serde(default)]
minor: u32,
#[serde(default)]
security: u32,
#[serde(default)]
openjdk_version: Option<String>,
}
impl AssetVersion {
/// `25.0.1` (`openjdk_version` without its build; `1.8.0_472` style for Java 8).
fn display(&self) -> String {
let plain = || format!("{}.{}.{}", self.major, self.minor, self.security);
match &self.openjdk_version {
Some(v) => {
let v = v.split(['+', '-']).next().unwrap_or(v);
if v.is_empty() { plain() } else { v.to_owned() }
}
None => plain(),
}
}
}
/// The JDK archive (`.tar.gz` on macOS / Linux, `.zip` on Windows) in an Adoptium
/// `assets/latest` response; `None` when there is no build for the platform.
pub fn adoptium_pick(json: &str, platform: Platform) -> IdeResult<Option<(Download, u32)>> {
let assets: Vec<Asset> =
serde_json::from_str(json).map_err(|e| proto(format!("unexpected Adoptium response: {e}")))?;
let ext = if platform.os == Os::Windows { ".zip" } else { ".tar.gz" };
let os = adoptium_os(platform.os);
let found = assets.into_iter().find(|a| {
a.binary.image_type.as_deref().is_none_or(|t| t == "jdk")
&& a.binary.heap_size.as_deref().is_none_or(|h| h == "normal")
&& a.binary.os.as_deref().is_none_or(|o| o == os)
&& a.binary.package.name.ends_with(ext)
});
Ok(found.map(|a| {
let sha256 = a.binary.package.checksum.map(|c| c.trim().to_ascii_lowercase()).filter(|c| c.len() == 64);
(
Download {
version: a.version.display(),
name: a.binary.package.name,
url: a.binary.package.link,
size: a.binary.package.size,
sha256,
checksum_url: None,
},
a.version.major,
)
}))
}
/// Folder name of a downloaded JDK, as IDEA names them: `temurin-25.0.1`.
pub fn jdk_dir_name(vendor: &str, version: &str) -> String {
let safe: String =
version.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '_') { c } else { '-' }).collect();
format!("{vendor}-{safe}")
}
fn is_jdk_home(dir: &Path, platform: Platform) -> bool {
dir.join("release").is_file() && dir.join("bin").join(platform.exe("java")).is_file()
}
/// The JDK home inside an unpacked JDK: `dir` itself, `dir/Contents/Home`
/// (a macOS bundle), or either of those below one top-level folder
/// (`jdk-25.0.1+8/`, `jdk-25.0.1+8/Contents/Home`).
pub fn find_jdk_home(dir: &Path, platform: Platform) -> Option<PathBuf> {
let candidates = |d: &Path| [d.to_path_buf(), d.join("Contents").join("Home")];
if let Some(home) = candidates(dir).into_iter().find(|h| is_jdk_home(h, platform)) {
return Some(home);
}
let mut subdirs: Vec<PathBuf> = std::fs::read_dir(dir)
.ok()?
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.map(|e| e.path())
.collect();
subdirs.sort();
subdirs.iter().flat_map(|d| candidates(d)).find(|h| is_jdk_home(h, platform))
}
/// The directory to move into place: the archive's single top-level folder
/// holding the JDK, else everything that was unpacked.
fn unpacked_root(pkg: &Path, home: &Path) -> PathBuf {
match home.strip_prefix(pkg).ok().and_then(|rel| rel.components().next()) {
Some(first) if first.as_os_str() != "Contents" => pkg.join(first),
_ => pkg.to_path_buf(),
}
}
impl Tools {
fn http(&self) -> IdeResult<Http> {
Http::new(&self.system_path)
}
/// Java versions `vendor` publishes.
pub fn jdk_releases(&self, vendor: &str, cancel: &CancellationToken) -> IdeResult<JdkReleases> {
vendor_or_err(vendor)?;
parse_releases(&self.http()?.get_text(&adoptium_releases_url(), cancel)?)
}
/// Downloads the latest `vendor` JDK of Java `feature` into
/// `<location>/<vendor>-<version>` (`location` defaults to the tools' `jdks`
/// folder), verifying its SHA-256. A JDK already there is reused.
pub fn download_jdk(
&self,
vendor: &str,
feature: u32,
location: Option<&Path>,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<DownloadedJdk> {
vendor_or_err(vendor)?;
let _guard = InstallGuard::acquire(&format!("jdk-{vendor}-{feature}"))?;
let http = self.http()?;
let location = location.map(Path::to_path_buf).unwrap_or_else(|| self.root.join("jdks"));
emit(InstallEvent::Line { text: format!("Resolving the latest Eclipse Temurin {feature}…") });
let mut picked =
adoptium_pick(&http.get_text(&adoptium_assets_url(feature, self.platform), cancel)?, self.platform)?;
if picked.is_none() && self.platform.os == Os::Mac && self.platform.arch == Arch::Arm64 {
// Java 8 has no Apple Silicon build: the Intel one runs under Rosetta.
let intel = Platform { os: Os::Mac, arch: Arch::X64 };
picked = adoptium_pick(&http.get_text(&adoptium_assets_url(feature, intel), cancel)?, intel)?;
}
let (dl, major) = picked.ok_or_else(|| {
IdeError::unavailable(format!(
"Eclipse Temurin {feature} has no build for {:?} {:?}",
self.platform.os, self.platform.arch
))
})?;
let target = location.join(jdk_dir_name(vendor, &dl.version));
let done = |home: PathBuf| DownloadedJdk { home: home.into(), version: dl.version.clone(), major };
if let Some(home) = find_jdk_home(&target, self.platform) {
emit(InstallEvent::Line { text: format!("{} is already installed", target.display()) });
return Ok(done(home));
}
emit(InstallEvent::Line { text: format!("Downloading {} ({})", dl.name, dl.url) });
std::fs::create_dir_all(&location)?;
// Next to the target, so moving it into place never crosses file systems.
let staging = location.join(format!(".staging-{}", jdk_dir_name(vendor, &dl.version)));
let _ = std::fs::remove_dir_all(&staging);
std::fs::create_dir_all(&staging)?;
let result = (|| {
let archive = fetch_verified(&http, &dl, &staging, cancel, emit)?;
emit(InstallEvent::Line { text: "Extracting…".into() });
let pkg = staging.join("pkg");
archive::extract(&archive, archive::ArchiveKind::from_name(&dl.name), &pkg, "java")?;
let home = find_jdk_home(&pkg, self.platform)
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("no JDK found in {}", dl.name)))?;
if target.exists() {
std::fs::remove_dir_all(&target)?;
}
std::fs::rename(unpacked_root(&pkg, &home), &target)?;
clear_quarantine(&target);
find_jdk_home(&target, self.platform)
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("no JDK found in {}", target.display())))
})();
let _ = std::fs::remove_dir_all(&staging);
let home = result?;
emit(InstallEvent::Line { text: format!("Eclipse Temurin {} installed in {}", dl.version, home.display()) });
Ok(done(home))
}
}
#[cfg(test)]
mod tests {
use super::*;
const MAC_ARM: Platform = Platform { os: Os::Mac, arch: Arch::Arm64 };
const LINUX_X64: Platform = Platform { os: Os::Linux, arch: Arch::X64 };
const WIN_X64: Platform = Platform { os: Os::Windows, arch: Arch::X64 };
#[test]
fn releases() {
let json = r#"{"available_lts_releases":[8,11,17,21,25],"available_releases":[8,11,16,17,21,24,25,26],
"most_recent_feature_release":26,"most_recent_lts":25,"tip_version":27}"#;
let r = parse_releases(json).unwrap();
assert_eq!(r.versions, [26, 25, 24, 21, 17, 16, 11, 8]);
assert_eq!(r.lts, [8, 11, 17, 21, 25]);
assert_eq!(r.recommended, 25);
assert!(parse_releases("{}").is_err());
}
#[test]
fn asset_urls() {
assert_eq!(
adoptium_assets_url(25, MAC_ARM),
"https://api.adoptium.net/v3/assets/latest/25/hotspot?architecture=aarch64&image_type=jdk&os=mac&vendor=eclipse"
);
assert_eq!(
adoptium_assets_url(21, WIN_X64),
"https://api.adoptium.net/v3/assets/latest/21/hotspot?architecture=x64&image_type=jdk&os=windows&vendor=eclipse"
);
assert!(adoptium_assets_url(17, LINUX_X64).contains("os=linux"));
}
fn asset(name: &str, os: &str, heap: &str, checksum: &str) -> String {
format!(
r#"{{"binary":{{"architecture":"x64","heap_size":"{heap}","image_type":"jdk","os":"{os}",
"installer":{{"name":"x.msi","link":"https://e/x.msi","checksum":"00"}},
"package":{{"name":"{name}","link":"https://e/{name}","checksum":"{checksum}","size":1234}}}},
"release_name":"jdk-25.0.1+8","vendor":"eclipse",
"version":{{"major":25,"minor":0,"security":1,"build":8,"openjdk_version":"25.0.1+8-LTS"}}}}"#
)
}
#[test]
fn picks_the_platform_archive() {
let sum = "36DC14D797AAFF6D89AAB302CD053FDBA6207DFDCF772052FA7B023A94B0E857";
let json = format!(
"[{},{},{}]",
asset("OpenJDK25U-jdk_x64_windows_hotspot_25.0.1_8.zip", "windows", "large", sum),
asset("OpenJDK25U-jdk_x64_windows_hotspot_25.0.1_8.zip", "windows", "normal", sum),
asset("OpenJDK25U-jdk_x64_linux_hotspot_25.0.1_8.tar.gz", "linux", "normal", sum),
);
let (dl, major) = adoptium_pick(&json, WIN_X64).unwrap().unwrap();
assert_eq!(dl.name, "OpenJDK25U-jdk_x64_windows_hotspot_25.0.1_8.zip");
assert_eq!(dl.url, "https://e/OpenJDK25U-jdk_x64_windows_hotspot_25.0.1_8.zip");
assert_eq!(dl.sha256.as_deref(), Some(sum.to_ascii_lowercase().as_str()));
assert_eq!((dl.version.as_str(), major, dl.size), ("25.0.1", 25, Some(1234)));
let (dl, _) = adoptium_pick(&json, LINUX_X64).unwrap().unwrap();
assert!(dl.name.ends_with(".tar.gz"));
// No build for the platform (Java 8 on Apple Silicon): an empty list.
assert_eq!(adoptium_pick("[]", MAC_ARM).unwrap(), None);
assert_eq!(adoptium_pick(&json, MAC_ARM).unwrap(), None);
assert!(adoptium_pick("{\"errorMessage\":\"x\"}", MAC_ARM).is_err());
}
#[test]
fn java_8_versions_and_dir_names() {
let v = AssetVersion { major: 8, minor: 0, security: 472, openjdk_version: Some("1.8.0_472-b08".into()) };
assert_eq!(v.display(), "1.8.0_472");
let v = AssetVersion { major: 21, minor: 0, security: 9, openjdk_version: None };
assert_eq!(v.display(), "21.0.9");
assert_eq!(jdk_dir_name(TEMURIN, "25.0.1"), "temurin-25.0.1");
assert_eq!(jdk_dir_name(TEMURIN, "1.8.0_472"), "temurin-1.8.0_472");
}
fn fake_jdk(home: &Path, platform: Platform) {
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("release"), "JAVA_VERSION=\"25.0.1\"\n").unwrap();
std::fs::write(home.join("bin").join(platform.exe("java")), "").unwrap();
}
#[test]
fn finds_the_home_of_each_archive_layout() {
let tmp = tempfile::tempdir().unwrap();
// macOS: jdk-25.0.1+8/Contents/Home
let mac = tmp.path().join("mac");
fake_jdk(&mac.join("jdk-25.0.1+8/Contents/Home"), MAC_ARM);
std::fs::create_dir_all(mac.join("jdk-25.0.1+8/Contents/MacOS")).unwrap();
let home = find_jdk_home(&mac, MAC_ARM).unwrap();
assert_eq!(home, mac.join("jdk-25.0.1+8/Contents/Home"));
assert_eq!(unpacked_root(&mac, &home), mac.join("jdk-25.0.1+8"));
// Once moved into place, the bundle itself.
assert_eq!(find_jdk_home(&mac.join("jdk-25.0.1+8"), MAC_ARM).unwrap(), mac.join("jdk-25.0.1+8/Contents/Home"));
// Linux tar.gz / Windows zip: jdk-25.0.1+8/bin/java[.exe]
for platform in [LINUX_X64, WIN_X64] {
let dir = tmp.path().join(format!("{:?}", platform.os));
fake_jdk(&dir.join("jdk-25.0.1+8"), platform);
let home = find_jdk_home(&dir, platform).unwrap();
assert_eq!(home, dir.join("jdk-25.0.1+8"));
assert_eq!(unpacked_root(&dir, &home), dir.join("jdk-25.0.1+8"));
}
// Without a top-level folder, everything unpacked is the JDK.
let flat = tmp.path().join("flat");
fake_jdk(&flat, LINUX_X64);
assert_eq!(find_jdk_home(&flat, LINUX_X64).unwrap(), flat);
assert_eq!(unpacked_root(&flat, &flat), flat);
let bundle = tmp.path().join("bundle");
fake_jdk(&bundle.join("Contents/Home"), MAC_ARM);
assert_eq!(unpacked_root(&bundle, &bundle.join("Contents/Home")), bundle);
// A Windows layout isn't a JDK for Linux (no `bin/java`), nor is a folder without `release`.
assert_eq!(find_jdk_home(&tmp.path().join("Windows"), LINUX_X64), None);
std::fs::create_dir_all(tmp.path().join("norelease/bin")).unwrap();
std::fs::write(tmp.path().join("norelease/bin/java"), "").unwrap();
assert_eq!(find_jdk_home(&tmp.path().join("norelease"), LINUX_X64), None);
}
#[test]
fn unknown_vendors_are_refused() {
let tools = Tools::with_paths(PathBuf::from("/nonexistent"), Default::default(), LINUX_X64);
let err = tools.download_jdk("acme", 25, None, &CancellationToken::new(), &|_| {}).unwrap_err();
assert_eq!(err.kind, ErrorKind::InvalidInput, "{err:?}");
}
/// Downloads a real JDK from Adoptium: `OPENIDEA_LIVE_JDK=25 cargo nextest run -p ide-tools live_download`;
/// `OPENIDEA_LIVE_JDK_OS=windows|linux` fetches and unpacks another platform's archive (not run).
#[test]
fn live_download() {
let Some(feature) = std::env::var("OPENIDEA_LIVE_JDK").ok().and_then(|v| v.parse::<u32>().ok()) else {
return;
};
let tmp = tempfile::tempdir().unwrap();
let other = match std::env::var("OPENIDEA_LIVE_JDK_OS").as_deref() {
Ok("windows") => Some(WIN_X64),
Ok("linux") => Some(LINUX_X64),
_ => None,
};
if let Some(platform) = other {
let tools = Tools::with_paths(crate::tools_dir(tmp.path()), crate::default_search_path(), platform);
let jdk = tools.download_jdk(TEMURIN, feature, None, &CancellationToken::new(), &|_| {}).unwrap();
let home = jdk.home.into_path_buf();
eprintln!("{}", home.display());
assert!(home.join("bin").join(platform.exe("java")).is_file());
assert_eq!(home.parent(), Some(jdks_dir(tmp.path()).as_path()), "no Contents/Home outside macOS");
return;
}
let tools = Tools::new(tmp.path());
let releases = tools.jdk_releases(TEMURIN, &CancellationToken::new()).unwrap();
assert!(releases.versions.contains(&feature), "{releases:?}");
let emit = |e: InstallEvent| {
if let InstallEvent::Line { text } = e {
eprintln!("{text}");
}
};
let jdk = tools.download_jdk(TEMURIN, feature, None, &CancellationToken::new(), &emit).unwrap();
let home = jdk.home.clone().into_path_buf();
assert!(home.starts_with(jdks_dir(tmp.path())), "{}", home.display());
let out = std::process::Command::new(home.join("bin").join(Platform::current().exe("java")))
.arg("-version")
.output()
.unwrap();
let text = String::from_utf8_lossy(&out.stderr);
eprintln!("{text}");
assert!(out.status.success() && text.contains("Temurin"), "{text}");
// Downloading again reuses it.
let again = tools.download_jdk(TEMURIN, feature, None, &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(again.home, jdk.home);
}
}
+93 -38
Переглянути файл
@@ -10,6 +10,7 @@
//! [`tools_bin_dirs`] on the process `PATH` at startup.
pub mod archive;
pub mod jdk;
pub mod platform;
mod process;
pub mod registry;
@@ -90,6 +91,14 @@ struct Manifest {
const MANIFEST: &str = ".openidea-tool.json";
/// `typescript@<7` → `typescript`, `@vue/language-server` unchanged.
fn npm_name(spec: &str) -> &str {
match spec[1..].find('@') {
Some(i) => &spec[..i + 1],
None => spec,
}
}
pub fn tools_dir(app_data: &Path) -> PathBuf {
app_data.join("tools")
}
@@ -275,6 +284,8 @@ pub struct Tools {
platform: Platform,
/// Executables chosen in settings, by command.
custom: BTreeMap<String, PathBuf>,
/// Executables found outside the search path (app bundles), by command.
found: BTreeMap<String, PathBuf>,
}
impl Tools {
@@ -288,7 +299,7 @@ impl Tools {
let system: Vec<PathBuf> = std::env::split_paths(&search_path).filter(|d| !ours.contains(d)).collect();
let system_path = std::env::join_paths(&system).unwrap_or_default();
let child_path = std::env::join_paths(ours.iter().chain(system.iter())).unwrap_or_default();
Self { root, system_path, child_path, platform, custom: BTreeMap::new() }
Self { root, system_path, child_path, platform, custom: BTreeMap::new(), found: BTreeMap::new() }
}
/// Reports the executables chosen in settings (command → path) as the tools' location.
@@ -297,6 +308,12 @@ impl Tools {
self
}
/// Reports executables located outside the search path (command → path) as on the PATH.
pub fn with_found_paths(mut self, found: BTreeMap<String, PathBuf>) -> Self {
self.found = found;
self
}
pub fn root(&self) -> &Path {
&self.root
}
@@ -349,6 +366,17 @@ impl Tools {
json.get("version")?.as_str().map(String::from)
}
/// Whether an installed npm tool other than `tool` also installs `package`.
fn npm_dependency_in_use(&self, tool: &str, package: &str) -> bool {
TOOLS.iter().any(|t| match t.method {
Method::Npm { packages } if t.name != tool => {
packages.iter().skip(1).any(|p| npm_name(p) == package)
&& self.npm_package_version(npm_name(packages[0])).is_some()
}
_ => false,
})
}
fn query_version(&self, spec: &ToolSpec, found: &Path) -> Option<String> {
let (cmd, args) = spec.version?;
let sibling = found.parent().and_then(|d| self.exe_in(d, cmd));
@@ -409,7 +437,7 @@ impl Tools {
let Some(spec) = spec else {
let u = usage?;
let command = u.command.clone()?;
let path = self.which(&command);
let path = self.which(&command).or_else(|| self.found.get(&command).cloned());
return Some(ToolInfo {
name: name.to_string(),
display_name: name.to_string(),
@@ -518,7 +546,7 @@ impl Tools {
let managed = managed_bin_dir(&self.root, spec, self.platform).and_then(|d| self.exe_in(&d, main));
if let Some(path) = managed {
let version = match spec.method {
Method::Npm { packages } => self.npm_package_version(packages[0]),
Method::Npm { packages } => self.npm_package_version(npm_name(packages[0])),
_ => self.manifest(spec.name).and_then(|m| m.version),
}
.or_else(|| self.query_version(spec, &path));
@@ -644,7 +672,7 @@ impl Tools {
let (manager, pnpm) = self.npm_manager()?;
self.ensure_package_json()?;
let mut c = self.command(manager);
let specs = packages.iter().map(|p| format!("{p}@latest"));
let specs = packages.iter().map(|p| if npm_name(p) == *p { format!("{p}@latest") } else { p.to_string() });
if pnpm {
c.arg("add").arg("--dir").arg(&self.root).args(specs);
} else {
@@ -929,33 +957,7 @@ impl Tools {
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let archive = staging.join(&dl.name);
http.download(&dl.url, &archive, dl.size, cancel, emit)?;
let expected = match (&dl.sha256, &dl.checksum_url) {
(Some(h), _) => Some(h.clone()),
(None, Some(url)) => match http.get_text(url, cancel) {
Ok(text) => sources::parse_checksum(&text, &dl.name),
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
Err(_) => None,
},
(None, None) => None,
};
match expected {
Some(expected) => {
let actual = sources::sha256_file(&archive)?;
if actual != expected {
return Err(IdeError::new(
ErrorKind::Io,
format!("checksum mismatch for {}: expected {expected}, got {actual}", dl.name),
));
}
emit(InstallEvent::Line { text: "Checksum verified (SHA-256)".into() });
}
None => emit(InstallEvent::Line { text: "No checksum published; skipping verification".into() }),
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let archive = fetch_verified(http, dl, staging, cancel, emit)?;
emit(InstallEvent::Line { text: "Extracting…".into() });
let pkg = staging.join("pkg");
let kind = archive::ArchiveKind::from_name(&dl.name);
@@ -999,11 +1001,8 @@ impl Tools {
archive::link_executable(&bin, main, &target)?;
}
}
#[cfg(target_os = "macos")]
{
// Downloads made by the IDE itself are not quarantined, but archives may carry the flag.
let _ = Command::new("xattr").args(["-dr", "com.apple.quarantine"]).arg(&final_dir).output();
}
// Downloads made by the IDE itself are not quarantined, but archives may carry the flag.
clear_quarantine(&final_dir);
self.write_manifest(spec.name, &Manifest { version: Some(dl.version.clone()), source: Some(dl.url.clone()) })
}
@@ -1038,12 +1037,19 @@ impl Tools {
}
Method::Npm { packages } => {
if self.root.join("node_modules").exists() {
// Shared dependencies (`typescript`) stay while another installed tool needs them.
let packages: Vec<&str> = packages
.iter()
.enumerate()
.filter(|(i, p)| *i == 0 || !self.npm_dependency_in_use(spec.name, npm_name(p)))
.map(|(_, p)| npm_name(p))
.collect();
let (manager, pnpm) = self.npm_manager()?;
let mut c = self.command(manager);
if pnpm {
c.arg("remove").arg("--dir").arg(&self.root).args(packages);
c.arg("remove").arg("--dir").arg(&self.root).args(&packages);
} else {
c.args(["uninstall", "--no-fund", "--no-audit", "--prefix"]).arg(&self.root).args(packages);
c.args(["uninstall", "--no-fund", "--no-audit", "--prefix"]).arg(&self.root).args(&packages);
}
c.current_dir(&self.root);
run_streamed(c, &cancel, &quiet)?;
@@ -1065,5 +1071,54 @@ impl Tools {
}
}
/// Downloads `dl` into `staging` and checks its SHA-256 when one is published;
/// returns the downloaded file.
fn fetch_verified(
http: &Http,
dl: &sources::Download,
staging: &Path,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<PathBuf> {
let archive = staging.join(&dl.name);
http.download(&dl.url, &archive, dl.size, cancel, emit)?;
let expected = match (&dl.sha256, &dl.checksum_url) {
(Some(h), _) => Some(h.clone()),
(None, Some(url)) => match http.get_text(url, cancel) {
Ok(text) => sources::parse_checksum(&text, &dl.name),
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
Err(_) => None,
},
(None, None) => None,
};
match expected {
Some(expected) => {
let actual = sources::sha256_file(&archive)?;
if actual != expected {
return Err(IdeError::new(
ErrorKind::Io,
format!("checksum mismatch for {}: expected {expected}, got {actual}", dl.name),
));
}
emit(InstallEvent::Line { text: "Checksum verified (SHA-256)".into() });
}
None => emit(InstallEvent::Line { text: "No checksum published; skipping verification".into() }),
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Ok(archive)
}
/// Removes the quarantine flag archives may carry, so macOS runs what was unpacked.
fn clear_quarantine(dir: &Path) {
#[cfg(target_os = "macos")]
{
let _ = Command::new("xattr").args(["-dr", "com.apple.quarantine"]).arg(dir).output();
}
#[cfg(not(target_os = "macos"))]
let _ = dir;
}
#[cfg(test)]
mod tests;
+7 -3
Переглянути файл
@@ -112,6 +112,10 @@ const fn ver(cmd: &'static str) -> Option<(&'static str, &'static [&'static str]
Some((cmd, &["--version"]))
}
/// The TypeScript these npm servers load as a library (`tsserver.js`, `ts.server`):
/// TypeScript 7 (the native port) ships neither, and `@latest` resolves to it.
pub const TYPESCRIPT: &str = "typescript@<7";
pub static TOOLS: &[ToolSpec] = &[
ToolSpec {
name: "rust-analyzer",
@@ -138,7 +142,7 @@ pub static TOOLS: &[ToolSpec] = &[
display: "typescript-language-server",
kind: LanguageServer,
commands: &["typescript-language-server"],
method: Method::Npm { packages: &["typescript-language-server", "typescript"] },
method: Method::Npm { packages: &["typescript-language-server", TYPESCRIPT] },
version: ver("typescript-language-server"),
homepage: "https://github.com/typescript-language-server/typescript-language-server",
needs: &[],
@@ -228,7 +232,7 @@ pub static TOOLS: &[ToolSpec] = &[
display: "Svelte Language Server",
kind: LanguageServer,
commands: &["svelteserver"],
method: Method::Npm { packages: &["svelte-language-server"] },
method: Method::Npm { packages: &["svelte-language-server", TYPESCRIPT] },
version: V,
homepage: "https://github.com/sveltejs/language-tools",
needs: &[],
@@ -238,7 +242,7 @@ pub static TOOLS: &[ToolSpec] = &[
display: "Vue Language Server",
kind: LanguageServer,
commands: &["vue-language-server"],
method: Method::Npm { packages: &["@vue/language-server"] },
method: Method::Npm { packages: &["@vue/language-server", TYPESCRIPT] },
version: V,
homepage: "https://github.com/vuejs/language-tools",
needs: &[],
+48
Переглянути файл
@@ -272,6 +272,54 @@ echo "added 1 package""#,
assert!(env.root.join("package.json").exists());
}
/// Servers that load TypeScript as a library get one with its JS API: `@latest`
/// is TypeScript 7 (native, no `ts.server`), which crashed vue-language-server (#25).
/// Uninstalling one keeps the TypeScript another installed server still uses.
#[cfg(unix)]
#[test]
fn npm_typescript_is_pinned_and_shared() {
let env = Env::new();
let log = env.root.parent().unwrap().join("npm-args.txt");
env.script(
&env.sys,
"npm",
&format!(
r#"echo "$@" >> '{log}'
prefix=""; for a in "$@"; do [ "$prev" = "--prefix" ] && prefix="$a"; prev="$a"; done
[ "$1" = "install" ] || exit 0
/bin/mkdir -p "$prefix/node_modules/.bin"
for a in "$@"; do case "$a" in
typescript-language-server@latest) n=typescript-language-server;;
@vue/language-server@latest) n=vue-language-server; d=@vue/language-server;;
*) continue;;
esac
d="${{d:-$n}}"; /bin/mkdir -p "$prefix/node_modules/$d"
echo '{{"version":"1.0.0"}}' > "$prefix/node_modules/$d/package.json"
printf '#!/bin/sh\necho 1.0.0\n' > "$prefix/node_modules/.bin/$n"; /bin/chmod +x "$prefix/node_modules/.bin/$n"; d=""
done"#,
log = log.display()
),
);
let tools = env.tools();
for name in ["vue-language-server", "typescript-language-server"] {
assert_eq!(
tools.install(name, &langs(), &CancellationToken::new(), &|_| {}).unwrap().status,
ToolStatus::Installed
);
}
let installs = fs::read_to_string(&log).unwrap();
for line in installs.lines() {
assert!(line.contains("typescript@<7") && !line.contains("typescript@latest"), "{line}");
}
assert!(installs.contains("@vue/language-server@latest"), "{installs}");
fs::write(&log, "").unwrap();
tools.uninstall("vue-language-server", &langs()).unwrap();
let uninstall = fs::read_to_string(&log).unwrap();
assert!(uninstall.contains("uninstall") && uninstall.contains("@vue/language-server"), "{uninstall}");
assert!(!uninstall.contains("typescript"), "typescript-language-server still needs it: {uninstall}");
}
#[test]
fn installed_bundle_is_detected_and_resolvable() {
let env = Env::new();
+79 -4
Переглянути файл
@@ -1,7 +1,7 @@
//! Commit history (topological walk) and per-commit changed files via gitoxide.
use crate::repo::{gx, resolve, to_string};
use crate::{ChangeKind, ChangedFile, Commit, LogOrder, LogQuery, Repo};
use crate::{ChangeKind, ChangedFile, Commit, LogOrder, LogQuery, Repo, RevisionChange};
use gix::ObjectId;
use gix::bstr::ByteSlice;
use ide_core::{IdeError, IdeResult};
@@ -423,11 +423,24 @@ fn path_entry(
pub(crate) fn commit_files(r: &Repo, rev: &str) -> IdeResult<Vec<ChangedFile>> {
let repo = r.gix()?;
let id = resolve(&repo, rev)?;
Ok(first_parent_changes(&repo, rev)?.files)
}
struct CommitChanges {
id: ObjectId,
parent: Option<ObjectId>,
files: Vec<ChangedFile>,
}
/// Files changed by `rev` relative to its first parent (renames detected), sorted by path.
fn first_parent_changes(repo: &gix::Repository, rev: &str) -> IdeResult<CommitChanges> {
let id = resolve(repo, rev)?;
let commit = repo.find_object(id).map_err(gx)?.peel_to_commit().map_err(gx)?;
let id = commit.id;
let parent = commit.parent_ids().next().map(|p| p.detach());
let new_tree = commit.tree().map_err(gx)?;
let old_tree = match commit.parent_ids().next() {
Some(p) => Some(repo.find_commit(p.detach()).map_err(gx)?.tree().map_err(gx)?),
let old_tree = match parent {
Some(p) => Some(repo.find_commit(p).map_err(gx)?.tree().map_err(gx)?),
None => None,
};
let mut opts = gix::diff::Options::default();
@@ -456,5 +469,67 @@ pub(crate) fn commit_files(r: &Repo, rev: &str) -> IdeResult<Vec<ChangedFile>> {
out.push(file);
}
out.sort_by(|a, b| a.path.cmp(&b.path));
Ok(CommitChanges { id, parent, files: out })
}
/// One file's change accumulated over several commits.
struct Merged {
/// Commit before the first change and the file's path there; `None` when it was added.
before: Option<(String, String)>,
/// Commit of the last change; `None` when it was deleted.
after: Option<String>,
path: String,
}
/// Combined changes of `commits` (oldest first), merged like IDEA merges a multi-commit Git
/// Log selection: per file, the state before the first selected commit that touched it ↔
/// after the last one, following renames. Files added and then deleted drop out.
pub(crate) fn commits_changes(r: &Repo, commits: &[String]) -> IdeResult<Vec<RevisionChange>> {
let repo = r.gix()?;
let mut merged: Vec<Merged> = Vec::new();
let mut seen = HashSet::new();
for rev in commits {
let c = first_parent_changes(&repo, rev)?;
if !seen.insert(c.id) {
continue;
}
let id = c.id.to_string();
for f in c.files {
let from = match f.kind {
ChangeKind::Renamed => f.old_path.as_deref().unwrap_or(&f.path),
_ => &f.path,
};
// A live entry at the path this change starts from, else a deleted one being re-added.
let existing = merged
.iter()
.position(|m| m.after.is_some() && m.path == from)
.or_else(|| merged.iter().position(|m| m.after.is_none() && m.path == f.path));
let i = existing.unwrap_or_else(|| {
let before = match (f.kind, c.parent) {
(ChangeKind::Added, _) | (_, None) => None,
(_, Some(p)) => Some((p.to_string(), from.to_owned())),
};
merged.push(Merged { before, after: None, path: f.path.clone() });
merged.len() - 1
});
let entry = &mut merged[i];
entry.after = (f.kind != ChangeKind::Deleted).then(|| id.clone());
entry.path = f.path;
}
}
let mut out: Vec<RevisionChange> = merged
.into_iter()
.filter_map(|m| {
let (kind, path, old_path) = match (&m.before, &m.after) {
(None, None) => return None,
(None, Some(_)) => (ChangeKind::Added, m.path, None),
(Some((_, old)), None) => (ChangeKind::Deleted, old.clone(), None),
(Some((_, old)), Some(_)) if *old != m.path => (ChangeKind::Renamed, m.path, Some(old.clone())),
(Some(_), Some(_)) => (ChangeKind::Modified, m.path, None),
};
Some(RevisionChange { path, kind, old_path, before: m.before.map(|(rev, _)| rev), after: m.after })
})
.collect();
out.sort_by(|a, b| a.path.cmp(&b.path));
Ok(out)
}
+30
Переглянути файл
@@ -205,6 +205,21 @@ pub struct ChangedFile {
pub old_path: Option<String>,
}
/// A file changed across several commits: its content at `before` ↔ at `after`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RevisionChange {
/// Repository-relative path after the change (before it, for a deletion).
pub path: String,
pub kind: ChangeKind,
/// Path at `before`, for a rename.
pub old_path: Option<String>,
/// Commit holding the old content; `None` when the file was added.
pub before: Option<String>,
/// Commit holding the new content; `None` when the file was deleted.
pub after: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Stash {
@@ -492,6 +507,11 @@ impl Repo {
pub fn branch_info(&self) -> IdeResult<BranchInfo> {
refs::branch_info(self)
}
/// Current branch (short name; `None` when detached) and HEAD commit, without
/// upstream tracking (cheap enough to call for every repository on each refresh).
pub fn head(&self) -> IdeResult<(Option<String>, Option<String>)> {
refs::head(&self.gix()?)
}
/// Merge / rebase / cherry-pick… in progress (cheap: no ref walking).
pub fn operation(&self) -> IdeResult<Option<String>> {
Ok(refs::operation(&self.gix()?))
@@ -546,6 +566,11 @@ impl Repo {
pub fn commit_files(&self, commit: &str) -> IdeResult<Vec<ChangedFile>> {
history::commit_files(self, commit)
}
/// Combined changes of several commits (oldest first): per file, before the first commit
/// that touched it ↔ after the last one (IDEA's multi-commit Git Log selection).
pub fn commits_changes(&self, commits: &[String]) -> IdeResult<Vec<RevisionChange>> {
history::commits_changes(self, commits)
}
/// Local and remote branches; the current branch first, then most recent first.
pub fn branches(&self) -> IdeResult<Vec<Branch>> {
refs::branches(self)
@@ -801,6 +826,11 @@ impl Repo {
pub fn diff_with_worktree(&self, rev: &str) -> IdeResult<Vec<ChangedFile>> {
ops::diff_with_worktree(self, rev)
}
/// `(repo-relative path, added lines, deleted lines)` of the tracked files whose
/// working-tree content differs from `rev`.
pub fn numstat_with_worktree(&self, rev: &str) -> IdeResult<Vec<(String, u32, u32)>> {
ops::numstat_with_worktree(self, rev)
}
// ---- patches and shelf ----
+29
Переглянути файл
@@ -349,6 +349,26 @@ pub(crate) fn diff_with_worktree(r: &Repo, rev: &str) -> IdeResult<Vec<ChangedFi
Ok(parse_name_status(&out.stdout_str()))
}
/// Added / deleted line counts of tracked files whose working-tree content differs from `rev`
/// (`git diff --numstat`); binary files count 0.
pub(crate) fn numstat_with_worktree(r: &Repo, rev: &str) -> IdeResult<Vec<(String, u32, u32)>> {
check_commits(&[rev.to_string()])?;
let out = run(r.root(), &["diff", "--numstat", "-z", "--no-renames", "--no-ext-diff", rev, "--"], None)?;
Ok(parse_numstat(&out.stdout_str()))
}
pub(crate) fn parse_numstat(text: &str) -> Vec<(String, u32, u32)> {
text.split('\0')
.filter_map(|rec| {
let mut parts = rec.splitn(3, '\t');
let added = parts.next()?.parse().unwrap_or(0);
let deleted = parts.next()?.parse().unwrap_or(0);
let path = parts.next().filter(|p| !p.is_empty())?;
Some((path.to_owned(), added, deleted))
})
.collect()
}
/// Files that differ between two revisions (Update Project's "N files updated").
pub(crate) fn diff_revisions(r: &Repo, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
check_commits(&[from.to_string(), to.to_string()])?;
@@ -402,4 +422,13 @@ mod tests {
]
);
}
#[test]
fn numstat_parsing() {
let got = parse_numstat("3\t1\tsrc/a.rs\0-\t-\timg.png\0\x30\t7\tdir/b c.txt\0");
assert_eq!(
got,
vec![("src/a.rs".to_owned(), 3, 1), ("img.png".to_owned(), 0, 0), ("dir/b c.txt".to_owned(), 0, 7)]
);
}
}
+5
Переглянути файл
@@ -30,6 +30,11 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
Ok(info)
}
pub(crate) fn head(repo: &gix::Repository) -> IdeResult<(Option<String>, Option<String>)> {
let name = repo.head_name().map_err(gx)?.map(|n| to_string(n.as_ref().shorten()));
Ok((name, repo.head_id().ok().map(|id| id.to_string())))
}
pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
use gix::state::InProgress::*;
let op = match repo.state()? {
+5
Переглянути файл
@@ -120,6 +120,11 @@ fn merge_with_options_and_rebase_onto() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"], None);
// Repo operations spawn their own Git commands, so command-local `-c`
// options in the helper do not supply their committer identity.
git(dir, &["config", "user.name", "Test"], None);
git(dir, &["config", "user.email", "[email protected]"], None);
git(dir, &["config", "commit.gpgsign", "false"], None);
let base = commit(dir, "a.txt", "base", 1000);
git(dir, &["checkout", "-q", "-b", "feature"], None);
let f1 = commit(dir, "f.txt", "f1", 2000);
+63
Переглянути файл
@@ -543,6 +543,67 @@ fn commit_files_kinds() {
assert!(repo.commit_files("HEAD").unwrap().len() == 4);
}
/// IDEA's multi-commit Git Log selection: per file, before the first commit touching it ↔
/// after the last one, contiguous or not.
#[test]
fn commits_changes_merge_selected_commits() {
let fx = Fixture::new();
fx.write("a.txt", "a0\n");
fx.write("b.txt", "b0\n");
fx.write("gone.txt", "g\n");
fx.write("move.txt", "a fairly long line of content\nanother line\nand a third\n");
let c0 = fx.commit_all("c0");
fx.write("a.txt", "a1\n");
fx.write("tmp.txt", "t\n");
let c1 = fx.commit_all("c1");
fx.write("b.txt", "b2\n");
fx.git(&["mv", "move.txt", "moved.txt"]);
let c2 = fx.commit_all("c2");
fx.write("a.txt", "a3\n");
std::fs::remove_file(fx.path("tmp.txt")).unwrap();
std::fs::remove_file(fx.path("gone.txt")).unwrap();
std::fs::create_dir(fx.path("dir")).unwrap();
fx.git(&["mv", "moved.txt", "dir/final.txt"]);
let c3 = fx.commit_all("c3");
let repo = fx.repo();
let changes = |ids: &[&String]| {
let ids: Vec<String> = ids.iter().map(|s| (*s).clone()).collect();
// Sorted by path.
repo.commits_changes(&ids)
.unwrap()
.into_iter()
.map(|c| (c.path, c.kind, c.old_path, c.before, c.after))
.collect::<Vec<_>>()
};
let s = |x: &String| Some(x.clone());
// Contiguous c1..c3: tmp.txt added then deleted drops out; the rename chain collapses.
assert_eq!(
changes(&[&c1, &c2, &c3]),
vec![
("a.txt".into(), ChangeKind::Modified, None, s(&c0), s(&c3)),
("b.txt".into(), ChangeKind::Modified, None, s(&c1), s(&c2)),
("dir/final.txt".into(), ChangeKind::Renamed, Some("move.txt".into()), s(&c1), s(&c3)),
("gone.txt".into(), ChangeKind::Deleted, None, s(&c2), None),
]
);
// Non-contiguous c1 + c3: each file from before its first selected change.
assert_eq!(
changes(&[&c1, &c3]),
vec![
("a.txt".into(), ChangeKind::Modified, None, s(&c0), s(&c3)),
("dir/final.txt".into(), ChangeKind::Renamed, Some("moved.txt".into()), s(&c2), s(&c3)),
("gone.txt".into(), ChangeKind::Deleted, None, s(&c2), None),
]
);
// The root commit has no parent: everything is added; a duplicate id counts once.
let root = changes(&[&c0, &c0]);
assert_eq!(root.len(), 4);
assert!(root.iter().all(|c| c.1 == ChangeKind::Added && c.3.is_none() && c.4 == s(&c0)));
// A single commit matches its own changed files.
assert_eq!(changes(&[&c2]).len(), repo.commit_files(&c2).unwrap().len());
}
#[test]
fn file_at_revisions_and_index() {
let fx = Fixture::new();
@@ -804,6 +865,7 @@ fn checkout_create_detached_delete_rebase() {
repo.checkout("topic", true).unwrap();
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
assert_eq!(repo.head().unwrap(), (Some("topic".to_string()), Some(c1.clone())));
fx.write("t", "topic\n");
fx.commit_all("topic work");
repo.checkout("main", false).unwrap();
@@ -818,6 +880,7 @@ fn checkout_create_detached_delete_rebase() {
let info = repo.branch_info().unwrap();
assert_eq!(info.head, None);
assert_eq!(info.head_commit.as_deref(), Some(c1.as_str()));
assert_eq!(repo.head().unwrap(), (None, Some(c1.clone())));
assert!(
repo.log(&LogQuery { branch: Some("HEAD".into()), ..Default::default() }).unwrap()[0]
.refs
+82
Переглянути файл
@@ -0,0 +1,82 @@
# 核心体验运行验收补测(2026-10-25)
本轮按用户缩小后的“核心体验”范围执行,**27个明确场景:修复复测后27通过、0失败**。这不是原94项清单全量完成声明;首轮发现的中文漏译及原清单未完成项仍保留。
实际版本:`d3feb05`(功能提交 `1e00ea5` 加版本更新)。macOS 原生调试应用,使用真实窗口、编辑器、已安装语言服务器、实际子进程与磁盘结果。测试项目是 `fixtures/ts-app` 的 `/tmp/idea-parity-qa/core-ts` 副本;Python调试和终端脚本仅写入该副本。首次验收未修改产品源码;随后按用户要求修复下列两处问题,运行版本为 `d3feb05` 加工作区改动,未在本仓库提交;Git验收仅在独立core-git副本里创建QA提交。
通过判定仅针对表内明确写出的步骤。重点编辑、查找、导航、补全、格式化、项目视图和 npm 运行做了亮/暗复测;调试、启动链等执行逻辑没有逐一覆盖所有主题和语言组合。数据库、Docker部署、复杂Git图/merge/rebase/worktree、设置导入导出、完整书签/布局/宏管理不在这次缩小后的核心范围内,原清单相关待测项仍保留。
## 修复复测(同日)
- IN-2:保留未过滤的服务器诊断;检查方案编辑时重新投影已完成或进行中的结果,同步严重级别和问题计数,保留排除状态。原生应用亮/暗各验证 error → warning → disabled → restored;还验证了禁用时执行检查,再启用无需重跑即恢复2条诊断。[结构化证据](/tmp/idea-parity-qa/fix-IN2-results.json)、[暗色恢复截图](/tmp/idea-parity-qa/fix-IN2-dark-restored.png)。
- CSS:为共享语言服务器的 CSS、SCSS、Less 配置提供默认对象,避免 workspace/configuration 返回 null。三种文件分别打开 `.qa { colr: red; }`,均返回 unknownProperties 警告;新进程日志无 validProperties 异常。[诊断证据](/tmp/idea-parity-qa/fix-css-results.json)、[原生日志](/tmp/idea-parity-qa/fix-app.log)。
- 验证:前端分析相关10项测试、LSP协议26项测试均通过;pnpm typecheck、原生 debug build、cargo clippy -p ide-lsp --all-targets -- -D warnings、cargo fmt 与 git diff --check 通过。新增回归覆盖方案修改、禁用后恢复、流式检查中修改方案、计数和原始严重级别恢复,以及真实内置配置的协议响应。
## 首次失败记录(已修复,保留复现过程)
### A. IN-2:旧 Inspect Code 结果不随检查方案更新
1. 打开 `src/qa-diagnostic.ts`:`const qaNumber: number = "wrong";`。
2. 默认方案执行 Code › Inspect Code,仅检查当前文件,得到2条 TypeScript 错误。
3. 将 TypeScript 检查严重级别设为 warning:编辑器变为黄色波浪线、Problems 显示 warning;旧 Inspection Results 仍是红色错误。
4. 禁用该检查:编辑器无波浪线、Problems 清空;旧 Inspection Results 仍显示“2 problems in 1 file”。
期望:按 IN-2 的“同时变化”要求,三处采用同一有效方案。实际只有前两处即时更新。亮/暗均复现。[暗色截图](/tmp/idea-parity-qa/core-IN2-repro-dark.png)、[亮色截图](/tmp/idea-parity-qa/core-IN2-batch-disabled.png)、[结构化结果](/tmp/idea-parity-qa/core-IN2-repro-dark.json)。
**边界:重新执行 Inspect Code 后确实得到0条结果**,所以不是方案永远无效,而是已有批量结果的实时同步缺失。[重跑结果](/tmp/idea-parity-qa/core-IN2-rerun-disabled.json)。
实现线索:[inspect.ts](/Users/thomas/repo/kalo/idea/src/features/analysis/inspect.ts:183) 在启动时取得方案,接收事件时过滤一次并保存;[InspectionView.tsx](/Users/thomas/repo/kalo/idea/src/features/analysis/InspectionView.tsx:219) 的树以已有 files 构建,没有将方案变化作为依赖。这与首次运行现象一致;现已按上节修复。
### B. CSS 语言服务器校验抛异常
1. 在副本新建并打开 `src/qa-validation.css`:`.qa { colr: red; }`。
2. 等待已安装的 `vscode-css-language-server` 校验。
3. 日志出现 `TypeError: Cannot read properties of null (reading 'validProperties')`,诊断列表为空,错误属性没有提示。
期望:默认 CSS 校验正常运行并对未知属性给出诊断,不抛异常。新建两个空 CSS 时已出现同一异常;专用错误样例和原生进程重启后再次复现。[运行日志及诊断](/tmp/idea-parity-qa/core-css-validation.json)、[编辑器截图](/tmp/idea-parity-qa/core-css-validation.png)、[重启日志](/tmp/idea-parity-qa/core-app-restart.log)。
首次排查线索为 [handler.rs](/Users/thomas/repo/kalo/idea/crates/ide-lsp/src/handler.rs:119) 的 workspace/configuration:未配置 section 返回 null。现已验证默认配置对象可修复该异常,见上节。
## 完成的核心场景
| 编号 | 结果 | 场景 | 实际验证 | 证据 |
|---|---|---|---|---|
| C01 | 通过 | 编辑与保存 | 输入、撤销、重做、保存磁盘、外部写入自动重载;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-edit-confirm-results.json) |
| C02 | 通过 | 常用编辑命令 | 同一行注释/取消注释、复制行,验证实际文档结果;亮/暗各复测。注释命令会移动到下一行,复测时重新定位原行。 | [记录](/tmp/idea-parity-qa/core-edit-commands-final-dark.json) |
| C03 | 通过 | 项目视图与恢复 | 五种视图均切换;Open Files 成目录树;All Changed Files 仅包含被修改的已跟踪 index.ts。结束并重新启动原生进程后仍为 Open Files,23个打开路径与重启前完全一致。 | [记录](/tmp/idea-parity-qa/core-persist-after.json) |
| C04 | 通过 | New 搜索和创建 | 项目树焦点下 ⌘N 出现 Search for file type;css 能找到 Stylesheet。CSS/SCSS/Less、Dockerfile、EditorConfig、gitignore、JSON/YAML/TOML/Shell/HTTP 的磁盘结果沿用首轮实际创建证据。 | [记录](/tmp/idea-parity-qa/core-NF1-dark.png) |
| C05 | 通过 | ⌘N 上下文路由 | Python/Markdown 打开 New,并实际在当前文件的 src 目录创建 CSS;Java/Kotlin/TS 的动作轨迹为 code.generate,未打开 New。Kotlin 只验证路由,未声称生成代码可用。 | [记录](/tmp/idea-parity-qa/core-lastkeys.log) |
| C06 | 通过 | 项目树文件操作 | 从选中的 src 目录 New › File 创建 qa-tree-created.txt;Rename 后旧路径消失、新路径存在;确认移至 Trash 后新路径消失。 | [记录](/tmp/idea-parity-qa/core-tree-deleted.json) |
| C07 | 通过 | 文件内上下文查找 | In Comments 仅选中三个注释内的 shared(含 shared_history),Next/Previous 在位置3/38/78间导航,不命中代码和字符串;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-find-final.log) |
| C08 | 通过 | 替换大小写与排除 | Preserve Case 实际得到 bar/Bar/BAR;排除项出现删除线,Replace All 保留该项、替换其余项;亮/暗重新验证。 | [记录](/tmp/idea-parity-qa/core-FB4-final-dark.png) |
| C09 | 通过 | 多行及搜索历史 | ⇧⌘↵ 输入跨行 alpha/beta 后计数1/1并选中完整跨行文本;⌥↓ 能打开编辑器历史,Find in Files 也显示新增 QA_shared_history。 | [记录](/tmp/idea-parity-qa/core-FB5-dark-confirm.png) |
| C10 | 通过 | 自定义搜索范围 | 三个文件同一标记:不限定时3个文件;file:src//*.ts&&!file:*test* 仅命中 qa_scope.ts;Inspect Code 的 Custom scope 可选同一 Core TS Scope。 | [记录](/tmp/idea-parity-qa/core-FF3-final.png) |
| C11 | 通过 | 跨文件替换与预览 | 两个文本文件6处替换,预览显示 Bar/BAR/bar,确认后磁盘一致;多行搜索可命中多个文件。保留大小写在亮/暗分别确认。 | [记录](/tmp/idea-parity-qa/core-FF4-dark-final.json) |
| C12 | 通过 | 搜索排除归档 | 在项目内放入含唯一标记的 zip、jar,Find in Files 返回 No matches;不是只根据代码推断。 | [记录](/tmp/idea-parity-qa/core-FF5-archive.png) |
| C13 | 通过 | 文件/类型/符号导航 | Go to File 打开 money.ts,Go to Class 打开 Cart,Go to Symbol 打开 formatMoney;调用点转到 Cart 定义,Back/Forward 正确返回和前进;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-navigation.log) |
| C14 | 通过 | Search Everywhere 筛选 | Files 排除 TypeScript、Classes 排除 Classes、Symbols 排除 Functions、Text 设 *.py,结果分别被过滤;切换页后各页值独立保留;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-filters-final.log) |
| C15 | 通过 | Actions 跳转设置 | 复选框为 Include disabled actions;搜索 code completion 有 Settings: Editor | General,选中后回车打开原生 Settings 的 Code Completion 页。 | [记录](/tmp/idea-parity-qa/core-NV2-target-final.png) |
| C16 | 通过 | 重命名与 Generate | ⇧F6 原地重命名,第二次 ⇧F6 打开名称对话框;qaOriginalName 的声明和引用一起改为 qaRenamed。TS ⌘N 对缺失接口方法执行 Generate,生成 run() 实现。 | [记录](/tmp/idea-parity-qa/core-rename-clean.log) |
| C17 | 通过 | LSP 补全 | 单候选自动插入开关实际改变行为;字母排序有效;函数补全插入(),有参数时光标在括号内且显示参数提示;无参光标在括号后;已有(不重复。亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-completion.log) |
| C18 | 通过 | 格式化保护区 | 手动 Reformat 与保存时格式化都格式化保护区外的代码,@formatter:off/on 中间保持逐字不变;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-IN7-save-dark.json) |
| C19 | 通过 | 检查结果同步(IN-2) | 修复后亮/暗均验证严重级别、禁用和恢复即时同步,禁用时运行后重新启用也可恢复旧结果,无需重跑。 | [记录](/tmp/idea-parity-qa/fix-IN2-results.json) |
| C20 | 通过 | 运行与测试反馈 | npm start 输出购物车合计 $134.97、退出0;正常测试通过;开启 opt-in 失败测试后树显示1 failed/4 passed、断言和源文件行、退出1。亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-runactual-final.log) |
| C21 | 通过 | Current File 与调试 | Current File 直接运行 TS 输出 QA_CURRENT_FILE_OK;Python Current File 调试命中断点,显示 number=21,进入 double、越过后 answer=42,求值返回42,跳出、恢复后输出42、退出0。TS 调试器另列环境阻塞。 | [记录](/tmp/idea-parity-qa/core-debug-final-console.png) |
| C22 | 通过 | Before launch 执行链 | 先运行子配置,再成功 Build,再 shell,最后主进程;记录 child/shell/main,Build 成功且主子退出0。额外验证非0步骤阻止启动并通知、循环引用被拒绝。 | [记录](/tmp/idea-parity-qa/core-RC6-success.json) |
| C23 | 通过 | Compound | 两个成员17ms间隔启动并同时处于 running;选择 compound、从编辑器触发 Stop 后两个成员均 finished/130。 | [记录](/tmp/idea-parity-qa/core-RC7-stopped.json) |
| C24 | 通过 | 交互终端 | PTY 输入 hello 得到回显;QA_RED 在亮/暗为红色;窗口缩放使子进程收到尺寸233→89列,恢复后120列;输入exit正常退出0,另一次Stop退出130。 | [记录](/tmp/idea-parity-qa/core-RC9-resize.png) |
| C25 | 通过 | Power Save 核心行为 | 正常模式自动补全弹出;开启后同样输入不弹出,编辑器有横幅;有效配置同时关闭 usages Code Vision 等后台提示。随后关闭并确认重启后 false;未把这等同于全部后台任务性能验证。 | [记录](/tmp/idea-parity-qa/core-WB7-enabled.json) |
| C26 | 通过 | CSS 校验集成 | 修复后重新编译并启动原生应用,CSS/SCSS/Less 均对 colr 返回 unknownProperties 警告,日志无原异常。 | [记录](/tmp/idea-parity-qa/fix-css-results.json) |
| C27 | 通过 | Git常用流程 | 独立Python副本中查看HEAD与工作区diff,显示唯一QA标记差异;Commit先报告已有2个警告,选择Commit Anyway后实际提交,git diff为空,Git Log显示新提交。未推送。 | [记录](/tmp/idea-parity-qa/core-git-final.json) |
## 环境和验证边界
- Python debugpy 1.8.22 已安装,断点、变量、求值、三种单步和正常退出都实际验证。`js-debug` 未安装,**TypeScript/Node 调试没有通过判定**,没有拿 Python 的结果替代它。
- Kotlin 两个语言服务器和 Marksman 缺失。Kotlin 的 ⌘N 仅确认路由到 Generate;未声称 Kotlin 代码生成/补全/重构已通过。
- 部分配置通过真实 settings IPC 写入副本,运行配置执行链通过真实注册动作启动;没有把这些视作配置编辑器每个鼠标流程都已验收。
- 第一次应用运行经过热更新,产生过状态模块/焦点残留;已关闭该调试进程、单独启动Vite和编译好的原生二进制后复测快捷键。干净启动后重命名和 Generate 正常,因此不列为产品失败。
- `document.execCommand` 在终端缩放后的第二次注入没有发送文本;改用 textarea 的 InputEvent 后回显与正常退出均成功。这是驱动差异,不列为产品键入失败。使用的桥接输入均未被等同于人工键盘全矩阵验证。
- 已结束并重启原生进程,Open Files 模式和23个打开路径完整恢复。[重启前](/tmp/idea-parity-qa/core-persist-before.json)、[重启后](/tmp/idea-parity-qa/core-persist-after.json)。记录中的 `/tmp` 与 `/private/tmp` 双路径是测试脚本先后用两种路径打开同一文件造成,没有将其直接列为正常用户路径问题。
- 本轮没有应用崩溃;没有做量化卡顿测试。故意失败的测试、Before launch失败和Stop后的130通知均为测试输入产生;独立异常是上面的CSS服务器错误。
- 本轮无产品代码改动,因此没有重复运行完整构建测试;首轮的 typecheck 与30个相关Vitest结果仍单独记录,不作为运行场景的替代。
- 测试进程已停止;Power Save 恢复为false;全局语言/主题未新增改动。副本和截图保留供复核。
+125
Переглянути файл
@@ -0,0 +1,125 @@
# IDEA 对齐运行验收记录(2026-10-25)
结论:**尚未达到全量验收通过条件**。累计94项中,功能断言通过35项、失败1项、部分验证58项。IN-2与清单外CSS校验异常已修复并经原生应用复测。核心复测27场景的具体范围、修复后27通过/0失败结论见[核心补测报告](acceptance-idea-core-result.md);不能把本次核心补测当作原94项全部完成。
目标提交为 `1e00ea5`;启动后仓库由外部更新为 `d3feb05 chore: v0.1.14`,仅版本文件变化,实际后续验收运行此版本。首次验收未改动产品源码;随后按用户要求修复IN-2和CSS配置,版本为 `d3feb05` 加工作区改动,未提交。测试均使用 `/tmp/idea-parity-qa/` 下的 fixture 副本。
使用 `pnpm tauri dev` 启动真实 macOS Tauri 应用,桥接操作真实 DOM、注册动作,并读取运行结果。部分设置通过真实 IPC 写入测试项目配置,以核对运行时行为;这不替代 Settings 原始鼠标路径或快捷键验证。热更新造成的旧模块实例问题已识别,相关外部库检查重新使用运行中的模块后重做;以 `libraries-final.log` 为准。
亮/暗主题已抽查 New、查找、运行配置、数据库、工具栏、Cleanup;未做到94项各自双主题全覆盖,主题总要求仍未完成。中文抽查发现可复现漏译。未观察到功能整体缺失;未覆盖项不能据此判定已实现。
辅助检查:`pnpm typecheck` 退出码0;4个相关 Vitest 文件共30个测试通过(libraries、NewPopup、file templates、run-anything)。没有重新运行完整 Rust/前端测试,不沿用清单中旧提交的通过数作为本轮证据。
## 逐项记录
| 编号 | 结果 | 现象、范围和证据 |
|---|---|---|
| PV-1 | 通过 | 真实 Project 标题下拉列出五种要求的模式;[证据](/tmp/idea-parity-qa/PV-1-menu.png) |
| PV-2 | 通过 | 核心复测:五种模式已操作;Open Files 成树、All Changed Files 仅显示修改的已跟踪文件;原生进程重启后 Open Files 和23个打开路径恢复。[证据](/tmp/idea-parity-qa/core-persist-after.json) |
| PV-3 | 通过 | Open Files 中定位未打开的 README.md,自动回到 Project 并选中 |
| PV-4 | 部分 | Python 副本已建 .venv,External Libraries 注册标准库、venv 库和 site-packages;.venv 下逐级展开对照未完成;[证据](/tmp/idea-parity-qa/PV-6-python-app.png) |
| PV-5 | 部分 | 在副本 site-packages 新建 qa_library.py,经编辑器插入文字后内容和磁盘均不变,readOnly=true,横幅正常;节点重命名/删除/新建/拖拽未逐项操作;[证据](/tmp/idea-parity-qa/PV-5-blocked-input.png) |
| PV-6 | 部分 | Rust stdlib、Go SDK、JDK/src.zip、Gradle junit-jupiter 源码 jar、TS 的 typescript/vitest 直接依赖均已识别并注册到树;Cargo 依赖、Go 模块和 Maven 分组未完整覆盖;[证据](/tmp/idea-parity-qa/libraries-final.log) |
| PV-7 | 部分 | JDK src.zip!/java.base/java/lang/String.java 实际打开,语法高亮、readOnly=true;树内逐级浏览及另一个 jar 未完整操作;[证据](/tmp/idea-parity-qa/PV-7-archive.png) |
| PV-8 | 通过 | TS 副本 package.json 添加已在 node_modules 中的 qa-dep;857ms 后 External Libraries 已出现该依赖,随后恢复清单;[证据](/tmp/idea-parity-qa/PV-8-refresh.json) |
| NF-1 | 通过 | 核心复测:项目树选中src,⌘N 打开带搜索框的 New;css 找到 Stylesheet。随后 New › File 实际在src创建文件。[证据](/tmp/idea-parity-qa/core-tree-new-parent.json) |
| NF-2 | 通过 | 实际创建 CSS、SCSS、Less、Dockerfile、.editorconfig、.gitignore、JSON、YAML、TOML、Shell 和 HTTP 文件;核对磁盘扩展名及模板内容;[证据](/tmp/idea-parity-qa/templatesactual.log) |
| NF-3 | 通过 | 核心复测:Python/Markdown 的 ⌘N 均打开 New,实际创建的CSS都在当前文件的src目录。[证据](/tmp/idea-parity-qa/core-lastkeys.log) |
| NF-4 | 通过 | 核心复测:Java/Kotlin/TS 的 ⌘N 动作轨迹为 code.generate,均不打开 New;TS 实际生成缺失接口方法。Kotlin只验证路由,语言服务器缺失。[证据](/tmp/idea-parity-qa/core-NF4-generate.png) |
| NF-5 | 部分 | 动作能弹出 New 并在当前 worker 目录创建文件;任意焦点和 ⌃⌥N 按键矩阵未完整验证;[证据](/tmp/idea-parity-qa/NF-5.png) |
| NF-6 | 通过 | 创建 /tmp/idea-parity-qa/qa-new-project,勾选 Git,磁盘 .git 存在,出现独立 project-1 窗口;[证据](/tmp/idea-parity-qa/NF-6-created.json) |
| NF-7 | 部分 | 重命名为 QA renamed project 后原生窗口标题更新,polyglot 磁盘目录保持原名;最近项目列表未单独检查;[证据](/tmp/idea-parity-qa/NF-7-renamed.png) |
| FB-1 | 通过 | 漏斗列出 Search In Selection 和清单中的六种上下文范围;[证据](/tmp/idea-parity-qa/FB-1-filter.png) |
| FB-2 | 通过 | 核心复测:In Comments 计数3;Next/Previous在三个注释位置间跳转,不命中代码/字符串;亮暗均验证。[证据](/tmp/idea-parity-qa/core-find-final.log) |
| FB-3 | 通过 | 9 处 foo/Foo/FOO 替换为 bar/Bar/BAR,磁盘副本编辑内容符合预期;[证据](/tmp/idea-parity-qa/FB-3-result.png) |
| FB-4 | 通过 | 排除第一处匹配后显示删除线,Replace All 保留该处 bar,其余变为 baz;[证据](/tmp/idea-parity-qa/FB-4-result.png) |
| FB-5 | 通过 | 核心复测:⇧⌘↵ 后跨行输入alpha/beta,计数1/1、选择完整跨行内容;亮暗均确认。[证据](/tmp/idea-parity-qa/core-FB5-dark-confirm.png) |
| FB-6 | 通过 | 核心复测:⌥↓ 打开编辑器最近搜索,新增QA_shared_history同时出现在 Find in Files 的最近搜索。[证据](/tmp/idea-parity-qa/core-find-final.log) |
| FF-1 | 通过 | 真实窗口显示 In Project/Module/Directory/Scope,polyglot Module 下拉含根模块及 api、web;[证据](/tmp/idea-parity-qa/FF-1-options.json) |
| FF-2 | 通过 | 新建并保存自定义 scope;!(file:src//* 实时显示 Missing `)` 错误,合法表达式出现在下拉;[证据](/tmp/idea-parity-qa/FF-2-real-invalid.png) |
| FF-3 | 通过 | 核心复测:自定义Scope将3个标记文件缩至唯一qa_scope.ts;Inspect Code的Custom scope也能选Core TS Scope。[证据](/tmp/idea-parity-qa/core-FF3-final.png) |
| FF-4 | 通过 | 核心复测:跨文件多行搜索命中;6处替换的保留大小写预览与磁盘Bar/BAR/bar一致;亮暗均确认。[证据](/tmp/idea-parity-qa/core-FF4-dark-final.json) |
| FF-5 | 通过 | 核心复测:项目内jar/zip包含唯一标记,Find in Files不命中。[证据](/tmp/idea-parity-qa/core-FF5-archive.png) |
| NV-1 | 通过 | 核心复测:四页分别过滤文件类型/类种类/符号种类/文件掩码,结果变化且各页保留独立选择;亮暗均验证。[证据](/tmp/idea-parity-qa/core-filters-final.log) |
| NV-2 | 通过 | 核心复测:文案正确;Settings: Code Completion结果回车打开原生设置的对应页面。[证据](/tmp/idea-parity-qa/core-NV2-target-final.png) |
| NV-3 | 部分 | 未执行:动作快捷键录入、生效与三种冲突解决 |
| NV-4 | 部分 | 未执行:书签列表新建/重命名/删除/默认列表/移动矩阵 |
| NV-5 | 部分 | 书签弹窗入口存在且空状态正常;文件、文件夹、行书签及按列表分组跳转未执行;[证据](/tmp/idea-parity-qa/NV-5.png) |
| NV-6 | 部分 | 未执行:Structure 字段/非公开成员/可见性排序 |
| NV-7 | 部分 | 未执行:支持 typeHierarchy 的 TS/Java 继承成员及跳转 |
| NV-8 | 部分 | Recent Locations 有相对时间和代码片段;类/方法面包屑和片段高亮未完整核对;[证据](/tmp/idea-parity-qa/NV-8.png) |
| NV-9 | 部分 | 已提交 fixture 的 Python 函数出现 Thomas Hong 作者;Settings 有 Code author;多人 +N 及关闭效果未验证 |
| ED-1 | 通过 | 核心复测:关闭单候选自动插入时保留一个候选,开启后实际自动插入;亮暗均确认。[证据](/tmp/idea-parity-qa/core-completion.log) |
| ED-2 | 通过 | 核心复测:打开Sort suggestions alphabetically后真实候选按名称排序,popup含Sort by name;通过设置开关路径验证。[证据](/tmp/idea-parity-qa/core-ED2-sorted-dark.png) |
| ED-3 | 通过 | 核心复测:有参/无参函数自动括号、光标落点和参数提示符合要求;已有(不重复;亮暗均验证。[证据](/tmp/idea-parity-qa/core-completion.log) |
| ED-4 | 部分 | Top/Bottom/Left/Right/None 均切换并截图,左右为竖排,None 隐藏标签;滚动、拖拽和菜单一致性未逐项验证;[证据](/tmp/idea-parity-qa/ED-4-none.png) |
| ED-5 | 部分 | Editor Tabs 的相关设置项齐全;每种选项实际行为未逐项验证;[证据](/tmp/idea-parity-qa/settings-Editor-Tabs.png) |
| ED-6 | 部分 | Inline Completion 设置页存在;未配置支持 inlineCompletion 的服务,运行预览及快捷键跳过,不能视为通过;[证据](/tmp/idea-parity-qa/settings-Inline-Completion.png) |
| IN-1 | 部分 | Inspections 页面有方案、搜索、按语言树和描述区域;三态与 Severity 的编辑操作未完成;[证据](/tmp/idea-parity-qa/IN-1-settings.png) |
| IN-2 | 通过 | 修复复测:亮/暗下编辑器和旧Inspect Code结果随严重级别、禁用、恢复即时同步,计数同步;禁用时运行后也能重新启用恢复诊断,无需重跑。[证据](/tmp/idea-parity-qa/fix-IN2-results.json) |
| IN-3 | 部分 | 未执行:检查方案 Duplicate/Copy/Rename/Delete 和内置方案保护 |
| IN-4 | 部分 | 测试副本已写入 recieve;注释/字符串/声明和调用名的诊断对照未完成 |
| IN-5 | 部分 | Spelling 设置页面存在;Typo 上下文候选及保存两类词典未执行;[证据](/tmp/idea-parity-qa/settings-Spelling.png) |
| IN-6 | 部分 | Code Style 页面有 Default (IDE) Scheme 与 Copy to Project;语言子页面联动未完整操作;[证据](/tmp/idea-parity-qa/settings-Code-Style.png) |
| IN-7 | 通过 | 核心复测:手动及保存格式化都格式化保护区之外,formatter:off/on之间逐字保持;亮暗均验证。[证据](/tmp/idea-parity-qa/core-IN7-save-dark.json) |
| IN-8 | 通过 | 项目配置 Do not format 为 *.json,执行 Reformat Code 出现明确跳过提示;[证据](/tmp/idea-parity-qa/IN-8-excluded.png) |
| IN-9 | 部分 | Cleanup 范围及 fix/import/format 选项存在,可取消;实际清理结果和中途取消未执行;[证据](/tmp/idea-parity-qa/IN-9.png) |
| FT-1 | 部分 | 打开 x.foo 后添加 YAML 关联,现有 editor context 立即变为 yaml/YAML;图标及 Go to File 未独立核对;[证据](/tmp/idea-parity-qa/FT-1-yaml.png) |
| FT-2 | 部分 | 调用同名注册动作使 YAML→JSON→YAML,现有编辑器立即更新;右键菜单路径及撤销未操作;[证据](/tmp/idea-parity-qa/FT-2-revert.json) |
| FT-3 | 通过 | 无扩展名 qa-hashbang 带 #!/usr/bin/env python3,实际 editor context 为 python/Python;[证据](/tmp/idea-parity-qa/FT-3-hashbang.png) |
| PS-1 | 部分 | 添加外部 extra-root 后树出现根,Find in Files 命中 extra.ts;Go to File 和外部文件修改刷新未完整验证;[证据](/tmp/idea-parity-qa/PS-1-search.png) |
| PS-2 | 部分 | 即时设置 *.log;tmp* 后 Find in Files 不再命中 qa.log 中的唯一标记;树与索引侧未独立核对;[证据](/tmp/idea-parity-qa/PS-2-search.png) |
| TP-1 | 部分 | File and Code Templates 页面包含 Includes,说明支持 #parse;编辑 File Header 后新建 Java/Kotlin 未执行 |
| TP-2 | 部分 | 模板页有 Code 标签;修改测试方法模板并生成测试未执行 |
| TP-3 | 部分 | Reformat according to style 默认已勾选;$END$ 光标及格式化效果未单独验证;[证据](/tmp/idea-parity-qa/settings-File-and-Code-Templates.png) |
| RC-1 | 通过 | 核心复测:Current File保持可选,直接运行TS输出正确;Python Current File调试命中断点并可单步/求值/正常退出。Node调试器缺失单独记为环境阻塞。[证据](/tmp/idea-parity-qa/core-debug-final-console.png) |
| RC-2 | 通过 | + 菜单列出所有要求类型,含 Compound 与 Docker 三种子类型,搜索输入存在;[证据](/tmp/idea-parity-qa/RC-2-types.png) |
| RC-3 | 部分 | 实际新建 Shell/Program,Program env 运行成功,检测配置正常;其余每种类型执行及旧配置兼容未覆盖;[证据](/tmp/idea-parity-qa/RC-8-process-output.png) |
| RC-4 | 部分 | 表单支持复制/分组/排序/Templates;对话框 Run 成功,local TOML 已落盘且 git check-ignore 命中 .openidea/.gitignore;其余子流程未逐项执行 |
| RC-5 | 部分 | Modify options 显示各类可选项;移除控件与各选项的运行效果未完整验证;[证据](/tmp/idea-parity-qa/RC-5.json) |
| RC-6 | 通过 | 核心复测:实际子配置→Build→Shell→主进程;Build成功,记录child/shell/main;失败步骤中止并通知,循环被拒绝。[证据](/tmp/idea-parity-qa/core-RC6-success.json) |
| RC-7 | 通过 | 核心复测:两成员17ms间隔启动并同时running,选中compound从编辑器触发Stop后都结束、退出130。[证据](/tmp/idea-parity-qa/core-RC7-stopped.json) |
| RC-8 | 部分 | A=1;B=2 输入后对话框拆成两行,关闭系统环境后 /usr/bin/env 仅输出 A/B,退出码 0;独立 Paste 按钮未操作;[证据](/tmp/idea-parity-qa/RC-8-process-output.png) |
| RC-9 | 通过 | 核心复测:PTY回显、亮暗ANSI颜色、resize传到子进程(233→89列)均正常;输入exit退出0,另次Stop退出130。[证据](/tmp/idea-parity-qa/core-RC9-resize.png) |
| RC-10 | 部分 | 空 Run 显示三条提示及 run configuration 链接;点击链接未操作 |
| RC-11 | 部分 | 本机 Docker 可用,但未运行/停止 fixture Docker 和 Compose,不能视为通过 |
| GT-1 | 部分 | Graph Options 所列排序和分支选项齐全;复杂分支图下的效果未执行;[证据](/tmp/idea-parity-qa/GT-1-options.png) |
| GT-2 | 部分 | View Options 所列显示项和 Highlight 存在;开关效果及重启持久化未完整验证;[证据](/tmp/idea-parity-qa/GT-2-options.png) |
| GT-3 | 部分 | 未执行:Log 焦点 ⌘F、补全、跳转及自动加载更多 |
| GT-4 | 部分 | 未执行:设置 Date 过滤后图仍保留 |
| GT-5 | 部分 | 七种对话框均实际打开,选项可见;未执行 pull/merge/rebase/worktree/clone 的磁盘变化;[证据](/tmp/idea-parity-qa/gitcheck.log) |
| SV-1 | 部分 | Add Service 菜单有三类要求入口;⌘N 和无连接空状态未完整验证;[证据](/tmp/idea-parity-qa/SV-1.png) |
| SV-2 | 部分 | 实际 Program/Run Anything/PTY 均已启动;Services 中运行配置分组与停止/重跑/输出跳转未验证 |
| SV-3 | 部分 | 自动连接 orbstack,显示容器、镜像、卷和网络;新建多个连接及绑定操作路由未执行;[证据](/tmp/idea-parity-qa/SV-1.png) |
| TD-1 | 部分 | TODO 有 Scope Based、Changes,显示7条 fixture TODO/FIXME;自定义范围和多个 changelist 下拉未验证;[证据](/tmp/idea-parity-qa/TD-1.png) |
| CV-1 | 部分 | LCOV 导入显示 app.ts 50%(1/2),管理弹窗列出报告;Go/JaCoCo、多报告切换和 gutter 未完整验证;[证据](/tmp/idea-parity-qa/CV-1-import.png) |
| DB-1 | 部分 | Driver 下拉按字母列出 CockroachDB/Redshift/TiDB 等;逐种默认端口未核对;[证据](/tmp/idea-parity-qa/DB-1-list.png) |
| DB-2 | 通过 | 指定 JDBC URL 解析出 h、5432、db,SSL 页为 Verify Full;[证据](/tmp/idea-parity-qa/DB-2-ssl.png) |
| DB-3 | 部分 | Options/Schemas/Advanced 页签存在;未连 SQLite/Postgres 验证只读/启动脚本/时区/过滤/驱动属性 |
| DB-4 | 部分 | 颜色和 Add comment 控件存在;树节点、console 标签及 hover 效果未验证 |
| WB-1 | 部分 | Run Anything 执行 pwd,输出进入 Run,cwd 为 fixture,退出码0,并列出检测配置;双 Ctrl、Maven/Gradle 和新历史未完整验证;[证据](/tmp/idea-parity-qa/WB-1-output.png) |
| WB-2 | 部分 | Customize Main Toolbar 可打开并显示增删/排序/恢复控件;实际保存和重启持久化未执行;[证据](/tmp/idea-parity-qa/WB-2.png) |
| WB-3 | 部分 | Save Current Layout as 弹出命名输入;另存、恢复、重命名、删除完整流程未执行;[证据](/tmp/idea-parity-qa/WB-3-save.json) |
| WB-4 | 部分 | 未执行:原生 View › Tool Windows 与注册表的一一核对 |
| WB-5 | 部分 | Quick Switch Scheme 弹出四类选项;其余菜单命令及所有效果未完整验证;[证据](/tmp/idea-parity-qa/WB-5.png) |
| WB-6 | 部分 | 无可用重构位置弹出 Nothing here;原生菜单上下文置灰未验证;[证据](/tmp/idea-parity-qa/WB-6.png) |
| WB-7 | 部分 | Power Save Mode 切换后编辑器出现横幅,随后关闭恢复;后台高亮与自动弹出抑制未完整验证;[证据](/tmp/idea-parity-qa/WB-7-real.png) |
| WB-8 | 部分 | 未执行:完整 Export/Import 设置与快捷键、模板、宏、布局恢复 |
| WB-9 | 部分 | 录制 QA macro 后回放,内容为 QA macroQA macro;保存命名和 Keymap 绑定未执行;[证据](/tmp/idea-parity-qa/WB-9-replay-result.png) |
| WB-10 | 部分 | Coverage 导入的信息通知显示 Don’t Show Again;点击后同类通知抑制未验证 |
| I18N-1 | 失败 | 复现:切换中文,打开 Code › Code Cleanup。实际 Whole project、Module or directory、Uncommitted files 和底部说明仍为英文;打开 Customize Main Toolbar 后 Project Widget/VCS Widget/Build Project/Run Widget 仍为英文;Services 的 Containers/Images/Volumes/Networks 仍为英文。期望这些新增界面文案均翻译;均不属于清单已知例外;[证据](/tmp/idea-parity-qa/IN-zh-dark.png) |
## 独立问题与环境说明
- 崩溃:已执行流程中未观察到应用崩溃。版本更新引起的 dev 自动重编译不是崩溃。
- 控制台:有自动化自身造成的错误(错误 action id、首次尝试不存在的文件、带换行注入脚本的 Unexpected EOF)和手动 reload 后 Tauri callback 警告;不归为产品功能失败。尚不能声明控制台全量无错误。应用日志在 [/tmp/idea-parity-qa.log](/tmp/idea-parity-qa.log)。
- 卡顿:未观察到已执行操作中的明显持续卡顿;没有完成量化性能验收。桥接脚本等待用户输入对话框导致的超时不按应用卡顿计。
- 核心补测新增的CSS语言服务器validProperties空值异常已修复;CSS/SCSS/Less真实校验均返回未知属性警告,见核心报告修复复测。
- Python REPL 的 Stop 先发中断(出现 KeyboardInterrupt),随后超时强制结束,最终137/SIGKILL;这是本轮观察结果,未仅凭此判失败。
- 首轮安装TS依赖时pnpm提示esbuild脚本未批准;核心补测已实际运行npm start及正常/故意失败测试。Build通过专用最小TS目标验证,未据此宣称所有原始QA文件能通过类型检查。
- 全量放行前仍需完成表中的未执行子项,包括所有语言/运行类型、Docker、复杂Git图与合并/变基、数据库、设置导入导出、完整书签/布局管理等;双主题逐项与中文复测也未全覆盖。Before launch、Compound、补全和基础运行/调试已有核心复测证据,见对应行。
截图和结构化证据目录:[/tmp/idea-parity-qa](/tmp/idea-parity-qa)。验收期间使用的全局主题、语言和 Power Save Mode 已恢复;最后录制宏为 QA 样例,测试项目仍保留供复核。
核心补测:新增真实编辑、导航、补全、重命名、检查同步、运行/调试、Before launch/Compound、PTY和原生重启验证;详情见[核心补测报告](acceptance-idea-core-result.md)。原表中其他待测子项仍保留,不因核心补测而自动变绿。
+593
Переглянути файл
@@ -0,0 +1,593 @@
# Theme plugins
OpenIDEA ships three built-in themes (Islands Light, Islands Dark, High
Contrast). Everything else comes from **theme plugins**, the same model as
IntelliJ IDEA, where most themes are plugins rather than part of the IDE.
A theme plugin is data only. Like an IntelliJ theme (a `.theme.json` plus an
optional `.icls` editor scheme) it has no code: no WebAssembly, nothing to
compile, no permissions.
```
my-theme/
├─ plugin.toml # manifest
└─ themes/
├─ my-theme.theme.json # UI colours (IntelliJ: .theme.json)
└─ my-theme.scheme.json # editor colours, optional (IntelliJ: .icls)
```
## Ready-made theme plugins
The repository's [`plugins/`](../../plugins) folder holds two complete theme
plugins, each with a light and a dark theme and an editor colour scheme
(syntax, editor and terminal ANSI colours):
| Package | Themes | Palette |
|---|---|---|
| [`plugins/theme-solarized`](../../plugins/theme-solarized) | Solarized Light, Solarized Dark | [Solarized](https://github.com/altercation/solarized) by Ethan Schoonover |
| [`plugins/theme-one`](../../plugins/theme-one) | One Light, One Dark | Atom [One Light](https://github.com/atom/one-light-syntax) / [One Dark](https://github.com/atom/one-dark-syntax) by GitHub |
Both palettes are MIT-licensed; each package carries the notice in its
`LICENSE`, which is installed with it. To use one:
1. *Settings › Plugins › ⚙ › Install Plugin from Disk…* and pick the package
folder (`plugins/theme-solarized` or `plugins/theme-one` of a checkout or a
downloaded copy). Development builds also list both on the *Available*
tab, where *Install* does the same.
2. Select the plugin and press *Apply* next to a theme.
The IDE remembers the theme: the next start-up opens its windows, splash and
workbench in the theme's colours before the plugin host has loaded.
## Writing a theme plugin
The quickest way to start is to copy [`templates/theme-plugin`](../../templates/theme-plugin).
It contains *Harbor Night*, a complete example dark theme that sets every
themeable token. The rest of this page covers the file format, the token
reference, porting themes from IntelliJ IDEA and VS Code, and testing.
## The manifest
```toml
id = "theme-harbor-night" # [a-z0-9][a-z0-9_-]*, unique among plugins
name = "Harbor Night Theme"
version = "1.0.0"
description = "..."
authors = ["You <you@example.com>"]
openidea-api = "0.1"
[[contributes.themes]] # one entry per theme; a plugin may ship several
path = "themes/harbor-night.theme.json"
editor-scheme = "themes/harbor-night.scheme.json" # optional
```
Paths are relative to the package directory and may not leave it. The other
manifest fields are described in [`plugins/README.md`](../../plugins/README.md).
## The theme file
```jsonc
{
"id": "harbor-night", // [a-z0-9][a-z0-9._-]*, unique within the plugin
"name": "Harbor Night", // shown in Settings › Plugins
"kind": "dark", // "dark" or "light": the built-in base
"tokens": {
"--bg-app": "#14171c",
"--accent": "#2b9e93"
}
}
```
- **`tokens`** are the CSS variables of [`src/styles/tokens.css`](../../src/styles/tokens.css),
the IDE's single source of colours. Components never use colour literals, so
every surface, border, text colour, syntax colour and status colour can be
themed through them. The [reference](#token-reference) lists them all.
- **`kind`** picks the built-in base. While the theme is active the IDE runs on
Islands Dark or Islands Light, and every token the theme leaves out keeps
that base's value. Icons also use the light or dark set that matches the
kind. A partial theme still looks consistent, but listing every token keeps
it stable when the IDE's own palette changes.
- Values are plain CSS values: hex (`#rgb`, `#rrggbb`, `#rrggbbaa`), `rgb()`,
`hsl()`, `color-mix()`, `var(--other-token)`, or for the few non-colour
tokens a keyword (`italic`, `normal`, `none`) or shadow list. `url()`,
`image()`, `;`, braces, `<`, `>` and `\` are rejected.
- `//` and `/* */` comments are allowed, as in VS Code theme files.
- Tokens that tokens.css derives from others (for example `--bg-editor` is
`var(--bg-island)`, and the coverage and flame graph colours are mixed from
the status colours) follow automatically. You may still set them.
- Metrics (`--fs-*`, `--h-*`, `--radius-*`) and fonts (`--font-ui`,
`--font-mono`) can be overridden too, but a theme normally leaves them alone
so that compact mode and the user's font settings keep working.
### The editor colour scheme file
```jsonc
{
"name": "Harbor Night",
"tokens": { "--syn-keyword": "#e0a46e", "--caret": "#5ce0d2" }
}
```
Its tokens are merged over the theme's, and the scheme wins where both set a
token. By convention it holds the *syntax*, *editor* and *ANSI palette* groups
of the reference, the parts IntelliJ keeps in an `.icls` file. The split only
organises the files: a theme can also put everything in its theme file.
### How a theme is applied
The selected theme is injected as one stylesheet on `:root` that outranks the
built-in theme blocks, and `data-theme` is switched to the theme's `kind`.
Three things still layer on top of it:
- an accent colour picked in *Settings › Appearance* (other than the default),
- an explicit scheme or attribute overrides in *Settings › Editor › Color Scheme*,
- the appearance options that change only metrics (compact mode).
The selection is remembered. When the plugin is disabled or uninstalled the
built-in theme returns.
## Building, packaging, installing
There is no build step. The package *is* the folder.
1. Copy `templates/theme-plugin` and rename `id`, `name` and the theme files.
2. Edit the colours. Keep `kind` truthful (`light` for light backgrounds).
3. **Install:** *Settings › Plugins › ⚙ › Install Plugin from Disk…* (or the
*Install Plugin from Disk…* action) and pick the package folder. The
manifest and the files it references are copied to
`<app-data>/plugins/<id>/`.
4. **Apply:** in *Settings › Plugins*, select the plugin and press *Apply* next
to the theme. *Use Default Theme* switches back.
To iterate without reinstalling, put (or symlink) the package in
`<project>/.openidea/plugins/<name>/` of an open project. It loads as a *dev*
plugin, and *Reload* (or the *Reload Plugins* action) picks up your edits.
To share a theme, publish the folder (a Git repository or a zip). Users
install it from disk.
## Porting a theme
Only port themes whose licence allows redistribution, keep their licence file,
and credit the original authors in `authors` and `description`.
### From IntelliJ IDEA (automatic)
`scripts/theme/import-intellij-theme.ts` converts an IntelliJ `.theme.json`,
and optionally its `.icls` editor scheme, into a ready-to-install plugin. It
has no dependencies beyond Node 22.
```sh
pnpm theme:import-intellij path/to/MyTheme.theme.json path/to/MyTheme.icls --out ~/my-theme --author "Original Author"
# or: node scripts/theme/import-intellij-theme.ts …
```
It maps the keys in the tables below, resolves named colours from the theme's
`colors` section and `*` wildcards, and takes `kind` from `"dark"` (or the
`.icls` `parent_scheme`). Tokens without an IntelliJ counterpart keep the
built-in values for that kind. Open the result next to the template and fill
in what matters to you. Themes that ship only a `.theme.json` with an
`editorScheme` path need that `.icls` passed as the second argument. Themes that
ship no `.icls` at all keep the built-in syntax colours.
#### `.theme.json` → UI theme
| OpenIDEA token | IntelliJ `ui` key (first present wins) |
|---|---|
| `--bg-app` | `Panel.background` |
| `--bg-frame` | `MainWindow.background`, `MainToolbar.background` |
| `--bg-island`, `--bg-elev` | `ToolWindow.background` |
| `--bg-popup` | `Popup.background`, `PopupMenu.background` |
| `--bg-hover` | `List.hoverBackground`, `Tree.hoverBackground` |
| `--bg-selected`, `--bg-tree-selected` | `List.selectionBackground`, `Tree.selectionBackground` |
| `--bg-tree-selected-inactive` | `Tree.selectionInactiveBackground` |
| `--bg-input`, `--bg-field` | `TextField.background` |
| `--border` | `Borders.color` |
| `--border-strong`, `--border-window` | `Component.borderColor`, `Borders.ContrastBorderColor` |
| `--fg`, `--fg-emphasis` | `Label.foreground` |
| `--fg-secondary`, `--fg-muted` | `Label.infoForeground`, `Component.infoForeground` |
| `--fg-subtle`, `--fg-faint` | `Label.disabledForeground` |
| `--accent` | `Button.default.startBackground`, `Component.focusColor` |
| `--fg-on-accent`, `--fg-button-primary` | `Button.default.foreground` |
| `--link`, `--link-hover` | `Link.activeForeground`, `Link.hoverForeground` |
| `--danger`, `--warning` | `Component.errorFocusColor`, `Component.warningFocusColor` |
| `--bg-tooltip`, `--fg-tooltip`, `--border-tooltip` | `ToolTip.background`, `.foreground`, `.borderColor` |
| `--bg-button`, `--border-button` | `Button.startBackground`, `Button.startBorderColor` |
| `--bg-tab-selected`, `--border-tab-selected` | `EditorTabs.underlinedTabBackground`, `EditorTabs.underlineColor` |
| `--bg-toolbar-hover`, `--bg-toolbar-pressed` | `ActionButton.hoverBackground`, `ActionButton.pressedBackground` |
| `--bg-stripe-hover`, `--bg-stripe-selected` | `ToolWindow.Button.hoverBackground`, `.selectedBackground` |
| `--scrollbar-thumb`, `--scrollbar-thumb-hover` | `ScrollBar.Mac.thumbColor`, `ScrollBar.Mac.hoverThumbColor` |
| `--bg-toggle-*` | `ToggleButton.onBackground`, `.offBackground`, `.buttonColor` |
| `--bg-feedback-*`, `--border-feedback-*` | `Banner.infoBackground`, `Banner.errorBorderColor`, … |
The full table is `UI_KEYS` in [`scripts/theme/intellij.ts`](../../scripts/theme/intellij.ts).
#### `.icls` → editor scheme
| OpenIDEA token | `.icls` option |
|---|---|
| `--fg-editor`, `--bg-editor` | attribute `TEXT` (foreground, background) |
| `--caret`, `--bg-current-line` | colour `CARET_COLOR`, `CARET_ROW_COLOR` |
| `--bg-editor-selection` | colour `SELECTION_BACKGROUND` |
| `--fg-line-number`, `--fg-line-number-current` | colour `LINE_NUMBERS_COLOR`, `LINE_NUMBER_ON_CARET_ROW_COLOR` |
| `--border-indent-guide`, `--border-right-margin`, `--fg-whitespace` | colour `INDENT_GUIDE`, `RIGHT_MARGIN_COLOR`, `WHITESPACES` |
| `--vcs-*`, `--gutter-*` | colour `FILESTATUS_*`, `MODIFIED_LINES_COLOR`, `ADDED_LINES_COLOR`, `DELETED_LINES_COLOR` |
| `--syn-keyword`, `--syn-string`, `--syn-number` | `DEFAULT_KEYWORD`, `DEFAULT_STRING`, `DEFAULT_NUMBER` |
| `--syn-comment` (+ `--syn-comment-style`), `--syn-doc-comment` | `DEFAULT_LINE_COMMENT` (+ `FONT_TYPE`), `DEFAULT_DOC_COMMENT` |
| `--syn-function`, `--syn-function-call` | `DEFAULT_FUNCTION_DECLARATION`, `DEFAULT_FUNCTION_CALL` |
| `--syn-type`, `--syn-constant`, `--syn-property` | `DEFAULT_CLASS_NAME`, `DEFAULT_CONSTANT`, `DEFAULT_INSTANCE_FIELD` |
| `--syn-variable`, `--syn-param`, `--syn-builtin` | `DEFAULT_LOCAL_VARIABLE`, `DEFAULT_PARAMETER`, `DEFAULT_PREDEFINED_SYMBOL` |
| `--syn-annotation`, `--syn-decorator` | `DEFAULT_METADATA` |
| `--syn-punct`, `--syn-escape` | `DEFAULT_OPERATION_SIGN`, `DEFAULT_VALID_STRING_ESCAPE` |
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5` (Semantic highlighting) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES` (effect colour) |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-match` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT` (`CONSOLE_DARKGRAY_OUTPUT` is bright black, `CONSOLE_GRAY_OUTPUT` white) |
The full tables are `ICLS_COLORS` and `ICLS_ATTRIBUTES` in the same file.
### From VS Code (by hand)
A VS Code theme (`themes/*.json` in the extension) has `type` (`dark` / `light`
/ `hc`), `colors` (workbench) and `tokenColors` (TextMate scopes). Set `kind`
from `type`, then map:
| OpenIDEA token | VS Code `colors` key |
|---|---|
| `--bg-frame` | `titleBar.activeBackground`, `activityBar.background` |
| `--bg-island`, `--bg-app` | `editor.background`, `sideBar.background` |
| `--bg-elev` | `sideBarSectionHeader.background`, `editorGroupHeader.tabsBackground` |
| `--bg-popup`, `--border-popup` | `editorWidget.background`, `editorWidget.border` |
| `--bg-hover` | `list.hoverBackground` |
| `--bg-selected`, `--bg-tree-selected` | `list.activeSelectionBackground` |
| `--bg-tree-selected-inactive` | `list.inactiveSelectionBackground` |
| `--border` | `panel.border`, `sideBar.border` |
| `--fg` | `foreground`, `sideBar.foreground` |
| `--fg-muted`, `--fg-subtle` | `descriptionForeground`, `disabledForeground` |
| `--accent`, `--fg-on-accent` | `button.background`, `button.foreground` |
| `--focus-ring-soft` | `focusBorder` |
| `--link` | `textLink.foreground` |
| `--bg-input`, `--bg-field` | `input.background` |
| `--bg-tab-selected`, `--border-tab-selected` | `tab.activeBackground`, `tab.activeBorderTop` |
| `--scrollbar-thumb`, `--scrollbar-thumb-hover` | `scrollbarSlider.background`, `scrollbarSlider.hoverBackground` |
| `--danger`, `--warning`, `--info` | `errorForeground`, `editorWarning.foreground`, `editorInfo.foreground` |
| `--vcs-modified`, `--vcs-added`, `--vcs-deleted`, `--vcs-untracked`, `--vcs-ignored`, `--vcs-conflict` | `gitDecoration.modifiedResourceForeground`, `.addedResourceForeground`, `.deletedResourceForeground`, `.untrackedResourceForeground`, `.ignoredResourceForeground`, `.conflictingResourceForeground` |
| `--fg-editor` | `editor.foreground` |
| `--caret` | `editorCursor.foreground` |
| `--bg-current-line` | `editor.lineHighlightBackground` |
| `--bg-editor-selection`, `--bg-editor-selection-inactive` | `editor.selectionBackground`, `editor.inactiveSelectionBackground` |
| `--fg-line-number`, `--fg-line-number-current` | `editorLineNumber.foreground`, `editorLineNumber.activeForeground` |
| `--border-indent-guide`, `--border-indent-guide-active` | `editorIndentGuide.background1`, `editorIndentGuide.activeBackground1` |
| `--fg-whitespace` | `editorWhitespace.foreground` |
| `--bg-text-search-result`, `--bg-text-search-result-current` | `editor.findMatchHighlightBackground`, `editor.findMatchBackground` |
| `--bg-matched-brace` | `editorBracketMatch.background` |
| `--syn-bracket-1` … `--syn-bracket-3` (Rainbow brackets) | `editorBracketHighlight.foreground1` … `foreground3` |
| `--bg-identifier-under-caret`, `-write` | `editor.wordHighlightBackground`, `editor.wordHighlightStrongBackground` |
| `--wave-error`, `--wave-warning` | `editorError.foreground`, `editorWarning.foreground` |
| `--gutter-modified`, `--gutter-added`, `--gutter-deleted` | `editorGutter.modifiedBackground`, `.addedBackground`, `.deletedBackground` |
| `--fg-inlay`, `--bg-inlay` | `editorInlayHint.foreground`, `editorInlayHint.background` |
| `--ansi-*` | `terminal.ansiBlack` … `terminal.ansiBrightWhite` |
`tokenColors` → syntax tokens, by TextMate scope:
| OpenIDEA token | Scope |
|---|---|
| `--syn-keyword` | `keyword`, `storage.type`, `storage.modifier` |
| `--syn-string` | `string` |
| `--syn-escape` | `constant.character.escape` |
| `--syn-number` | `constant.numeric` |
| `--syn-constant` | `constant.language`, `variable.other.constant` |
| `--syn-comment`, `--syn-doc-comment` | `comment`, `comment.block.documentation` |
| `--syn-function`, `--syn-function-call` | `entity.name.function`, `meta.function-call` |
| `--syn-type` | `entity.name.type`, `entity.name.class`, `support.class` |
| `--syn-variable`, `--syn-param` | `variable`, `variable.parameter` |
| `--syn-property` | `variable.other.property`, `variable.other.member` |
| `--syn-builtin`, `--syn-predefined` | `support.function`, `support.variable` |
| `--syn-self` | `variable.language.self`, `variable.language.this` |
| `--syn-annotation`, `--syn-decorator` | `meta.decorator`, `storage.type.annotation` |
| `--syn-punct` | `punctuation`, `keyword.operator` |
| `--syn-tag`, `--syn-attribute` | `entity.name.tag`, `entity.other.attribute-name` |
| `--syn-regexp` | `string.regexp` |
| `--syn-markup-heading`, `--syn-markup-code`, `--syn-link` | `markup.heading`, `markup.inline.raw`, `markup.underline.link` |
| `--syn-invalid` | `invalid` |
A `fontStyle: "italic"` on comments maps to `"--syn-comment-style": "italic"`.
## Testing a theme
- Install it from disk (or as a dev plugin), apply it, and walk through: the
Project tool window with a selection, the editor with a few languages, Search
Everywhere, a popup menu, a tooltip, Settings, the terminal (`ls --color`),
a diff, and the VCS colours in the Commit tool window.
- *Settings › Plugins* shows a load error (with the file and line) if the JSON
or a value is invalid. *Reload* re-reads a dev plugin.
- Text should keep at least WCAG AA contrast (4.5:1) on its surfaces. The
built-in themes are checked by `src/features/settings/__tests__/contrast.test.ts`.
- Repository checks (for changes to this repo): `pnpm vitest run scripts/theme`
validates the template and the theme plugins in `plugins/` against
tokens.css and keeps this reference current, and `cargo test -p ide-plugin`
loads them through the plugin host.
## Token reference
Generated from `src/styles/tokens.css` (the variables of its Islands Light
block, which redefines every colour token of Islands Dark). `pnpm gen:theme-docs`
regenerates it. The `scripts/theme` tests fail when it, or the template, misses
a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
203 themeable tokens: 113 in the UI theme file, 90 in the editor colour scheme file.
### Surfaces (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--bg-app` | `#191a1c` | `#ffffff` |
| `--bg-elev` | `#212326` | `#f7f8f9` |
| `--bg-popup` | `#26282c` | `#ffffff` |
| `--bg-hover` | `#2e2f30` | `#ededed` |
| `--bg-selected` | `#2a4371` | `#d0dffe` |
| `--bg-selected-strong` | `#2e4d89` | `#bdd3ff` |
| `--bg-current-line` | `#1f2024` | `#f5f8fe` |
| `--bg-debug-line` | `#2a5091` | `#d4e2ff` |
| `--bg-backdrop` | `#26282c` | `#e9eaee` |
| `--bg-input` | `#191a1c` | `#ffffff` |
### Lines (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--border` | `#26282c` | `#e9eaee` |
| `--border-popup` | `#33353b` | `#d1d3d9` |
| `--border-strong` | `#40434a` | `#d1d3d9` |
| `--border-window` | `#40434a` | `#d1d3d9` |
| `--control-off` | `#5f6269` | `#c3c5cb` |
### Text (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--fg-strong` | `#dfe1e5` | `#000000` |
| `--fg-emphasis` | `#d1d3d9` | `#000000` |
| `--fg` | `#d1d3d9` | `#000000` |
| `--fg-secondary` | `#9fa2a8` | `#5f6269` |
| `--fg-muted` | `#8c8f95` | `#6c707e` |
| `--fg-subtle` | `#73767c` | `#73767c` |
| `--fg-faint` | `#5f6269` | `#9fa2a8` |
| `--fg-gutter` | `#4b5059` | `#aeb3c2` |
| `--fg-icon` | `#ced0d6` | `#6c707e` |
### Accent (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--accent` | `#3871e1` | `#3871e1` |
| `--link` | `#71a1fe` | `#2f5eb9` |
| `--link-hover` | `#92b7ff` | `#2e4d89` |
### Charts (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--chart-series` | `#e07a7c` | `#d9686a` |
### Status (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--danger` | `#f57e84` | `#c54e58` |
| `--warning` | `#d59637` | `#a56906` |
| `--success` | `#6db083` | `#338555` |
| `--db-connected` | `#2fe02f` | `#00ff00` |
| `--db-connected-ring` | `#1d6b1d` | `#5b995b` |
| `--info` | `#548af7` | `#3871e1` |
### Vcs (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--vcs-modified` | `#70aeff` | `#0033b3` |
| `--vcs-added` | `#73bd79` | `#067d17` |
| `--vcs-deleted` | `#6f737a` | `#6c707e` |
| `--vcs-untracked` | `#e88f89` | `#b23247` |
| `--vcs-ignored` | `#d69a6b` | `#8c4f00` |
| `--vcs-conflict` | `#de6a66` | `#de1b2e` |
| `--gutter-modified` | `#375fad` | `#88adf7` |
| `--gutter-added` | `#549159` | `#7fc784` |
| `--gutter-deleted` | `#868a91` | `#767a8a` |
### Syntax (editor scheme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--syn-keyword` | `#cf8e6d` | `#0033b3` |
| `--syn-string` | `#6aab73` | `#067d17` |
| `--syn-type` | `#bcbec4` | `#000000` |
| `--syn-function` | `#56a8f5` | `#00627a` |
| `--syn-function-call` | `#bcbec4` | `#080808` |
| `--syn-comment` | `#7a7e85` | `#8c8c8c` |
| `--syn-comment-style` | `normal` | `italic` |
| `--syn-doc-comment` | `#5f826b` | `#8c8c8c` |
| `--syn-docstring` | `#5f826b` | `#067d17` |
| `--syn-annotation` | `#b3ae60` | `#9e880d` |
| `--syn-decorator` | `#b3ae60` | `#9e880d` |
| `--syn-number` | `#2aacb8` | `#1750eb` |
| `--syn-punct` | `#bcbec4` | `#080808` |
| `--syn-variable` | `#bcbec4` | `#080808` |
| `--syn-param` | `#bcbec4` | `#080808` |
| `--syn-property` | `#c77dbb` | `#871094` |
| `--syn-constant` | `#c77dbb` | `#871094` |
| `--syn-builtin` | `#8888c6` | `#000080` |
| `--syn-self` | `#94558d` | `#94558d` |
| `--syn-keyword-arg` | `#aa4926` | `#660099` |
| `--syn-predefined` | `#b200b2` | `#b200b2` |
| `--syn-escape` | `#cf8e6d` | `#0037a6` |
| `--syn-regexp` | `#42c3d4` | `#264eff` |
| `--syn-tag` | `#d5b778` | `#0033b3` |
| `--syn-attribute` | `#bcbec4` | `#174ad4` |
| `--syn-todo` | `#8bb33d` | `#008dde` |
| `--syn-link` | `#548af7` | `#006dcc` |
| `--syn-markup-heading` | `#cf8e6d` | `#871094` |
| `--syn-markup-code` | `#6aab73` | `#067d17` |
| `--syn-invalid` | `#f75464` | `#f50000` |
| `--syn-inline-value` | `#868a91` | `#8c8c8c` |
| `--syn-rainbow-1` | `#6fafbd` | `#9b3b6a` |
| `--syn-rainbow-2` | `#d79b6e` | `#114d77` |
| `--syn-rainbow-3` | `#9fbf6b` | `#9c6a2c` |
| `--syn-rainbow-4` | `#c98bc6` | `#005910` |
| `--syn-rainbow-5` | `#8e9cf0` | `#bc5150` |
| `--syn-bracket-1` | `#e8c25b` | `#0431fa` |
| `--syn-bracket-2` | `#d78bd6` | `#319331` |
| `--syn-bracket-3` | `#4ea7f0` | `#7b3814` |
### Editor (editor scheme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--fg-editor` | `#bcbec4` | `#080808` |
| `--caret` | `#ced0d6` | `#000000` |
| `--fg-line-number` | `#4b5059` | `#aeb3c2` |
| `--fg-line-number-current` | `#a1a3ab` | `#767a8a` |
| `--border-gutter` | `#26282c` | `#ebecf0` |
| `--border-indent-guide` | `#323438` | `#ebecf0` |
| `--border-indent-guide-active` | `#4e5157` | `#aeb3c2` |
| `--border-right-margin` | `#323438` | `#ebecf0` |
| `--bg-editor-selection` | `#214283` | `#a6d2ff` |
| `--bg-editor-selection-inactive` | `#1d3460` | `#c9e3ff` |
| `--bg-text-search-result` | `#114957` | `#fcd47e` |
| `--bg-text-search-result-current` | `#165e70` | `#f2bf57` |
| `--bg-matched-brace` | `#43454a` | `#93d9d9` |
| `--matched-brace-weight` | `var(--fw-code-bold)` | `inherit` |
| `--bg-matched-tag` | `#3f4045` | `#c9ecec` |
| `--bg-fold-placeholder` | `#393b40` | `#e9f5e6` |
| `--fg-fold-placeholder` | `#868991` | `#414d41` |
| `--fg-fold-marker` | `#6f737a` | `#8b8e94` |
| `--fg-whitespace` | `#6f737a` | `#b5b7bd` |
| `--fg-unused` | `#6f737a` | `#8c8c8c` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
| `--wave-warning` | `#f2c55c` | `#f2bf57` |
| `--editor-error-decoration` | `underline wavy #fa6675` | `underline wavy #f50000` |
| `--editor-warning-decoration` | `underline wavy #f2c55c` | `none` |
| `--editor-warning-background` | `transparent` | `#fcf4d4` |
| `--bg-breakpoint-line` | `#40252b` | `#faeae6` |
| `--fg-completion-match` | `#538af9` | `#2f5eb9` |
| `--bg-editor-inline` | `#212326` | `#f7f8f9` |
| `--bg-editor-banner` | `#233558` | `#f7f8ff` |
| `--fg-weak-warning` | `#6f737a` | `#a8adbd` |
| `--fg-bulb` | `#f2c55c` | `#ffaf0f` |
### ANSI palette (editor scheme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--ansi-black` | `#000000` | `#000000` |
| `--ansi-red` | `#f0524f` | `#e5372a` |
| `--ansi-green` | `#5c962c` | `#367a29` |
| `--ansi-yellow` | `#a68a0d` | `#ad8d2b` |
| `--ansi-blue` | `#3993d4` | `#3866d1` |
| `--ansi-magenta` | `#a771bf` | `#a33cae` |
| `--ansi-cyan` | `#00a3a3` | `#3c8b8d` |
| `--ansi-white` | `#808080` | `#8b8e94` |
| `--ansi-bright-black` | `#595959` | `#73767c` |
| `--ansi-bright-red` | `#ff4050` | `#f05046` |
| `--ansi-bright-green` | `#4fc414` | `#2e9b3f` |
| `--ansi-bright-yellow` | `#e5bf00` | `#b58e00` |
| `--ansi-bright-blue` | `#1fb0ff` | `#3d82f0` |
| `--ansi-bright-magenta` | `#ed7eed` | `#c04bcf` |
| `--ansi-bright-cyan` | `#00e5e5` | `#1b9ea3` |
| `--ansi-bright-white` | `#ffffff` | `#5f6269` |
### Shadows and window controls (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--shadow-popup` | `0 6px 20px rgba(0, 0, 0, 0.45)` | `0 6px 20px rgba(0, 0, 0, 0.12)` |
| `--shadow-dialog` | `0 0 0 0.5px rgba(0, 0, 0, 0.6), 0 10px 24px rgba(0, 0, 0, 0.35), 0 24px 72px rgba(0, 0, 0, 0.45)` | `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)` |
| `--traffic-close` | `#ff5f57` | `#ff5f57` |
| `--traffic-close-border` | `#e0443e` | `#e0443e` |
| `--traffic-close-pressed` | `#bf4942` | `#bf4942` |
| `--traffic-glyph` | `#4d0000` | `#4d0000` |
| `--traffic-off` | `#4b4c4f` | `#dddddd` |
| `--traffic-off-border` | `#404144` | `#c8c8c8` |
### Additive (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--bg-tooltip` | `#33353b` | `#ffffff` |
| `--fg-tooltip` | `#d1d3d9` | `#000000` |
| `--border-tooltip` | `#33353b` | `#d1d3d9` |
| `--bg-control` | `#26282c` | `#ffffff` |
| `--bg-control-hover` | `#33353b` | `#f7f8f9` |
| `--bg-active` | `#40434a` | `#dddfe4` |
| `--bg-scrim` | `rgba(0, 0, 0, 0.45)` | `rgba(0, 0, 0, 0.16)` |
| `--fg-on-accent` | `#ffffff` | `#ffffff` |
| `--shadow-tooltip` | `0 4px 12px rgba(0, 0, 0, 0.4)` | `0 4px 12px rgba(0, 0, 0, 0.12)` |
| `--shadow-balloon` | `0 8px 24px rgba(0, 0, 0, 0.45)` | `0 8px 24px rgba(0, 0, 0, 0.14)` |
### Islands contract (UI theme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--bg-frame` | `#26282c` | `#e9eaee` |
| `--bg-island` | `#191a1c` | `#ffffff` |
| `--bg-stripe-hover` | `#ffffff17` | `#00000012` |
| `--bg-stripe-selected` | `#ffffff29` | `#00000020` |
| `--fg-stripe-selected-active` | `#ffffff` | `#ffffff` |
| `--fg-stripe-label` | `#9fa2a8` | `#5f6269` |
| `--bg-tab-selected` | `#233558` | `#e3ebfe` |
| `--border-tab-selected` | `#2e4d89` | `#a7c5ff` |
| `--bg-tab-selected-inactive` | `#26282c` | `#e9eaee` |
| `--border-tab-selected-inactive` | `#40434a` | `#d1d3d9` |
| `--bg-tab-hover` | `#ffffff17` | `#00000012` |
| `--border-editor-tabs` | `#26282c` | `#e9eaee` |
| `--bg-tree-selected` | `#2a4371` | `#d0dffe` |
| `--bg-tree-selected-inactive` | `#33353b` | `#e9eaee` |
| `--bg-tree-hover` | `#ffffff10` | `#00000008` |
| `--bg-toolbar-hover` | `#ffffff17` | `#00000012` |
| `--bg-toolbar-pressed` | `#ffffff29` | `#00000020` |
| `--bg-toolbar-selected` | `#2e4d89` | `#d0dffe` |
| `--bg-toolbar-selected-hover` | `#2f5eb9` | `#bdd3ff` |
| `--bg-button-primary-hover` | `#2f5eb9` | `#2f5eb9` |
| `--fg-button-primary` | `#ffffff` | `#ffffff` |
| `--bg-button` | `transparent` | `#ffffff` |
| `--border-button` | `#40434a` | `#d1d3d9` |
| `--bg-field` | `#191a1c` | `#ffffff` |
| `--bg-checkbox` | `#191a1c` | `#ffffff` |
| `--border-checkbox` | `#5f6269` | `#a8adbd` |
| `--bg-toggle-on` | `#338555` | `#4e9d6c` |
| `--fg-toggle-on` | `#ffffff` | `#ffffff` |
| `--bg-toggle-off` | `#191a1c` | `#f7f8f9` |
| `--fg-toggle-off` | `#73767c` | `#73767c` |
| `--border-toggle` | `#5f6269` | `#c3c5cb` |
| `--bg-toggle-knob` | `#5f6269` | `#c3c5cb` |
| `--focus-ring-soft` | `#3d6185` | `#97c3f3` |
| `--scrollbar-thumb` | `#ffffff33` | `#00000033` |
| `--scrollbar-thumb-hover` | `#ffffff59` | `#00000080` |
| `--bg-search-match` | `#ba9752` | `#fee6b1` |
| `--bg-search-match-current` | `#f2c55c` | `#fcd47e` |
| `--fg-search-match` | `#191a1c` | `#000000` |
| `--bg-dialog` | `#191a1c` | `#f7f8f9` |
| `--bg-popup-inline` | `#26282c` | `#f7f8f9` |
| `--bg-popup-advertiser` | `#26282c` | `#f7f8f9` |
| `--bg-feedback-info` | `#233558` | `#f7f8ff` |
| `--border-feedback-info` | `#2e4d89` | `#bdd3ff` |
| `--bg-feedback-error` | `#56272b` | `#fff6f5` |
| `--border-feedback-error` | `#80383e` | `#ffc4c5` |
| `--bg-feedback-warning` | `#44321d` | `#fff6e9` |
| `--border-feedback-warning` | `#694820` | `#f4cd9a` |
| `--bg-feedback-success` | `#203b2a` | `#f5faf3` |
| `--border-feedback-success` | `#29583c` | `#bbdbc2` |
| `--bg-counter` | `#73767c` | `#8b8e94` |
| `--fg-counter` | `#000000` | `#ffffff` |
| `--bg-progress-track` | `#40434a` | `#dddfe4` |
<!-- END GENERATED TOKEN REFERENCE -->
+10 -2
Переглянути файл
@@ -4,8 +4,16 @@ test("⌘, opens Settings with the page tree; Escape closes", async ({ workbench
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings" });
await expect(dialog).toBeVisible();
for (const name of ["Appearance & Behavior", "Keymap", "Editor", "Plugins", "Version Control"]) {
await expect(dialog.getByRole("treeitem", { name, exact: true })).toBeVisible();
const item = (name: string) => dialog.getByRole("treeitem", { name, exact: true });
for (const name of ["Appearance & Behavior", "Keymap", "Editor"]) {
await expect(item(name)).toBeVisible();
}
// The tree is virtualized: collapse Editor (expanded by default) so the later groups render.
await item("Editor").click();
await page.keyboard.press("ArrowLeft");
await expect(item("Editor")).not.toHaveAttribute("aria-expanded", "true");
for (const name of ["Plugins", "Version Control"]) {
await expect(item(name)).toBeVisible();
}
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
+5 -2
Переглянути файл
@@ -10,12 +10,15 @@
<body>
<div id="root"></div>
<div id="splash" class="splash" data-tauri-drag-region>
<svg viewBox="0 0 64 64" aria-hidden="true">
<svg class="splash-logo" viewBox="0 0 64 64" aria-hidden="true">
<rect width="64" height="64" rx="15" fill="#0E0E10" />
<circle cx="26" cy="32" r="11" fill="none" stroke="#FFFFFF" stroke-width="8" />
<rect x="43" y="18" width="8" height="28" rx="1.5" fill="#FF4F1A" />
</svg>
<span>OpenIDEA</span>
<!-- "OpenIDEA" in Inter 500 as outlines: the web font loads late in dev and would swap in. -->
<svg class="splash-wordmark" viewBox="0 -1984 9994 2478" role="img" aria-label="OpenIDEA">
<path fill="currentColor" d="M785.8 20Q592.6 20 440.4 -71.7Q288.2 -163.4 200.4 -334.7Q112.6 -506 112.6 -744Q112.6 -983.2 200.4 -1154.6Q288.2 -1326 440.4 -1418Q592.6 -1510 785.8 -1510Q979 -1510 1130.7 -1418Q1282.4 -1326 1369.8 -1154.6Q1457.3 -983.2 1457.3 -744Q1457.3 -505.8 1369.8 -334.5Q1282.4 -163.2 1130.7 -71.6Q979 20 785.8 20ZM785.8 -187.7Q913 -187.7 1013.5 -251.6Q1114 -315.5 1172.4 -439.9Q1230.7 -564.3 1230.7 -744Q1230.7 -925.6 1172.4 -1050Q1114 -1174.5 1013.5 -1238.4Q913 -1302.3 785.8 -1302.3Q657.9 -1302.3 557 -1238Q456.1 -1173.7 397.7 -1049.2Q339.2 -924.7 339.2 -744Q339.2 -564.3 397.7 -440.3Q456.1 -316.3 557 -252Q657.9 -187.7 785.8 -187.7ZM1717.9 418V-1118H1932.2V-935.9H1950.4Q1970 -970.8 2005.4 -1016.7Q2040.9 -1062.7 2104.6 -1097.3Q2168.3 -1132 2272.6 -1132Q2407.4 -1132 2512.7 -1064Q2617.9 -996 2678.8 -867Q2739.8 -738 2739.8 -556.4Q2739.8 -375.7 2679.8 -246.2Q2619.8 -116.7 2514.5 -47.3Q2409.1 22.2 2272.7 22.2Q2171.8 22.2 2107.4 -12.4Q2043 -47 2006.6 -93.2Q1970.2 -139.3 1950.4 -175H1937.9V418ZM2224 -165.3Q2320.1 -165.3 2384.9 -217.3Q2449.6 -269.3 2482.4 -358.3Q2515.2 -447.3 2515.2 -558Q2515.2 -668.1 2482.8 -755.4Q2450.4 -842.8 2385.7 -893.7Q2321 -944.5 2224 -944.5Q2129.6 -944.5 2065 -896.1Q2000.4 -847.7 1967.4 -761.2Q1934.4 -674.6 1934.4 -558Q1934.4 -441.7 1967.8 -353.2Q2001.2 -264.7 2066.2 -215Q2131.2 -165.3 2224 -165.3ZM3465.8 23.3Q3300.7 23.3 3181.1 -48.1Q3061.4 -119.5 2996.9 -248.5Q2932.4 -377.5 2932.4 -551.1Q2932.4 -723.3 2995.8 -854Q3059.1 -984.7 3175.1 -1058.4Q3291 -1132 3446.8 -1132Q3542.6 -1132 3632 -1100.7Q3721.4 -1069.4 3792.3 -1002.3Q3863.3 -935.2 3904.7 -828.3Q3946.2 -721.5 3946.2 -570.3V-492.2H3054.8V-656.5H3832.8L3730.1 -602.3Q3730.1 -704.7 3698.2 -783.2Q3666.3 -861.7 3603.5 -905.9Q3540.8 -950 3447.5 -950Q3354.2 -950 3288.2 -905Q3222.1 -860 3187.4 -786.5Q3152.6 -712.9 3152.6 -626.1V-514.4Q3152.6 -399.4 3192.1 -319.8Q3231.6 -240.1 3302.9 -199.4Q3374.2 -158.7 3468.1 -158.7Q3529.6 -158.7 3579.9 -176.3Q3630.2 -194 3666.5 -229.4Q3702.8 -264.9 3722.2 -317.2L3928.6 -268.5Q3902.2 -181.6 3838.6 -115.9Q3775 -50.2 3680.4 -13.4Q3585.8 23.3 3465.8 23.3ZM4406.9 -662.4V0H4186.9V-1118H4396.6L4398.9 -844.3H4376.2Q4424.9 -994.3 4517.8 -1063.1Q4610.7 -1132 4742.5 -1132Q4856.6 -1132 4942 -1084.2Q5027.5 -1036.3 5075.1 -942.5Q5122.7 -848.8 5122.7 -710.4V0H4902.7V-682.9Q4902.7 -803.7 4839.8 -872.1Q4776.9 -940.5 4667.3 -940.5Q4592.9 -940.5 4533.8 -907.9Q4474.8 -875.3 4440.8 -813.3Q4406.9 -751.2 4406.9 -662.4ZM5664.4 -1490V0H5435.9V-1490ZM6478.5 0H6109.9V-199.7H6465.8Q6635 -199.7 6747.1 -263Q6859.2 -326.3 6915 -448.6Q6970.8 -571 6970.8 -747.3Q6970.8 -922.1 6915.2 -1043.3Q6859.7 -1164.4 6750.5 -1227.4Q6641.3 -1290.3 6478.4 -1290.3H6102.2V-1490H6493Q6713.2 -1490 6869.9 -1400.9Q7026.7 -1311.8 7110.7 -1145.2Q7194.7 -978.6 7194.7 -747.3Q7194.7 -514.5 7110.4 -347.1Q7026 -179.6 6865.8 -89.8Q6705.5 0 6478.5 0ZM6222.4 -1490V0H5993.9V-1490ZM7471.9 0V-1490H8409.8V-1293.6H7700.4V-849.7H8359.5V-654.7H7700.4V-196.4H8416.4V0ZM8592.9 0 9123.5 -1490H9403.2L9942.8 0H9696.3L9406.1 -828.9Q9372.2 -930 9331.8 -1066.9Q9291.4 -1203.8 9238.4 -1395.6H9284.5Q9232.7 -1202.2 9192.5 -1063.6Q9152.4 -925.1 9121.4 -828.9L8839.9 0ZM8880.4 -392.6V-583.1H9655.3V-392.6Z" />
</svg>
<div class="splash-bar" role="progressbar" aria-label="Loading"><i></i></div>
</div>
<script type="module" src="/src/main.tsx"></script>
+1 -1
Переглянути файл
@@ -10,5 +10,5 @@ tree-sitter = "css"
name = "vscode-css-language-server"
command = "vscode-css-language-server"
args = ["--stdio"]
initialization-options = { provideFormatter = true }
initialization-options = { provideFormatter = true, css = {}, scss = {}, less = {} }
install-hint = "npm i -g vscode-langservers-extracted"
+26
Переглянути файл
@@ -0,0 +1,26 @@
id = "gdscript"
name = "GDScript"
extensions = ["gd"]
line-comment = "#"
# Godot's default (Editor Settings › Text Editor › Behavior › Indent › Type).
indent = { tab-size = 4, insert-spaces = false }
tree-sitter = "gdscript"
# The language server runs inside the Godot editor and speaks LSP over TCP only:
# connect to an open editor, else start a headless editor for the project on a free port.
[[language-servers]]
name = "godot"
command = "godot"
args = ["--headless", "--editor", "--path", "${root}", "--lsp-port", "${port}"]
connect = "127.0.0.1:6005"
root-markers = ["project.godot"]
install-hint = "Open the project in the Godot editor, or install Godot 4 and set the Godot executable in Settings › Languages & Frameworks › Language Servers › godot"
# Godot's debug adapter also lives in the editor (DAP over TCP, port 6006).
[debugger]
adapter = "godot"
command = "godot"
args = ["--headless", "--editor", "--path", "${root}", "--dap-port", "${port}"]
transport = "tcp"
connect = "127.0.0.1:6006"
install-hint = "Open the project in the Godot editor, or install Godot 4 and set the Godot executable in Settings › Languages & Frameworks › Language Servers › godot"
+8
Переглянути файл
@@ -0,0 +1,8 @@
id = "gdshader"
name = "Godot Shader"
extensions = ["gdshader", "gdshaderinc"]
line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 4, insert-spaces = false }
# GLSL-like: the C mode colours keywords, types, numbers and comments.
ui-mode = "C"
+8
Переглянути файл
@@ -0,0 +1,8 @@
id = "godot-resource"
name = "Godot Resource"
# Text scenes / resources, `project.godot`, import metadata and export presets (INI-like).
extensions = ["tscn", "tres", "godot", "import"]
filenames = ["export_presets.cfg", "override.cfg", "extension_list.cfg"]
line-comment = ";"
indent = { tab-size = 4, insert-spaces = false }
ui-mode = "Properties files"
+1 -1
Переглянути файл
@@ -22,7 +22,7 @@ fallback = true
command = "typescript-language-server"
args = ["--stdio"]
root-markers = ["jsconfig.json", "tsconfig.json", "package.json"]
install-hint = "npm i -g typescript typescript-language-server"
install-hint = "npm i -g typescript@\"<7\" typescript-language-server"
[debugger]
adapter = "js-debug"
+1 -1
Переглянути файл
@@ -21,7 +21,7 @@ fallback = true
command = "typescript-language-server"
args = ["--stdio"]
root-markers = ["jsconfig.json", "tsconfig.json", "package.json"]
install-hint = "npm i -g typescript typescript-language-server"
install-hint = "npm i -g typescript@\"<7\" typescript-language-server"
[debugger]
adapter = "js-debug"
+1 -1
Переглянути файл
@@ -10,5 +10,5 @@ ui-mode = "LESS"
name = "vscode-css-language-server"
command = "vscode-css-language-server"
args = ["--stdio"]
initialization-options = { provideFormatter = true }
initialization-options = { provideFormatter = true, css = {}, scss = {}, less = {} }
install-hint = "npm i -g vscode-langservers-extracted"
Loaded 100 of 454 files, more files were not shown because too many files have changed in this diff. Show more