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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 56d9788747 fix(vcs): scroll the changes tree horizontally instead of clipping rows
Rows in the Commit and Local Changes trees were locked to the pane width and
ellipsized, so the end of a long file name and its directory path could only
be read by widening the tool window. The tree now keeps rows at their natural
width and scrolls horizontally, as the Project view does.

Fixes #6080
2026-11-26 16:10:01 +08:00
l0ng-ai ef1b159544 fix(editor): keep what a diff revert or gutter rollback put back when saving (#6112)
Save cleanup treated text a diff revert or gutter rollback restored from the VCS version as the user's edit: reverting an added line break at the end of a file had it added back on the next save (Ensure every saved file ends with a line break, or editorconfig insert_final_newline), so the change came back. Restored text no longer counts as edited for trailing-space stripping, and when a revert last changed the end of the file, saving leaves its line break and trailing blank lines alone until the user edits there again.
2026-11-26 15:13:40 +08:00
l0ng-ai 7bfba926c2 fix(build-tools): don't offer to attach a folder as another root in a remote window (#6096)
Import Module from Existing Sources asked to attach a folder without a build file as another root, but Attach runs project.attachFolder, which is only enabled in a local project, so in a remote window the confirmation silently did nothing. When the action isn't enabled, the import now says the folder can't be attached as another root in this window instead of offering it.
2026-11-26 14:30:58 +08:00
l0ng-aiтаClaude Opus 5.5 1042f5fa56 fix(i18n): update the catalogs for the run.createConfig description (#6095)
#6079 extended the run.createConfig action's description, so every locale catalog still keyed the old text and the source-text catalog tests failed on main. Rekeys the entry in all catalogs with the new clause translated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:30:01 +08:00
l0ng-ai fdad01034c fix(format): keep language-server range formatting on the selected lines (#6088)
Reformat Code with a selection sent textDocument/rangeFormatting and applied every edit the server returned. Intelephense answers a range request with edits across the whole file, so formatting two selected lines of a PHP file rewrote quotes and parentheses elsewhere ("Formatted 45 lines"); the second time nothing outside was left to change, so it looked like a first-open problem. Language-server range formatting now keeps only the edits on the selected lines; a changed region that reaches past them and keeps its line count is split per line first.

Part of #6055
2026-11-26 13:43:21 +08:00
l0ng-ai 6dddfde3bc fix(run): keep a saved configuration when its gutter action creates it again (#6079)
"Modify Run Configuration…" from a Dockerfile's gutter icon (and the Maven tool window's Create Run Configuration) saved a freshly built configuration over the saved one with the same fixed id, so the bound ports and other edits were gone the next time it was opened. A saved configuration with that id now opens as the user left it; only a new one is saved.

Fixes #6047
2026-11-26 13:33:39 +08:00
l0ng-ai 0324bc368d fix(python): list the folders on the interpreter's sys.path in External Libraries (#6078)
External Libraries listed only the interpreter's sysconfig folders (stdlib, platstdlib, purelib, platlib). For Ubuntu's /usr/bin/python3, purelib is the usually empty /usr/local/lib/python3.X/dist-packages, while the packages apt installs (/usr/lib/python3/dist-packages) and the user's site-packages are only on sys.path, so the interpreter's libraries looked missing. The library group now also lists the other folders on the interpreter's sys.path (queried without the IDE's PYTHONPATH), except those inside or around the project's folders, which an editable install's .pth puts there.

Fixes #6042
2026-11-26 13:27:21 +08:00
l0ng-ai 96c6e65aad fix(debugger): end lines typed into a debugged program's terminal with Enter (#6077)
The Debug console sent input typed into a debugged program's terminal ending in LF. Windows' ConPTY reads LF as Ctrl+J, so a program blocked in input() never saw its line end. Line ends are now sent as CR, as a terminal does for Enter; a Unix terminal maps it back to the newline a line read waits for.

Fixes #6041
2026-11-26 13:24:40 +08:00
l0ng-ai 6eebd895ea fix(remote): refuse a hand-placed server of another version instead of failing with EOF (#6076)
When the server for this version can't be downloaded, a hand-placed openidea-server in the local data dir was uploaded regardless of its version, and a server of another version failed the handshake with a bare "EOF inside message header". Use it only when it contains this version string; otherwise report the download error and the stale file to delete or replace.

Fixes #5742
2026-11-26 13:21:11 +08:00
l0ng-ai cfad729dbd fix(linux): use the bundled JetBrains Mono unless the system has it installed (#6074)
WebKitGTK looks the editor's "JetBrains Mono" up through fontconfig, and
a rule that strongly aliases unknown families (CJK locales put Noto Sans
CJK first) makes it resolve to that proportional face instead of falling
through to the bundled "JetBrains Mono Variable". On Linux the bundled
face is now named alone, in the editor/terminal stacks and --font-mono,
unless the native font catalog lists an installed JetBrains Mono.

Fixes #5770
2026-11-26 13:15:42 +08:00
Mansur Akhmadiтаmansur-akhmadi bd905c6689 feat(run): Up / Down the Stack Trace in the Run console (#6060)
In a run console that isn't a test run, Previous / Next Occurrence now step
through the file links in the output (skipping URLs, the IDE's own lines and
collapsed folds), select the link, scroll it to the centre and open its target,
and the console toolbar shows them as Up / Down the Stack Trace. Test runs keep
stepping through failed tests.

Closes #6059

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 13:11:24 +08:00
Mansur Akhmadiтаmansur-akhmadi 7138becb3a feat(code-insight): Recent Find Usages action (#6000)
Adds IDEA's Recent Find Usages (find.recentUsages, Find category): every Find
Usages run (first search, Rerun, Search in Libraries) is recorded, newest first,
one per caret position, up to 10, cleared on project switch; the action lists
them in a centered menu and runs the chosen one again in a new tab, opening the
file's document when no editor has it. Unbound by default; IDEA keymap import
maps ShowRecentFindUsagesGroup.

Closes #5999

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 13:07:18 +08:00
Mansur Akhmadiтаmansur-akhmadi 6f7d2ce34d feat(vcs): Annotate Revision in the annotate gutter's context menu (#6011)
Adds Annotate Revision to the annotate gutter's context menu, before Annotate
Previous Revision: the file as of the clicked line's commit against the
working file, annotated on the left (the view Annotate at Revision... opens),
read from the line's origin path when blame reports a rename. Uncommitted
lines don't get the item.

Closes #6010

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 13:06:33 +08:00
Mansur Akhmadiтаmansur-akhmadi 719961e34e feat(editor): Scroll to Top / Scroll to Bottom actions (#6054)
Adds IDEA's Scroll to Top / Scroll to Bottom (EditorScrollTop /
EditorScrollBottom) as Editor Actions next to Scroll Up / Down: Top sets the
scroller to 0 keeping the horizontal position, Bottom brings the end of the
document to the centre; neither moves the caret or the selection. Unbound by
default as in IDEA's default keymaps; IDEA keymap import maps them.

Closes #6053

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 13:05:38 +08:00
Mansur Akhmadiтаmansur-akhmadi 11c432fc23 feat(editor): Move Caret Forward / Backward a Paragraph actions (#6005)
Adds IDEA's Move Caret Forward / Backward a Paragraph and their with-selection
variants (EditorForwardParagraph, EditorBackwardParagraph, ...WithSelection)
as Editor Actions. Blank lines are whitespace-only lines; Forward stops at the
start of the next blank line or the end of the text, Backward at the empty
line before the paragraph, as IDEA's ForwardParagraphAction /
BackwardParagraphAction. Unbound by default; IDEA keymap import maps them.

Closes #6004

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 13:04:44 +08:00
Mansur Akhmadiтаmansur-akhmadi 0b8698e47c feat(editor): Swap Selection Boundaries action (#5997)
Adds IDEA's Swap Selection Boundaries (EditorSwapSelectionBoundaries) as
editor.swapSelectionBoundaries in Editor Actions: each non-empty selection
swaps anchor and head, plain carets stay, the primary range stays primary;
with no selection it does nothing. No default shortcut, as in IDEA; IDEA
keymap import and IdeaVim :action map to it.

Closes #5996

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 13:03:05 +08:00
Mansur Akhmadiтаmansur-akhmadi f595a7abf0 feat(editor): Select Line at Caret action (#5994)
Adds IDEA's Select Line at Caret (EditorSelectLine) as editor.selectLine in
Editor Actions: each caret or selection grows to the whole lines it touches
plus the line break after them (to the end of the text on the last line); a
folded region's lines go with the line it is shown on. No default shortcut,
as in IDEA; IDEA keymap import and IdeaVim :action map to it.

Closes #5993

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 13:01:53 +08:00
l0ng-ai fe7fa7d505 fix(java): keep Maven system-scope jars on the run classpath (#6070)
The IDE build's Maven extension left system-scope dependencies out of
the runtime classpath it records, and launches built by the IDE replay
that classpath, so a Spring Boot app whose POM points at lib/*.jar with
<systemPath> failed with NoClassDefFoundError. A systemPath names an
explicit file the JVM must load (IDEA imports the scope as Compile);
provided stays excluded. The rebuilt jar changes java_build_version, so
existing build models are prepared again.

Fixes #6023
2026-11-26 13:00:14 +08:00
l0ng-ai e998e2ca8e fix(database): keep the checked values in a column's local filter (#6067)
The column header's local filter popup started with every value checked and a
click unchecked the value, so checking a value hid its rows. As in DataGrip,
values now start unchecked, the checked ones are the rows shown, and a column
with no value checked is not filtered.

Fixes #6022
2026-11-26 12:55:47 +08:00
audichuang 18424b322f fix(editor): check the disk before autosave overwrites an external change (#5991)
Autosave (tab switch, window blur) refused to overwrite an external change
only once the file watcher's debounced event had set disk_conflict, so an
external write followed by a blur inside that window was overwritten with the
older buffer. autosave() now compares the file's (mtime, length) with the
stamp of the disk state the buffer last loaded or wrote, right before writing;
on a mismatch it marks the conflict like the watcher path (including dropping
the clean text), emits DocDiskConflict and returns false. Explicit Save still
overwrites.

Co-authored-by: audichuang <[email protected]>
2026-11-26 12:52:41 +08:00
audichuang daee26e680 fix(editor): stop adding theme rules for every editor tab and notebook cell (#5995)
breakpointGutter, inlineBlame, indexedMarkers and the notebook CellEditor
built EditorView.theme / baseTheme inside their factories, so every editor or
notebook cell mounted a new style module whose rules CodeMirror never removes
(+12 rules per file editor, +1.4k while scrolling a 100-cell notebook). The
four themes are now module constants, like the other editor themes; the font
theme in setup.ts is already cached per key.

Co-authored-by: audichuang <[email protected]>
2026-11-26 12:51:14 +08:00
Alexanderтаformiat 5886e055b4 fix(vcs): F7 goes on to the next file in diffs opened from a changes tree (#6052)
A diff opened from a changes tree (Compare with Local / Compare with Branch,
Changes Between, push dialog, rebase plan) was a single-file diff with no
chain, so F7 at the last difference had no next file. Opening a file from the
shared ComparisonTree and the Changes Between dialog's Show Diff now pass the
tree's files in display order as the chain (chainedDiff), like Git Log commit
details already do.

Closes #6051

Co-authored-by: formiat <[email protected]>
2026-11-26 12:50:09 +08:00
LU XIANGRUIтаwildcatDownstairs 8d4b360933 fix(search): show the full path in the Find in Files directory field (#6057)
With the Directory scope selected, Find in Files showed the stored absolute
directory with the project root stripped (`src`, or `.` for the root itself).
The field now shows the full path; a typed relative path is still resolved
against the project root when searching.

Closes #6024

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 12:48:53 +08:00
l0ng-ai f6704b53f6 fix(clipboard): read text natively on Windows instead of prompting (#6065)
Windows had no native clipboard text read, so Paste from a menu, Vim's "+p, terminal paste and other clipboard reads fell back to navigator.clipboard.readText(), and WebView2 asked the user to allow clipboard access. Read CF_UNICODETEXT through the native clipboard instead; an empty clipboard reads as empty text so it never falls back to the WebView.
2026-11-26 12:46:58 +08:00
l0ng-ai 91da88d09d revert(browser): take the Open Local Browser panel out for now (#6027)
The panel needed the workbench to run as a child webview, which on macOS declines key equivalents, so Command shortcuts went to the native menu and many were lost (#5954, #5992). Reverts #5788, #5917 and the #5956 key-monitor workaround; the workbench webview is the window's own view again on every platform. The panel can come back once it no longer needs a child webview.
2026-11-26 10:25:25 +08:00
l0ng-ai 5ab91245dd chore: v0.1.53 2026-11-26 08:16:53 +08:00
audichuang fb063c1f84 fix(editor): undoing back to the saved text marks the document unmodified (#5985)
Undoing edits back to the saved text left the document marked modified. The
text buffer now remembers the text last known to match the file, and an edit,
undo or redo that returns to it clears the dirty flag. Rolling back a workspace
edit keeps the external-change warning when the buffer stays dirty, so autosave
still leaves a file changed on disk alone.

Co-authored-by: audichuang <[email protected]>
2026-11-26 07:26:54 +08:00
audichuang f926390d2e fix(console): find and copy console lines cut at 8,000 characters (#5989)
The Run and Debug consoles cut an output line longer than 8,000 characters into
separate rows and nothing treated those rows as one line again: Find missed a
string spanning the cut, and Copy All, Select All + Copy and copied selections
inserted a line break at every cut. A cut row is now marked as continuing the
next: Find searches the joined line and highlights the match on each row it
covers, and copying and the output replay join the rows. Rendering is
unchanged.

Co-authored-by: audichuang <[email protected]>
2026-11-26 07:13:56 +08:00
Mansur Akhmadiтаmansur-akhmadi 9b66744e72 feat(editor): Hungry Backspace action (#5988)
Adds Hungry Backspace (code.hungryBackspace, EditorHungryBackSpace for imported
keymaps and IdeaVim :action): a caret right after a space, tab or line break
deletes the whole whitespace run before it, across lines; a caret after
anything else, or a selection, gets a plain Backspace, so an empty bracket pair
still goes as one. Unbound by default, reachable from Find Action and
Settings > Keymap.

Closes #5987

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 07:06:38 +08:00
audichuang 071f768635 fix(http-client): keep the response find bar's keys away from the IDE keymap (#5983)
Escape and F3 typed in the HTTP Client response find bar ran IDE actions: the
view never registered a key claim for the bar, as the Run and Debug consoles
do. After clicking the Raw/Formatted toggle, Cmd+F no longer opened the bar
because its handler sat only on the body pane and WebKit does not focus a
clicked button; the handler now covers the whole exchange view and the toggle
hands focus back to the body.

Co-authored-by: audichuang <[email protected]>
2026-11-26 07:03:55 +08:00
audichuang bbe9cf7a86 fix(build): copy the whole build output after Select All (#5984)
Select All then Copy in the Build output copied only the rows the virtual list
had mounted. The Build console now does what the Run console does: Cmd/Ctrl+A
selects the output container, and a fully selected container copies every line
from the store, through both the key path and the native copy event. On macOS
the Edit menu's Select All (a selectstart on the body) is redirected to the
output while it has focus.

Co-authored-by: audichuang <[email protected]>
2026-11-26 07:03:44 +08:00
l0ng-ai c10d2f0732 perf(index): classify binary files from their head without reading them whole (#5990)
The index worker read every file up to 2 MiB in full and blake3-hashed it before checking the first 8 KiB for NUL, so binary files were loaded and hashed only to be skipped. Extraction now reads the first 8 KiB, stops on NUL, and reads the rest only for text; binary records keep a zero hash. A warm start that falls back to the full walk now logs the reason.

Refs #4792
2026-11-26 07:03:26 +08:00
audichuang ec02a121e9 fix(build): say how many lines the Build output's line cap discarded (#5982)
The Build tool window keeps the last 20,000 console lines and dropped older
ones with nothing on screen, so a long build silently lost its beginning. The
Build store now counts the lines the cap drops and the Build output shows the
"N earlier lines were discarded" notice the Run and Debug consoles already
show; the count resets with each new build.

Co-authored-by: audichuang <[email protected]>
2026-11-26 07:03:09 +08:00
audichuang 12eb2db641 fix(project): keep Gradle submodules in module lists after a sync (#5977)
Source roots reported by a Gradle sync were all stamped with detected_from "Gradle", so the module lists (project tree module markers, VCS change modules, new-file package lookup) collapsed every subproject into the root module after a sync. gradle_source_roots now also returns the project directory that reported each root, and with_gradle_roots stamps "<module>/Gradle" for subprojects under the project root (plain "Gradle" for the root project and for included builds outside it). The JVM build-file patterns in folderPresentation and the file templates accept the "Gradle" marker so these roots keep their source/test presentation.

Co-authored-by: audichuang <[email protected]>
2026-11-26 06:38:17 +08:00
Mansur Akhmadiтаmansur-akhmadi 2735d45d7e feat(vcs): Names in the annotate gutter's Options (initials, last, first or full name) (#5981)
Adds the annotate gutter's Options › Names submenu: Initials, Last Name, First Name and Full Name, with Last Name as the default. Names are shortened as IDEA's ShortNameType does: an <email> part is dropped, a bare email's local part is split on delimiters, initials also split on delimiters, and a name taken from an email is capitalized. The choice is remembered and shared across windows, and every annotated editor, including historical annotations, re-blames when it changes. The commit popup and inline blame keep the full name.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 06:33:58 +08:00
audichuang 60262c92ba test(workbench): wait for the toolbar label cap before measuring narrowed labels (#5976)
After shrinking the viewport, mainToolbarLayout.spec.ts polled only the
short branch label and then read the project and run label widths at
once. The label cap is applied from a ResizeObserver in the next
animation frame, so the read could land before the labels shrank. The
test now polls until both long labels are narrower than their preferred
width before asserting.

Co-authored-by: audichuang <[email protected]>
2026-11-26 06:28:58 +08:00
Vladislav Kuzmin ca472742bf fix(macos): restore workbench shortcuts from the editor (#5956)
Since the multi-webview change, Wry builds the workbench WKWebView as a
child view that declines every key equivalent, so AppKit sent Command
shortcuts straight to the native menu, where keymap-drawn items are
dropped during key handling. ⌘0 / ⌘1 and other workbench shortcuts
could then stop working from the editor.

A local key monitor now gives the focused workbench webview first
refusal for the printable Command shortcuts its current keymap shows in
the menu, only when that webview is the window's first responder and no
sheet is attached. Native clipboard commands keep AppKit's path. Undo
and Redo use the focused CodeMirror history, with the Edit menu as the
fallback when the page declines.

Closes #5954

Co-authored-by: principalwater <[email protected]>
2026-11-26 06:25:50 +08:00
Deng Liuтаdengliu 023408eb26 fix(keymap): allow toggling plugin tool windows from plugin webviews (#5979)
A shortcut that opens a plugin tool window moves focus into the plugin's frame. Without ide.commands, the frame's forwarded keys could only run the static FORWARDABLE_ACTIONS, so pressing the same shortcut again could not close the pane. Forwarded keys may now also toggle the tool window enclosing the frame (except the terminal) and the plugin's own toolwindow.plugin.<id>.* windows; other plugins' windows and plugin commands stay blocked.

Co-authored-by: dengliu <[email protected]>
2026-11-26 05:46:05 +08:00
audichuang 92c0e304cd fix(vcs): open the all-in-one diff at the staged or unstaged block that was opened (#5974)
With Show All Files in One Diff View and the staging area on, a partially staged file is listed twice in the all-in-one diff. The tab revealed its block by path, so opening the unstaged entry scrolled to the staged block. openDiff now passes the opened diff's key and the tab reveals that block, falling back to the path.

Co-authored-by: audichuang <[email protected]>
2026-11-26 05:43:27 +08:00
Vadim LazukтаInf1mum 3d534b447d feat(run): run and debug a .NET project file from the project view (#5969)
The Project view context menu on a .csproj / .fsproj / .vbproj offers
Run '<name>' / Debug '<name>' / More Run/Debug. It produces a temporary
dotnet configuration (`dotnet run --project <file> --no-launch-profile`,
built first by the dotnetBuild before-launch step, debugged through
netcoredbg), so it launches and edits like a saved one. Solutions keep
only Build / Restore / Clean; launch profiles stay on the
launchSettings.json gutter.

The run feature recognises project files itself instead of importing
the dotnet feature.

Refs #5635

Co-authored-by: Inf1mum <[email protected]>
2026-11-26 05:33:04 +08:00
Deng Liuтаdengliu 89a3359aaf feat(terminal): add New Terminal Tab in Editor action and keyWhen-aware conflict checks (#5973)
Adds New Terminal Tab in Editor (terminal.newInEditor, unbound by default), which opens a fresh terminal session as an editor tab. Its keyWhen keeps it out of the Terminal tool window and popups, so it can share a key such as Cmd+T with New Terminal Tab, and editor terminal sessions pass its shortcut to the IDE. Keymap conflict detection now combines an action's when and keyWhen, so bindings in disjoint focus contexts are no longer reported as conflicts.

Co-authored-by: dengliu <[email protected]>
2026-11-26 05:23:30 +08:00
Mansur Akhmadiтаmansur-akhmadi d88c4c87b6 feat(run): Select First Failed Test When Finished in Test Runner Options (#5972)
Adds the Select First Failed Test When Finished toggle under Test Runner Options and in Find Action (off by default, stored with the other test tree options). When a run finishes with it on, the test tree selects the first failure in tree order, honouring filters and sorting, opens its collapsed suites and shows its output without moving focus.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 05:21:18 +08:00
l0ng-ai 197c7d6141 fix(workbench): centre the project colour gradient on the Project widget (#5975)
The frame's project colour gradient was pinned to the top-left corner, so it stayed there when the Project widget was moved to the Center or Right toolbar group. The title bar now measures the widget's icon whenever the bar or its entries change size and writes its centre to the frame as --project-gradient-x. Without the widget the gradient keeps the corner.
2026-11-26 05:08:33 +08:00
l0ng-ai c61bb2b56d fix(vcs): show the whole branch name in the status bar's Git Branch widget (#5970)
The status bar widget was capped at 240px and, when repositories are on different branches, the non-shrinking repository prefix took up to 120px of it, so branch names were cut to a few characters. The widget now grows to about 100 characters as IDEA's does, and a long repository prefix shrinks before the branch name.
2026-11-26 04:55:41 +08:00
l0ng-ai b9429858a6 feat(tools): try several download mirrors in order and follow the system proxy in curl (#5968)
Tools › Download sources accepts several GitHub mirror prefixes,
separated by commas or whitespace. Downloads try them in order, then
the official host; a mirror that just failed to deliver moves behind
the others for ten minutes. Plugin package downloads use the same list.

Tool downloads run curl, which reads only the environment's proxy. In
Auto mode the IDE's HTTP client already follows the macOS / Windows
system proxy; curl now gets the same proxy via --proxy when the
environment names none.

The npm "cannot look up the latest" error now says the registry comes
from the npm configuration.

Refs #5824
2026-11-26 04:51:57 +08:00
l0ng-ai c1e9707c7e perf(editor): let Go to Declaration go before Code Vision usage counts (#5967)
Code Vision usage counts run project-wide reference searches on the same language server as Go to Declaration, so a jump queued behind in-flight counts on large Java workspaces. Counts now give way like the implementation gutter markers: in-flight ones are cancelled when a navigation starts, no batch starts while it runs, and the pass runs again once it is done.
2026-11-26 04:47:48 +08:00
l0ng-ai a483ea77f4 feat(database): show table grants in the Modify Table dialog (#5965)
The Modify Table dialog gains a read-only Grants tab for PostgreSQL and
MySQL tables: one row per grantee and grantor, a column per privilege,
and a `*` mark for privileges held WITH GRANT OPTION.

- PostgreSQL expands the table ACL with aclexplode, falling back to the
  owner's implicit privileges when relacl is null; PUBLIC is listed.
- MySQL reads information_schema.table_privileges (no grantor there).
- Other engines show no tab and run no query; grants load only when the
  tab is opened.

Fixes #5832
2026-11-26 04:37:53 +08:00
l0ng-ai de36b46660 fix(python): keep uv run's own options in run, debug, coverage and profiling (#5963)
A Python run configuration such as 'uv run --with rich --no-sync main.py' lost uv's options: the interpreter rewrite dropped 'run' and passed them to Python, debugpy took '--with' for the module (and 'uv run main.py' for the module 'main.py'), and coverage / profiling found no python token. Runner options now keep the runner command, and debugpy / coverage / profiling skip them (including value-taking ones) and add debugpy after the python that 'uv run [options] script.py' or '-m / --module' implies.

Refs #5874
2026-11-26 04:19:21 +08:00
Mansur Akhmadiтаmansur-akhmadi 5918605b2b feat(editor): Copy as Plain Text / Copy as Rich Text (#5960)
Adds CopyAsPlainText and CopyAsRichText: copy the selection once in the other format than Settings > Editor > General > Rich-Text Copy, without changing the setting. The editor popup's Copy / Paste Special shows the one the setting doesn't already give, only with a selection; Copy as Rich Text needs a single selection. No default shortcut; both are listed in Keymap and Find Action.

Closes #5959

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 04:13:42 +08:00
l0ng-ai f69d394480 feat(terminal): Max FPS paces terminal, Run and Debug console output end to end (#5962)
terminal.maxFps now paces process output end to end. The terminal and Run pumps batch for half the frame interval (4-200 ms, never faster than the Unlimited 4 / 8 ms; Unlimited unchanged), applied by the host when a session starts and when a terminal setting changes. The Run console's terminal mode writes through OutputGate; the plain Run console's 50 ms floor and the Debug console's per-frame flush stretch when Max FPS asks for fewer frames. Adds a 5 FPS option; the hint names the terminal and the Run and Debug consoles. ide-dap has no output pump to pace.

Closes #5897
2026-11-26 04:12:48 +08:00
l0ng-ai eb078a0a19 fix(appearance): give reduced-motion transitions no duration so layout reads stay right (#5961)
Reduce motion set every element's transition-duration to 0.01ms. With the default transition-property: all, every property change on every element became a transition, CodeMirror's virtual height gaps included, so a layout read right after a change saw the old size and diff navigation scrolled to the end of the file instead of centring the change. Transitions now get 0s; animations keep 0.01ms so their end events still fire.
2026-11-26 04:06:58 +08:00
Vadim LazukтаInf1mum 5a884d7cba refactor(dotnet): remove the standalone .NET tool window (#5918)
Removes the standalone .NET tool window, its stripe button and dotnet.show. NuGet package search / install / update / remove move to a bottom "NuGet Packages" tool window (stripe onUse) opened by dotnet.packages. Build / Restore / Clean / Test act on the project of the current context: the Project view's selected .csproj / .fsproj / .vbproj / .sln, else the active editor's project, else the solution (the NuGet-selected project without one); an unloaded workspace model is scanned once, shared between concurrent actions and the NuGet window, and retried after a failure. Build / Restore / Clean join the Project view context menu for project and solution files.

Review fixes: the context target reads the workbench projectViewSelection() instead of importing the project-tree store; the NuGet window loads the model through the shared scan; the menu uses the same path helpers as the target resolution.

Refs #5635

Co-authored-by: Inf1mum <[email protected]>
2026-11-26 03:51:30 +08:00
l0ng-ai 2ba2f33232 fix(terminal): keep Latin text monospace when the chosen font is missing (#5958)
The terminal stack named the CJK fallback faces (since #5458) right after the Nerd Fonts. Their Latin glyphs are proportional, and past the bundled font the --font-mono stack only has macOS faces, so on Linux and Windows a chosen family that doesn't take left plain text drawn by Noto Sans CJK SC / Microsoft YaHei inside cells sized for its widest glyph. Common Linux/Windows monospace faces (DejaVu Sans Mono, Liberation Mono, Noto Sans Mono, Cascadia Mono, Consolas) now come before the CJK faces; none has CJK glyphs, so wide characters still reach the named CJK faces.

Fixes #5799
2026-11-26 03:46:52 +08:00
Mansur Akhmadiтаmansur-akhmadi c9bb5a3169 feat(editor): Split and Move Right / Down as actions (#5953)
The editor tab menu's Split and Move Right / Split and Move Down become actions (editor.splitAndMoveRight / editor.splitAndMoveDown, IDEA ids MoveTabRight / MoveTabDown), so Find Action lists them, they can take a shortcut and imported keymaps / IdeaVim :action can map to them. They move the active tab of the active group into a new split and are enabled only when the group has more than one tab; the tab menu items show their shortcut. No default shortcut in the presets.

Closes #5952

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 03:44:37 +08:00
l0ng-ai bfbc70a438 feat(plugins): editor decorations with their own colors (API 1.17) (#5957)
Plugin API 1.17: decorations.set-styled (SDK host::set_styled_decorations) lets editor decoration items carry their own #rrggbb / #rrggbbaa foreground and background, for colors the theme palette lacks (e.g. a TODO highlighter's user-chosen colors).

- Host validates and normalizes colors (anything else is Invalid); an item with colors may leave style empty; set ids, limits and clear are shared with set / set-markdown.
- Editor paints the range with inline color / background-color; the after label takes the foreground only; the frontend re-checks the hex format.
- SDK types, wrapper and mock (shared replace/limit helper for the three decoration kinds); decorations fixture gains a styled command.
- Package openidea:[email protected].0, engine 1.17.0, components rebuilt; docs list 1.16 as shipped with 0.1.52.
2026-11-26 03:40:40 +08:00
Mansur Akhmadiтаmansur-akhmadi e74edbcedc feat(editor): Cut up to Line End and Delete to Line Start / End actions (#5945)
Adds Cut up to Line End (Ctrl+K in the macOS IntelliJ keymap; repeated cuts at the same caret collect into one clipboard and Paste from History entry) and Delete to Line Start / Delete to Line End. They work on document lines rather than soft-wrapped rows, merge overlapping spans of several carets, and run only in a focused editor so popup text fields keep their own keys. Eclipse keymaps bind Delete to Line End to Shift+Cmd/Ctrl+Delete; Ctrl+K is listed as a Vim conflict.

Closes #5944

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 02:57:11 +08:00
Alexanderтаformiat ebeb6476eb fix(toolwindows): keep an undocked window opened from a menu on screen (#5946)
An undocked or unpinned tool window shown with focus from a menu or popup hid again at once: the window takes focus a frame later, and in between the closing menu returned focus to the editor, which hides unpinned windows. A window whose focus request has not reached it yet no longer auto-hides; the request counts as served once the window gets focus or is hidden. Git > Show History with an undocked Git window now opens and stays.

Closes #5941

Co-authored-by: formiat <[email protected]>
2026-11-26 02:38:41 +08:00
Alexanderтаformiat b8b245da5f feat(vcs): Show in Git Log in the File History commit menu, as in IDEA (#5948)
A commit in a File History tab gets Show in Git Log in its context menu, after Compare with Local. It reuses the vcs.showCommit action (switch to the Log tab and select the commit) that Blame and Compare Branches already use; the plain Log menu is unchanged.

Closes #5947

Co-authored-by: formiat <[email protected]>
2026-11-26 02:31:45 +08:00
l0ng-ai 5aeadcc888 fix(java): reload annotation processors after a project reload (#5950)
JDT APT keeps a class loader per project over the annotation processor path, holding its jars open; after a dependency on that path was installed again in place (a SNAPSHOT), the next build failed with Unable to load annotation processor factory until jdtls restarted. Every project reload already runs openidea.java.refreshArchives; it now also resets JDT APT's processor class loaders (AnnotationProcessorFactoryLoader.resetAll), so the next build loads the processors from the current jars.

Fixes #4105
2026-11-26 02:29:12 +08:00
l0ng-ai edc750174b feat(run): run JUnit 4 tests from the gutter without Maven (#5949)
Running a JUnit 4 test from the gutter of a Maven module started mvn test, so the Run console showed the whole Maven and Surefire log. OpenIDEA's JUnit runner now runs JUnit 4 and JUnit 3 tests on JUnit 4's own JUnitCore when the classpath has no JUnit Platform (or one without the Vintage engine); JUnit 5 keeps the Platform launcher. The Run console of JVM test runs also shows each test's stdout/stderr and failure trace, which the runner and the Gradle init script report only through service messages.

Fixes #5765
2026-11-26 02:14:28 +08:00
l0ng-ai cdff357fdd fix(build): build the selected run configuration from the toolbar hammer (#5901)
The main toolbar's hammer now builds the selected Run Configuration's target and reads Build '<name>'; with no configuration selected it stays Build Project, and Build > Build Project (Cmd+F9) still builds the whole project. The target is resolved for application, Spring Boot, JUnit, Tomcat, Maven (-pl), Gradle (:subproject:task), .NET, Cargo, Go and CMake configurations.

Also fixes module and project build edge cases: relative file paths resolve against the project root, linked Maven directories are included when scoping a build plan, Go directory targets no longer step to the parent, a root with no build file of its own builds its Gradle and Maven sibling projects, and building an aggregator POM builds its subprojects. The Build tool window's rerun keeps the CMake target.
2026-11-26 01:52:01 +08:00
Mansur Akhmadiтаmansur-akhmadi de971848ab feat(database): interactive ER diagram, unique keys and indexes, Show Diagram Popup (#5937)
The database ER diagram becomes interactive: automatic layout, draggable and collapsible tables, unique keys and indexes with badges, dashed nullable foreign keys, and a Show Diagram Popup action.

Refs #5778

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 01:43:41 +08:00
Mansur Akhmadiтаmansur-akhmadi 90cb56e9f8 feat(editor): Expand / Collapse Doc Comments actions (#5935)
Adds Expand Doc Comments and Collapse Doc Comments to Code > Folding, folding or unfolding every documentation comment in the file.

Closes #5934

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-26 01:43:19 +08:00
l0ng-ai baa0171d8a feat(appearance): add a Reduce motion setting (#5940)
Adds Reduce motion under Appearance > Accessibility. When on, or when the system asks for reduced motion, CSS animations and transitions finish at once; script-driven motion reads the same preference.

Fixes #5887
2026-11-26 01:42:42 +08:00
l0ng-ai 0d493fb515 fix(search): match Class::method in Search Everywhere's language-server symbols (#5938)
Search Everywhere sent queries such as Class::method or Class.method to workspace/symbol as typed, so language servers returned nothing. The query is split into container and name like the index search does; the name goes to the server and the results are filtered by container.

Fixes #5888
2026-11-26 01:42:33 +08:00
Vladislav Kuzmin a56add66ea feat(database): protect read-only PostgreSQL queries behind transaction poolers (#5810)
PgBouncer in transaction mode rejects the default_transaction_read_only startup option (08P01), so read-only PostgreSQL data sources behind it could not connect. The native driver now falls back to BEGIN READ ONLY with such poolers and Test Connection says so. Auto-commit, manual transactions and forward paging keep a query on its assigned backend; console and startup scripts that would replace the protected transaction are rejected before they run. Direct connections keep the startup-option path.

Closes #5691

Co-authored-by: principalwater <[email protected]>
2026-11-26 01:42:15 +08:00
l0ng-ai 2d568980c5 fix(editor): fill identifier and match highlights to the full line height (#5936)
Inline marks (occurrence highlights, search matches, framed marks) were painted only over the text height, leaving gaps at larger line heights. They now pad to the full line height; token backgrounds keep the capped height.

Fixes #5879
2026-11-26 01:42:06 +08:00
Vadim LazukтаInf1mum 7920a4985e fix(keymap): match unshifted punctuation by the typed character on AZERTY (#5932)
Shortcuts on unshifted punctuation keys were matched by physical key code, so on AZERTY a binding like Shift+Meta+M or Meta+1 never matched what the user typed. ASCII punctuation typed without Alt or Shift is now matched by the typed character; letters, digits and non-Latin layouts keep the existing logic.

Closes #5924

Co-authored-by: Inf1mum <[email protected]>
2026-11-26 01:41:56 +08:00
QтаNeverKnowsTomorrow d6c7e7edc4 fix(editor): keep the smooth caret under the mouse while selecting text (#5930)
With smooth caret movement on, every mousemove during a drag selection restarted the caret's CSS transition, so the caret trailed the pointer (and on WKWebView the transition kept running after the button was released). Pointer-driven selection now moves the caret without the transition.

Closes #5928

Co-authored-by: NeverKnowsTomorrow <[email protected]>
2026-11-26 01:41:42 +08:00
Vadim LazukтаInf1mum b1c69d1991 fix(notebook): keep the caret in the focused cell across undo and redo (#5926)
Undo and redo in a notebook cell were re-accepted as a full snapshot, re-rendering the cells with the caret at the start of the notebook. The caret now stays in the focused cell and lands on the undone change.

Part of #5846

Co-authored-by: Inf1mum <[email protected]>
2026-11-26 01:41:32 +08:00
l0ng-ai a869acdca2 fix(debugger): attach a debugpy subprocess through the running adapter (#5931)
A debugpy subprocess (multiprocessing / fork) was attached through a new adapter process that knew nothing of the parent session, so breakpoints in the child never hit. The child is now attached through the running adapter with the startDebugging request it sends.

Fixes #5877
2026-11-26 01:40:44 +08:00
Deng Liuтаdengliu fb3a037b7e fix(agents): stage all active skills for Copilot headless sessions (#5923)
Copilot headless sessions staged only the skills named in the prompt; skills set to Auto were left out, so the CLI could not load them. All active skills are staged now.

Closes #5920

Co-authored-by: dengliu <[email protected]>
2026-11-26 01:40:21 +08:00
l0ng-ai dfaa784513 fix(build): finish a build step when its process exits, even if a daemon holds the pipes (#5943)
Build steps read the child's output until every end of its pipes closed. On Windows a Gradle daemon started by the build inherits those pipes and outlives the build, so the step waited for the daemon. A step now stops reading once the process has exited and its output has been quiet for a second, as Run configurations and SDK queries already do.
2026-11-26 01:40:11 +08:00
l0ng-ai 67e58f61b6 (#5927)
Sticky lines and line previews render through a separate view that did not receive the LSP semantic token decorations, so they showed only syntax colours. They now carry the semantic highlighting of the editor they mirror.

Fixes #5858
2026-11-26 01:38:54 +08:00
Akbar Husain e75deb11c0 (#5907)
Clears the remaining non-e2e no-await-in-loop diagnostics: independent supertype/outline reads, message-bundle reads and project-icon deletes run in parallel; intentionally sequential loops get a narrow, documented suppression. No behaviour change.

Co-authored-by: akbar1214 <[email protected]>
2026-11-26 01:38:46 +08:00
Deng Liuтаdengliu 94b67515a5 (#5919)
Hiding a maximized tool window cleared the side's maximized anchor without remembering it, so reopening it from its stripe icon brought it back unmaximized. The maximized preference is now tracked per window and restored on reopen.

Co-authored-by: dengliu <[email protected]>
2026-11-26 01:38:38 +08:00
Alexis a0b2678466 (#5892)
On macOS, Ctrl+N / Ctrl+P move the selection down and up in Search Everywhere results, as Emacs-style navigation does in other lists.

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-26 01:38:30 +08:00
Alexis e3dc7e950b (#5889)
Adds a Copy Branch Name action that copies the current branch of the active repository and shows the usual Copied hint. It is available from Search Everywhere, a shortcut, and VCS Operations after Branches.

Closes #5853

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-26 01:38:22 +08:00
Vladislav Kuzmin 0a53c7b864 test(build): keep Gradle daemons within the fixture lifetime (#5915)
On Windows a persistent Gradle daemon started by the Java build fixtures kept the launcher's captured output pipe open after a successful build, so the fixture waited for EOF until the CI job timed out. The fixture projects now set org.gradle.daemon=false; both tests still run real Gradle.

Closes #5913

Co-authored-by: principalwater <[email protected]>
2026-11-26 01:37:44 +08:00
Vladislav Kuzmin d4447c7aba test(mcp): wait for the background run to exit through stdin (#5842)
The background-project test stopped `sleep 30` gracefully, but where SIGINT is ignored (CI) the child never exited, the MCP call timed out and the run still held the project. The fixture now runs `cat`, closes its stdin once the request hold is observed, and requires exit code 0 before checking the project was released.

Closes #5841

Co-authored-by: principalwater <[email protected]>
2026-11-26 01:35:56 +08:00
l0ng-ai 9740edbfd4 fix(coverage): line the column headers up with their cells again (#5939)
The Coverage header kept a 10px scrollbar gutter for the tree's native scrollbar, which #5850 replaced with a DOM scrollbar drawn over the rows, so every header sat 10px left of its cells.

Also updates two agent e2e specs that failed on main: a reasoning step and its command now fold into one run (#5906), and the tool-window focus spec clicks reply text instead of a point that can land on a message's footer button.
2026-11-26 01:33:30 +08:00
l0ng-ai b49b0e5c98 fix(remote): serve the HTTP Client commands from the remote server (#5925)
The HTTP Client commands were desktop-only, so a remote (SSH) window ran
them on the local host, which has no project for that window, and sending
a request failed with "no project is open in this window". Execution,
history, environments, cURL conversion and variable lookup now live in
ide_host::ops::http and are routed to the project host; parsing, cURL
import and the proxy check stay in the desktop shell.

Fixes #5859
2026-11-25 23:18:03 +08:00
Vadim LazukтаInf1mum c88e379c8b fix(editor): auto-complete after ( in Java so annotation attributes are offered (#5912)
Automatic completion fired only after word characters and . : -> @, so
typing ( after a Java annotation name never asked the language server and
its attributes were not offered. ( is now a trigger in Java documents when
it directly follows an annotation name; method calls, if ( and other
languages still do not open the popup.

Fixes #5855

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 23:09:01 +08:00
akshathayadav378-boopтаakshathayadav378-boop db63c6c93b fix(host): isolate login environment shell session (#5908)
read_login_env() ran `$SHELL -ilc` in the app's inherited terminal session.
Started from a terminal (the `openidea` command, or `openidea … &`), the
interactive shell took job control of that terminal, and the background
process group (the app and its shell) stopped with SIGTTIN/SIGTTOU, so
the CLI timed out after 30 s. The env-reading shell now calls setsid()
before exec: it has no controlling terminal, runs without job control,
and still reads the rc files.

Fixes #5871

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-25 23:08:05 +08:00
Vadim LazukтаInf1mum 54a7962043 fix(settings): keep an uncommitted Run Targets field edit off the next target (#5900)
The run target list switches selection on mousedown, before the Published
ports / Compose files field's blur commits its draft, so the commit closure
already saw the newly selected target and wrote the edit onto it. The
Target Settings form is now keyed by target id, so switching targets
remounts it and drops the uncommitted draft.

Fixes #5872

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 23:03:43 +08:00
l0ng-ai 7c3b9824e6 chore: v0.1.52 2026-11-25 22:37:51 +08:00
Deng Liuтаdengliu 0450de5321 fix(macos): preserve horizontal trackpad scrolling inside iframes (#5916)
Two-finger horizontal trackpad swipes over embedded iframes (plugin web views, web previews, Flutter DevTools, notebook outputs) now scroll the iframe content instead of starting a Back/Forward page swipe. The workbench cannot see inside these frames, so an iframe is treated as owning horizontal scroll.

Co-authored-by: dengliu <[email protected]>
2026-11-25 22:37:36 +08:00
l0ng-ai fadd2a78aa fix(agents): keep composer top padding outside scroll container 2026-11-25 22:35:53 +08:00
l0ng-aiтаCursor 53f5ecb233 fix(browser): align child webview under IDE zoom and polish inspector UX (#5917)
Co-authored-by: Cursor <[email protected]>
2026-11-25 22:27:42 +08:00
l0ng-ai 0b079af75d fix(i18n): drop the text of the removed turn-folding setting (#5914)
#5906 removed foldTurns and its settings row, but its four strings stayed in every locale catalog, so the catalog test that rejects entries missing from the source failed on main.
2026-11-25 21:56:03 +08:00
Deng Liuтаdengliu 6dab294dbf fix(editor): keep syntax and semantic backgrounds on their own row (#5787)
Syntax and semantic token backgrounds no longer cover characters on neighboring lines when the font box is taller than the line height. Token fills now go through the same 1lh-capped inline background as Find and occurrence highlights, with the colour in --openidea-token-bg so semantic roles can override nested syntax fills; an unset fill paints nothing. The background size is a separate declaration, so WebKit without lh support still shows the fill.

Co-authored-by: dengliu <[email protected]>
2026-11-25 21:55:45 +08:00
l0ng-ai fc0ca1e029 test(remote): retry the old backend connect until its socket listens (#5910)
The daemon's socket file appears at bind(), before listen(), so a connect in between is refused; upgraded_build_refuses_live_work_and_then_replaces_idle_backend failed that way on macOS CI. The helper now retries on ConnectionRefused.
2026-11-25 21:42:45 +08:00
l0ng-ai fe024713da fix(java): take the last diagnostic line with next_back (#5909)
lines.last() on the double-ended filter iterator tripped clippy::double_ended_iterator_last, failing the Rust checks on main; next_back() returns the same line.
2026-11-25 21:39:51 +08:00
l0ng-aiтаCursor 42c7834023 feat(agents): fold all consecutive tool calls into runs and remove foldTurns (#5906)
Co-authored-by: Cursor <[email protected]>
2026-11-25 21:28:10 +08:00
l0ng-ai 96f73c82da fix(vcs): keep every repository listed after double-clicking a branch (#5905)
Double-clicking a branch in the Git Log Branches pane now changes only the branch filter. It no longer also sets the repository filter, which narrowed the Branches pane to that one repository and left a second filter to clear by hand. Repositories without the branch contribute no commits, so the log shows the same history, and clearing the branch filter restores the whole log. A repository filter chosen from the Paths filter is kept.

Fixes #5893
2026-11-25 21:22:16 +08:00
854c81e49b feat(browser): browse and inspect localhost in a persistent native panel (#5788)
Open Local Browser opens a Browser tool window hosting a Tauri child webview
for a loopback HTTP(S) origin in a trusted local project: back, forward,
reload, same-origin navigation, and Inspect Element, whose reviewed selection
is appended to the Agent draft without being sent. The guest webview has an
empty capability set; workbench capabilities are scoped by webview label, and
application IPC and the plugin protocol reject guests by label. Workbench
windows are tracked as their original WebviewWindow handles, because Tauri's
single-webview lookup stops matching once a child is attached; window
commands (including the parallel close flow) use those handles.

Console URL clicks keep opening the external browser; loopback URLs get
"Open in Browser Tool Window" in the Run and Debug console context menus.
The panel uses a one-row icon toolbar, fills the panel with the page, has its
own tool window icon and focuses the address field for a new session.

Co-authored-by: dengliu <[email protected]>
Co-authored-by: aditya-786 <[email protected]>
2026-11-25 21:20:37 +08:00
l0ng-ai b19922b71d fix(agents): keep the context ring on the window Claude Code reports (#5902)
A result's modelUsage can give a model a larger contextWindow (1M) than the window Claude Code counts and compacts against (get_context_usage maxTokens, 400k), so the ring and the Context window details disagreed. The window get_context_usage reports, when the details or a compaction read it, now wins for that model.
2026-11-25 21:17:35 +08:00
l0ng-ai afab9d0ba2 fix(java): name a failed Gradle sync's cause when Run or Debug stops on it (#5904)
Buildship marks a Gradle project whose sync failed with the tooling API's message first and the build's own error last; launch errors kept only the first line. For these Gradle messages the last line now follows as the cause, in launch compile errors and in the build-file problems that keep a module out of jdtls.
2026-11-25 21:17:15 +08:00
l0ng-ai 04ed8712b5 fix(markdown): reflow the blocks in view while a pane is resized (#5903)
During a pane resize only the blocks the viewport observer marked reflowed; when the marks were missing (content replaced without a new render, a restored preview) every block kept its old width and visible text was clipped until the drag ended. A resize now marks the blocks in and near the viewport by position, and replaced content is observed again.
2026-11-25 21:17:06 +08:00
l0ng-ai 971b520399 feat(agents): fold shell commands that only read or search into exploration runs (#5898)
A shell command whose every segment only reads or searches (grep, rg, git grep, find, cat, sed -n, ls, git status/diff/log/show…) now joins the exploration run with reasoning and counts in its summary as a read or a search. Commands that may change something (builds, tests, writes, redirects, command substitution, unknown programs) still show on their own row. The leading cd parsing moves into the same module and is shared with command titles.
2026-11-25 20:39:48 +08:00
l0ng-ai c67363ec6b test(sdk): use an absolute temp path for the explicit Dart tool path (#5899)
'/opt/dart/bin/dart' is not absolute on Windows, so it resolved against the project root's drive and the Flutter SDK test failed on windows-latest. The test now uses an absolute path under the temp dir.
2026-11-25 20:37:09 +08:00
l0ng-ai 2568772700 perf(window): close project tabs in parallel and move teardown off the UI thread (#5882)
Quit, closing a tab group and Close Other/Left/Right Tabs now close their windows in parallel and hide them together in one frame; a window that needs to ask (unsaved changes, running processes, remote backend) takes the prompt turn and comes forward, so prompts still appear one at a time. Agent, terminal and process teardown moves off the UI thread into the project's background shutdown, idle agent tasks are no longer rewritten on close, and opening a project only waits for closes of overlapping roots.
2026-11-25 20:19:17 +08:00
l0ng-ai 536f85b9df feat(java): build Maven and Gradle modules with a resident, incremental javac build service (#5854)
Implements #4078 steps 2–4: an IDE-owned Java build service that compiles Maven and Gradle modules with a resident javac, class by class, for launches and the Build menu.

## What changes

- **Model.** The build tool records each project's source roots, compile/runtime classpaths, resources and the compiler configuration it actually uses (release/source/target, encoding, `-parameters`, debug level, `proc`, compiler args, includes/excludes, resolved annotation processor path):
  - Maven: a core extension (`java/java-build`, `BuildModel`) during `process-resources resources:testResources`.
  - Gradle: an init script (`gradle-build.init.gradle`) with an `openideaBuildModel` task that runs source generators and `processResources`.

  The prepare run happens only when what the model is built from changes: build scripts, settings, toolchains, the launcher, the JDK, generator inputs (`src/*/proto`, `antlr4`…), or a generated root that is gone.
- **Outputs.** Every project writes to `<cache>/java-build/<build>/out/<group>.<name>/classes|test-classes`, and dependencies on other projects of the build resolve to those folders. jdtls and a terminal `mvn`/`gradle` never write the classes a launch runs.
- **Compile.** A resident javac process per JDK (and `.mvn/jvm.config`) compiles source sets in dependency order, without `-am` or the full lifecycle.
- **Class-level incremental compilation.** Each source set records, per class: its source, supertypes, the classes its constant pool references, and fingerprints of its API and compile-time constants (read from the class files, private and synthetic members excluded).
  - A build compiles the changed sources.
  - It then compiles, round after round, the sources of classes that reference a class whose API changed (or one of its subclasses), and the sources a new class could shadow.
  - Downstream sets follow an API change log.
  - A changed constant recompiles the set and everything compiled against it.
  - Sources a failed compile left behind stay dirty.
  - Sets whose annotation processors aggregate compile from scratch.
- **Build menu.**
  - Build Project and Build Module compile with the service.
  - Recompile compiles the file with the service and publishes javac's diagnostics.
- **Events.** Steps, positioned javac diagnostics and progress stream on the `BuildEvent` channel from #5801.
- **When it applies.**
  - Maven modules, unless Settings › Maven › *Delegate IDE build/run actions to Maven* is on.
  - Gradle modules when Settings › Gradle › *Build and run using* is the IDE.
  - Debug launches keep jdtls' build, because java-debug's HotSwap reloads what jdtls compiles.
  - jdtls keeps autobuild on: cross-module diagnostics depend on it (verified with a real jdtls, see the ignored test below).
- **Fallback.** These go to the build tool's own build:
  - modules that need it: another compiler (Kotlin, Groovy, AspectJ…), a non-javac compiler id, multi-release output, Java modules, unresolvable dependencies or processor paths, composite Gradle builds;
  - a failed prepare run.

The javac server and the Maven extension are built reproducibly with `--release 8` against Maven 3.9.11 (`java/java-build/build.py`, dependencies pinned) and embedded by `ide-sdk`.

## Tests

- `ide-build` `jbuild::tests`, run against a real Maven/Gradle and JDK (skipped when missing):
  - first build, no-op build, only changed files recompile;
  - API changes reach dependents, including through subclasses and across modules;
  - constant changes recompile dependents;
  - resource changes run only the resources step;
  - deleted sources, compile errors with positions, the test source set;
  - Recompile and Build Project;
  - Gradle projects;
  - fallback for Gradle projects with other compilers;
  - plus class-file parsing, the API change log, javac options and Ant patterns.
- `ide-host` `tests/java_build.rs`: Maven and Gradle launches through `java_resolve_launch` compile with javac into the IDE's outputs, and Build Project reports javac's errors.
- `tests/workspaces.rs`: a Maven that writes no build model falls back to `mvn -pl app -am`.
- `ide-lsp` (ignored, needs jdtls): jdtls reports cross-module errors in open and closed files with autobuild on.
2026-11-25 20:01:26 +08:00
l0ng-ai e5c5915f2e feat(agents): logos for every agent in the ACP registry (#5884)
Every agent in the ACP registry now shows its own logo instead of the generic agents icon. A provider's logo is looked up by id, with legacy and ACP-adapter ids (claude-acp, codex-acp, kimi-code, opencode-v2) sharing their agent's logo and Hermes profiles using Hermes'. The registry logos are listed in THIRD_PARTY_LICENSES.md.
2026-11-25 19:55:06 +08:00
l0ng-ai ca2bf89f86 feat(agents): drop the leading cd from command titles (#5890)
Command titles drop a leading `cd <dir> &&`; a folder other than the task's shows as a small tag before the command, with the full path on hover. The running-command hint in a grouped run's summary uses the same title.
2026-11-25 19:45:51 +08:00
l0ng-ai 735fe5dd30 feat(agents): show task status marks in a column beside the age (#5885)
The status mark (spinner, usage-limit clock, needs-input warning, ...) moves from right after the title to a fixed slot just before the age, so marks line up across rows regardless of title length. The age gets a minimum width so the column stays put between "now", "3m" and "12d".
2026-11-25 19:37:53 +08:00
l0ng-ai 0cfd17979b fix(agents): use spacing tokens for the session asset pill gaps (#5886)
The three gaps added to Session.module.css were raw 6px values, which the spacing-scale test rejects on main; they now use --space-1-5.
2026-11-25 19:30:01 +08:00
Deng Liuтаdengliu 41165bb8c0 fix(ssh): migrate legacy saved credentials at startup (#5786)
Host startup now moves legacy plaintext SSH passwords and key passphrases from
ssh-passwords.json into the OS credential store, without waiting for the next
SSH connection. When the move cannot finish, each workbench shows a sticky
warning with Retry migration and a confirmed Remove plaintext copy, which keeps
credentials already moved. A credential that cannot be saved stays for the
session and the requesting window is warned. An unreadable ssh-passwords.json
is set aside (renamed, never deleted) like the other secret files, so it no
longer blocks saving new credentials.

Co-authored-by: dengliu <[email protected]>
2026-11-25 19:27:09 +08:00
l0ng-ai 91264713e7 fix(linux): use X11 under WSLg (#5748)
Started from a WSL shell, GTK opens WSLg's Wayland display, where Mesa has no usable GPU driver for WebKitGTK and the window stays blank. Under WSL (WSL_DISTRO_NAME or WSL_INTEROP set) with an X display available, OpenIDEA now sets GDK_BACKEND=x11 before GTK starts; an explicit GDK_BACKEND is kept, and nothing changes outside WSL.

Fixes #5178
2026-11-25 18:54:43 +08:00
729 змінених файлів з 20792 додано та 2968 видалено

No files matched your search

+2 -21
Переглянути файл
@@ -149,27 +149,8 @@
}
},
{
"files": [
"evals/**/*.ts",
"perf/**/*.ts",
"smoke/**/*.ts",
"src/features/vcs/**/*.ts",
"src/features/vcs/**/*.tsx",
"src/features/run/**/*.ts",
"src/features/run/**/*.tsx",
"src/features/database/**/*.ts",
"src/features/database/**/*.tsx",
"src/features/analysis/**/*.ts",
"src/features/analysis/**/*.tsx",
"src/features/project-tree/**/*.ts",
"src/features/project-tree/**/*.tsx",
"src/features/http-client/**/*.ts",
"src/features/http-client/**/*.tsx",
"src/platform/**/*.ts",
"src/platform/**/*.tsx",
"src/features/debugger/**/*.ts",
"src/features/debugger/**/*.tsx"
],
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"excludeFiles": ["e2e/**"],
"rules": {
"no-await-in-loop": "error"
}
Створено
+50 -48
Переглянути файл
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4172,7 +4172,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4184,7 +4184,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"serde",
@@ -4195,7 +4195,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"blake3",
"chardetng",
@@ -4213,7 +4213,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4227,7 +4227,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4238,7 +4238,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4249,7 +4249,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4271,7 +4271,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-run",
@@ -4284,7 +4284,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4313,7 +4313,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4352,7 +4352,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"serde",
@@ -4365,7 +4365,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4379,7 +4379,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4399,7 +4399,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-android",
"ide-core",
@@ -4410,7 +4410,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4422,7 +4422,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4435,7 +4435,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"criterion",
"ide-core",
@@ -4454,7 +4454,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4530,7 +4530,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"hyper-util",
"ide-core",
@@ -4549,7 +4549,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"blake3",
"criterion",
@@ -4572,7 +4572,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4584,7 +4584,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4600,7 +4600,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"libc",
"tempfile",
@@ -4609,7 +4609,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"futures",
"serde",
@@ -4620,7 +4620,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"blake3",
"criterion",
@@ -4679,7 +4679,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"criterion",
"dunce",
@@ -4708,7 +4708,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"bytes",
"dunce",
@@ -4727,7 +4727,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4748,7 +4748,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"blake3",
"dunce",
@@ -4770,7 +4770,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4784,7 +4784,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"dunce",
"futures",
@@ -4804,7 +4804,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"dunce",
"encoding_rs",
@@ -4828,7 +4828,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-tools",
@@ -4844,7 +4844,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4870,7 +4870,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"criterion",
"encoding_rs",
@@ -4891,7 +4891,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"parking_lot",
@@ -4904,7 +4904,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4929,7 +4929,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-language",
@@ -4942,7 +4942,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-language",
@@ -4957,7 +4957,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"ide-core",
"libc",
@@ -4971,7 +4971,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"criterion",
"ide-core",
@@ -4984,10 +4984,12 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"flate2",
"hex",
"http",
"hyper-util",
"ide-core",
"ide-language",
"libc",
@@ -5005,7 +5007,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"blake3",
"dunce",
@@ -5027,7 +5029,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"chardetng",
"dunce",
@@ -5054,7 +5056,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5070,7 +5072,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"blake3",
"dunce",
@@ -6699,7 +6701,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.51"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.51"
version = "0.1.53"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+11
Переглянути файл
@@ -6,6 +6,17 @@
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## Agent logos
The `src/ui/openidea/agents/` logos of agents listed in the
[ACP agent registry](https://github.com/agentclientprotocol/registry) (`agoragentic-acp`, `amp-acp`,
`antigravity-acp`, `autohand`, `bob`, `cline`, `codebuddy-code`, `cortex-code`, `corust-agent`,
`crow-cli`, `deepagents`, `devin`, `dimcode`, `dirac`, `factory-droid`, `fast-agent`, `glm-acp-agent`,
`grok-build`, `harn`, `junie`, `kilo`, `kimchi`, `minimax-code`, `minion-code`, `muse-code`, `nova`,
`pi-acp`, `poolside`, `sigit`, `stakpak`, `vtcode`) are the registry's icons, with a root `fill`
moved onto a group. The registry is licensed under Apache-2.0; the logos remain trademarks of
their owners.
## Microsoft ConPTY
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
+16 -5
Переглянути файл
@@ -2291,14 +2291,25 @@ impl AgentManager {
}
}
/// Stops sending events to UI sinks (project closing).
pub fn detach_sinks(&self) {
self.shared.sinks.write().clear();
}
/// Stops every agent (project closed).
pub fn shutdown(&self) {
for task in self.tasks.read().values() {
task.kill();
// What arrived after the last save (a subagent's late updates).
task.persist();
self.detach_sinks();
let tasks: Vec<_> = self.tasks.read().values().cloned().collect();
for task in tasks {
let was_live = task.kill().is_some();
if was_live {
// Persist late subagent updates and cleared live background state.
task.persist();
} else {
// Flush pending delayed saves without rewriting untouched or archived tasks.
task.save();
}
}
self.shared.sinks.write().clear();
}
}
+10 -1
Переглянути файл
@@ -505,7 +505,16 @@ impl Shim {
"_openidea/context_usage" => {
let session = self.session(&params)?;
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)
let usage = rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)?;
// The meter shows the same numbers as these details from now on.
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
if let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) {
let update = session.st.lock().tr.on_context_usage(used, size);
if let Some(shim) = session.shim() {
shim.notify(vec![update]);
}
}
Ok(usage)
}
"_openidea/stop_task" => {
let session = self.session(&params)?;
+18
Переглянути файл
@@ -1148,6 +1148,24 @@ fn a_compaction_replaces_the_context_usage() {
assert!(t.on_result(&result).is_empty());
}
#[test]
fn claude_codes_own_window_wins_over_the_results_context_window() {
let mut t = Translator::new("s", PathBuf::from("/w"), true);
let assistant = |model: &str| {
json!({"type": "assistant", "parent_tool_use_id": null,
"message": {"id": "m1", "model": model, "content": [], "usage": {"input_tokens": 900, "output_tokens": 100}}})
};
t.on_message(&assistant("x"));
let result = json!({"modelUsage": {"x": {"contextWindow": 1_000_000}, "y": {"contextWindow": 200_000}}});
assert_eq!(t.on_result(&result)[0].update["size"], 1_000_000);
// `get_context_usage` reports the window Claude Code compacts against.
assert_eq!(t.on_context_usage(1000, 400_000).update["size"], 400_000);
assert_eq!(t.on_result(&result)[0].update["size"], 400_000);
// Another model: its own window again until Claude Code reports one for it.
t.on_message(&assistant("y"));
assert_eq!(t.on_result(&result)[0].update["size"], 200_000);
}
#[test]
fn rate_limits_and_cost() {
let mut t = Translator::new("s", PathBuf::from("/w"), false);
+14 -7
Переглянути файл
@@ -58,6 +58,10 @@ pub(super) struct Translator {
pub used: Option<u64>,
pub model: Option<String>,
windows: HashMap<String, u64>,
/// The window Claude Code itself counts against (`get_context_usage` `maxTokens`) and the
/// model it was read for. It can be smaller than the model's `contextWindow` in a `result`
/// (its compaction threshold follows this one), so it wins while the model is the same.
context_max: Option<(Option<String>, u64)>,
/// The session's cost so far in USD, as the last `result` reported it.
cost_usd: Option<f64>,
}
@@ -77,6 +81,7 @@ impl Translator {
used: None,
model: None,
windows: HashMap::new(),
context_max: None,
cost_usd: None,
}
}
@@ -571,6 +576,7 @@ impl Translator {
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
self.used = Some(used);
self.context_max = Some((self.model.clone(), size));
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if let Some(amount) = self.cost_usd {
update["cost"] = json!({ "amount": amount, "currency": "USD" });
@@ -580,13 +586,14 @@ impl Translator {
fn usage_update(&self) -> Option<Update> {
let used = self.used?;
let size = self
.model
.as_ref()
.and_then(|m| {
self.windows
.get(m)
.or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v))
let own = self.context_max.as_ref().filter(|(model, _)| *model == self.model).map(|(_, size)| size);
let size = own
.or_else(|| {
self.model.as_ref().and_then(|m| {
self.windows
.get(m)
.or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v))
})
})
.or_else(|| (self.windows.len() == 1).then(|| self.windows.values().next()).flatten())?;
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
+44
Переглянути файл
@@ -751,3 +751,47 @@ async fn stop_ends_a_turn_left_running_only_by_background_shells() {
assert_eq!(res["stopReason"], "cancelled");
assert!(!server.calls.lock().iter().any(|(m, _)| m == "session.abort"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skills() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let meta = json!({
"openidea": {
"skills": {
"copilotSkillDirectories": ["/farm/task-1/copilot"],
"copilotDisabledSkills": ["muted", "off"],
}
}
});
let _: Value =
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
let _: Value = client
.request(
"session/load",
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
None,
)
.await
.unwrap();
let calls = server.calls.lock();
for method in ["session.create", "session.resume"] {
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
assert_eq!(params["skillDirectories"], json!(["/farm/task-1/copilot"]), "{method}: {params}");
assert_eq!(params["disabledSkills"], json!(["muted", "off"]), "{method}: {params}");
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
}
}
+30 -38
Переглянути файл
@@ -649,11 +649,14 @@ pub struct Delivery {
/// Stages the skills a session of `provider` runs with into `farm` — linking (copying on
/// Windows, where directory symlinks need Developer Mode) every active skill folder into
/// the CLI's tree — and reports what to hand the CLI. Skills the CLI discovers natively
/// (its own folders of the working directory and the home) are not staged again: it already
/// sees them, and seeing both would list one skill twice. Skills `off` are never staged;
/// the CLI's native disable (where it has one) receives their names or paths. An ACP
/// agent gets nothing here: its `/` menu is filtered instead.
/// the CLI's tree — and reports what to hand the CLI. For Claude Code and Codex, skills
/// the CLI discovers natively (its own folders of the working directory and the home) are
/// not staged again so the CLI does not see duplicates. For Copilot (`copilot --headless`),
/// config discovery is off by default (enabling it would also auto-load workspace `.mcp.json`
/// outside OpenIDEA's MCP approvals), so every active `Auto` skill is staged into
/// `skillDirectories`. Skills `off` are never staged; the CLI's native disable (where it has
/// one) receives their names or paths. An ACP agent gets nothing here: its `/` menu is
/// filtered instead.
pub fn stage(
farm: &Path,
provider: &str,
@@ -705,7 +708,7 @@ pub fn stage(
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
if let Some(tree) = copilot_tree.as_ref().filter(|_| !native_copilot(&state.skill, &cwd, home)) {
if let Some(tree) = copilot_tree.as_ref() {
link_skill(&tree.join(name), path)?;
}
if let Some(tree) = codex_tree.as_ref().filter(|_| !native_codex(&state.skill, &cwd, home)) {
@@ -794,29 +797,6 @@ fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
}
}
/// Copilot natively scans `.github/skills`, `.agents/skills` and `.claude/skills` in `cwd`,
/// plus `~/.copilot` and `~/.agents/skills` in `home`. `.openidea/skills` is NOT native.
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
let target = skill.path.0.as_path();
for rel in [".github/skills", ".agents/skills", ".claude/skills"] {
let root = cwd.join(rel);
if is_under(target, &root) || direct_link_matches(&root, &skill.name, target) {
return true;
}
}
if let Some(h) = home {
let h = dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf());
if is_under(target, &h.join(".copilot"))
|| is_under(target, &h.join(".agents/skills"))
|| direct_link_matches(&h.join(".copilot/skills"), &skill.name, target)
|| direct_link_matches(&h.join(".agents/skills"), &skill.name, target)
{
return true;
}
}
false
}
/// Codex natively scans `.codex/skills` and `.agents/skills` in `cwd` and `home`.
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
let target = skill.path.0.as_path();
@@ -1232,8 +1212,9 @@ mod tests {
true,
);
//For a local session, `.github/skills`, `.agents/skills` and `~/.agents/skills` are
// already scanned natively by Copilot; `.openidea/skills` and `~/.codex/skills` are staged.
// Copilot headless does not run disk config discovery unless explicitly opted in, so
// every active `Auto` skill — including `.github/skills`, `.agents/skills`, `~/.agents/skills`,
// `~/.copilot/installed-plugins`, `.openidea/skills`, and `~/.codex/skills` — must be staged.
let mut states = states;
std::fs::create_dir_all(repo.join(".openidea/skills/ideonly")).unwrap();
states.push(AgentSkillState {
@@ -1241,6 +1222,13 @@ mod tests {
mode: AgentSkillMode::Auto,
origin: AgentSkillOrigin::None,
});
let copilot_plugin_skills = home.join(".copilot/installed-plugins/_direct/azure/skills");
std::fs::create_dir_all(copilot_plugin_skills.join("azure-ai")).unwrap();
states.push(AgentSkillState {
skill: skill("azure-ai", AgentSkillSource::CopilotUser, &copilot_plugin_skills),
mode: AgentSkillMode::Auto,
origin: AgentSkillOrigin::None,
});
let farm = farm_dir(&root.join("store"), "task-1");
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
@@ -1249,7 +1237,7 @@ mod tests {
let staged = listed(&claude_tree);
assert_eq!(
staged,
["codexy", "gh", "ideonly", "lint", "muted", "tdd"],
["azure-ai", "codexy", "gh", "ideonly", "lint", "muted", "tdd"],
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
);
@@ -1259,8 +1247,8 @@ mod tests {
let copilot_staged = listed(&farm.join("copilot"));
assert_eq!(
copilot_staged,
["codexy", "ideonly"],
"`gh` (.github), `tdd` (.agents) and `lint` (~/.agents) are native to Copilot; `.openidea` & `~/.codex` are staged"
["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"],
"all active Auto skills (including .github, .agents, ~/.agents, and ~/.copilot/installed-plugins) are staged for Copilot headless"
);
assert_eq!(
delivery.codex_off,
@@ -1276,12 +1264,12 @@ mod tests {
]
);
// A worktree task: the repo's skills are untracked, so workspace skills are staged now.
// A worktree task also stages all active workspace, user, and plugin skills.
let worktree = root.join("wt");
std::fs::create_dir_all(&worktree).unwrap();
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
let copilot_staged = listed(&farm.join("copilot"));
assert!(copilot_staged.contains(&"gh".to_string()) && copilot_staged.contains(&"tdd".to_string()));
assert_eq!(copilot_staged, ["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"]);
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
@@ -1289,7 +1277,7 @@ mod tests {
assert_eq!(settings["skillOverrides"]["muted"], "user-invocable-only");
assert_eq!(settings["skillOverrides"]["off"], "off");
// Restaging after a session turned `lint` off drops its link and leaves the skill.
// Restaging after a session turned `lint` off drops its link and leaves the skill on disk.
let session = BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)]);
let restated = resolve(
states.iter().map(|s| s.skill.clone()).collect(),
@@ -1299,10 +1287,14 @@ mod tests {
true,
);
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
assert_eq!(listed(&claude_tree), ["codexy", "gh", "ideonly", "muted", "tdd"]);
assert_eq!(listed(&claude_tree), ["azure-ai", "codexy", "gh", "ideonly", "muted", "tdd"]);
assert!(home.join(".agents/skills/lint").is_dir());
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
let delivery = stage(&farm, "copilot", &restated, &repo, Some(&home)).unwrap();
assert_eq!(listed(&farm.join("copilot")), ["azure-ai", "codexy", "gh", "ideonly", "tdd"]);
assert_eq!(delivery.copilot_disabled_skills, ["lint", "muted", "off"]);
// An ACP agent gets no farm.
let delivery = stage(&farm, "cursor-acp", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery, Delivery::default());
+41
Переглянути файл
@@ -1632,6 +1632,47 @@ async fn shutdown_writes_the_saves_still_waiting_and_a_delete_drops_them() {
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"));
}
/// Closing a project with many restored/archived tasks must not rewrite tasks that never changed.
#[tokio::test]
async fn shutdown_skips_rewriting_untouched_restored_tasks() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let untouched = idle_task(&mgr, "untouched").await;
let archived = idle_task(&mgr, "archived").await;
mgr.archive(&archived.id).unwrap();
let dirty = idle_task(&mgr, "dirty").await;
mgr.shutdown();
let (untouched_path, archived_path, dirty_path) =
(task_file(tmp.path(), &untouched.id), task_file(tmp.path(), &archived.id), task_file(tmp.path(), &dirty.id));
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let before_untouched = FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0);
let before_archived = FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0);
let before_dirty = FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0);
let dirty_handle = restored.task(&dirty.id).unwrap();
dirty_handle.state.lock().task.title = "updated".into();
dirty_handle.persist_soon();
restored.shutdown();
assert_eq!(
FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0),
before_untouched,
"untouched task should not be rewritten on shutdown"
);
assert_eq!(
FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0),
before_archived,
"archived task should not be rewritten on shutdown"
);
assert!(
FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0) > before_dirty,
"pending persist_soon task must still be flushed on shutdown"
);
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
}
/// Archiving saves the task as it is, including changes nobody asked to be saved.
#[tokio::test]
async fn archiving_saves_the_task_before_it_returns() {
+7 -2
Переглянути файл
@@ -6,7 +6,7 @@ use std::io::Read;
use std::time::SystemTime;
/// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only.
type Stamp = (u64, SystemTime, Option<String>);
pub(crate) type Stamp = (u64, SystemTime, Option<String>);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LaunchFingerprint {
@@ -182,7 +182,7 @@ fn collect(
}
/// Scans every input, storing project inputs relative to the project.
pub(super) fn scan_all(
pub(crate) fn scan_all(
root: &Path,
inputs: Vec<PathBuf>,
cancel: &CancellationToken,
@@ -282,6 +282,11 @@ pub(super) fn module_fingerprint(
}
impl LaunchFingerprint {
/// The fingerprint of `parameters` and the files under `inputs` (see [`scan_all`]).
pub(crate) fn new(parameters: String, files: BTreeMap<PathBuf, Option<Stamp>>) -> Self {
LaunchFingerprint { version: 2, parameters, files }
}
/// Folders (relative to the project) of the Maven projects whose POM is an input.
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
self.files
+145 -20
Переглянути файл
@@ -3,7 +3,7 @@
//! background with cancellation and parses the compiler output into messages
//! for the Build tool window, the Problems view and the editor.
mod fingerprint;
pub(crate) mod fingerprint;
mod launch_resources;
mod modules;
mod parse;
@@ -236,10 +236,13 @@ pub fn plan(
let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned());
let module_dir = match file {
Some(f) => {
let scope = model
.gradle
.iter()
.flat_map(|g| std::iter::once(root.join(&g.dir)).chain(g.projects.iter().map(|p| root.join(&p.dir))))
let maven_dirs = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| normalize(&root.join(&p.dir))));
let gradle_dirs = model.gradle.iter().flat_map(|g| {
std::iter::once(normalize(&root.join(&g.dir)))
.chain(g.projects.iter().map(|p| normalize(&root.join(&p.dir))))
});
let scope = maven_dirs
.chain(gradle_dirs)
.filter(|dir| f.starts_with(dir))
.max_by_key(|dir| dir.components().count())
.unwrap_or_else(|| root.to_path_buf());
@@ -251,10 +254,13 @@ pub fn plan(
None => None,
};
let dir = module_dir.clone().unwrap_or_else(|| root.to_path_buf());
// A folder of sibling projects has no build file itself; its Maven projects are built one by one.
let system = detect_dir(&dir, model, root)
.or((!model.gradle.is_empty()).then_some(BuildSystem::Gradle))
.or_else(|| model.maven.as_ref().filter(|m| !m.projects.is_empty()).map(|_| BuildSystem::Maven))
let direct_system = detect_dir(&dir, model, root);
let has_gradle = !model.gradle.is_empty();
let has_maven = model.maven.as_ref().is_some_and(|m| !m.projects.is_empty());
// A folder of sibling projects has no build file itself; build every linked Gradle and Maven project in it.
let system = direct_system
.or(has_gradle.then_some(BuildSystem::Gradle))
.or(has_maven.then_some(BuildSystem::Maven))
.ok_or_else(|| {
IdeError::not_found("no supported build system (Maven, Gradle, .NET, Cargo, Go, TypeScript, CMake) found")
})?;
@@ -267,17 +273,26 @@ pub fn plan(
),
None => project_name,
};
let steps = match system {
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
BuildSystem::Cargo => cargo_steps(&dir, kind),
// Go builds the file's package (a module holds many).
BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?,
BuildSystem::TypeScript => ts_steps(&dir, kind),
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
let steps = if module_dir.is_none() && direct_system.is_none() && has_gradle && has_maven {
let mut combined = gradle_steps(root, model, kind, None)?;
combined.extend(maven_steps(root, model, kind, None, cache, cancel)?);
combined
} else {
match system {
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
BuildSystem::Cargo => cargo_steps(&dir, kind),
// Go builds the file's package (a module holds many); a directory target builds itself.
BuildSystem::Go => {
let pkg = file.map(|f| if f.is_dir() { f } else { f.parent().unwrap_or(f) }).unwrap_or(&dir);
go_steps(pkg, kind)?
}
BuildSystem::TypeScript => ts_steps(&dir, kind),
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
}
};
Ok(BuildPlan { system, title, steps })
}
@@ -845,6 +860,28 @@ fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject)
projects
}
/// A step running Maven, its output parsed as Maven's.
pub(crate) fn maven_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
BuildStep::new(program, args, cwd, Format::Maven)
}
pub(crate) fn gradle_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
BuildStep::new(program, args, cwd, Format::Gradle)
}
/// The linked reactor root building the project at `module` (project-relative).
pub(crate) fn maven_reactor_dir<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
maven_reactor(m, module)
}
/// The projects of the reactor `top`.
pub(crate) fn reactor_projects_of<'a>(
m: &'a maven::MavenModel,
top: &'a maven::MavenProject,
) -> Vec<&'a maven::MavenProject> {
reactor_projects(m, top)
}
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
}
@@ -1890,4 +1927,92 @@ mod tests {
assert_eq!(launch_class_dirs(BuildSystem::Gradle, m, true)[0], m.join("build/classes/kotlin/test"));
assert_eq!(launch_class_dirs(BuildSystem::Maven, m, true), [m.join("target/classes")]);
}
#[test]
fn polyglot_root_targets_selected_subproject_or_combines_sibling_builds() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("polyglot");
write(&root, "Cargo.toml", "[package]\nname = \"root\"\nversion = \"0.1.0\"\n");
write(
&root,
"fixtures/java-app/pom.xml",
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>app</artifactId><version>1</version></project>",
);
write(&root, "fixtures/kotlin-gradle/build.gradle.kts", "plugins { kotlin(\"jvm\") }\n");
let model = crate::load(&root, &tmp.path().join("cache"), None);
let maven = plan(
&root,
&model,
BuildKind::Build,
Some(&root.join("fixtures/java-app")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(maven.system, BuildSystem::Maven);
assert_eq!(maven.steps.len(), 1);
assert_eq!(maven.steps[0].cwd, root.join("fixtures/java-app"));
let gradle = plan(
&root,
&model,
BuildKind::Build,
Some(&root.join("fixtures/kotlin-gradle")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(gradle.system, BuildSystem::Gradle);
assert_eq!(gradle.steps.len(), 1);
assert_eq!(gradle.steps[0].cwd, root.join("fixtures/kotlin-gradle"));
let cargo = plan(&root, &model, BuildKind::Build, Some(&root), None, None, &CancellationToken::new()).unwrap();
assert_eq!(cargo.system, BuildSystem::Cargo);
assert_eq!(cargo.steps[0].cwd, root);
// Folder without a root build file builds both linked Gradle and Maven subprojects on Build Project.
let mixed = tmp.path().join("mixed");
write(&mixed, "gradle-app/build.gradle.kts", "plugins { java }\n");
write(
&mixed,
"maven-app/pom.xml",
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>m</artifactId><version>1</version></project>",
);
let mixed_model = crate::load(&mixed, &tmp.path().join("cache2"), None);
let all = plan(&mixed, &mixed_model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(all.steps.len(), 2);
assert_eq!(all.steps[0].cwd, mixed.join("gradle-app"));
assert_eq!(all.steps[1].cwd, mixed.join("maven-app"));
}
#[test]
fn go_directory_target_builds_that_package_without_stepping_to_parent() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("go-app");
write(&root, "go.mod", "module example.com/app\n\ngo 1.22\n");
write(&root, "cmd/server/main.go", "package main\nfunc main() {}\n");
let pkg = plan(
&root,
&BuildModel::default(),
BuildKind::Build,
Some(&root.join("cmd/server")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(pkg.system, BuildSystem::Go);
assert_eq!(pkg.steps[0].cwd, root);
assert_eq!(pkg.steps[0].args, ["build", "./cmd/server/..."]);
let whole =
plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root), None, None, &CancellationToken::new())
.unwrap();
assert_eq!(whole.steps[0].cwd, root);
assert_eq!(whole.steps[0].args, ["build", "./..."]);
}
}
+6 -6
Переглянути файл
@@ -364,9 +364,9 @@ pub fn parse_reported_projects(output: &str) -> Vec<ReportedProject> {
output.lines().filter_map(|l| serde_json::from_str(l.trim_end().strip_prefix(MODEL_LINE)?).ok()).collect()
}
/// Source roots of the reported source sets: `(absolute folder, is test, is resources)`.
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot)> {
let mut out: Vec<(PathBuf, ReportedRoot)> = Vec::new();
/// Source roots of the reported source sets: `(absolute folder, role, absolute folder of its project)`.
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot, PathBuf)> {
let mut out: Vec<(PathBuf, ReportedRoot, PathBuf)> = Vec::new();
for p in reported {
for set in &p.source_sets {
let (src, res) = if set.test {
@@ -377,14 +377,14 @@ pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, Repo
for (dir, kind) in set.src.iter().map(|d| (d, src)).chain(set.res.iter().map(|d| (d, res))) {
let dir = PathBuf::from(dir);
// A folder shared by `main` and another set is `main`'s, as in IDEA.
if !out.iter().any(|(d, _)| *d == dir) {
out.push((dir, kind));
if !out.iter().any(|(d, _, _)| *d == dir) {
out.push((dir, kind, PathBuf::from(&p.dir)));
}
}
}
// IDEA excludes the build folder of every module.
if let Some(b) = &p.build_dir {
out.push((PathBuf::from(b), ReportedRoot::Excluded));
out.push((PathBuf::from(b), ReportedRoot::Excluded, PathBuf::from(&p.dir)));
}
}
out
+482
Переглянути файл
@@ -0,0 +1,482 @@
//! What the incremental build needs from a class file (JVMS §4): its name, supertypes, the
//! classes its constant pool refers to, and fingerprints of its API and of its compile-time
//! constants. Bounds-checked: a malformed file is `None`, never a panic.
use std::collections::BTreeSet;
/// A class file, as the dependency graph and the API diff see it.
#[derive(Clone, Debug, PartialEq)]
pub struct ClassFile {
/// Internal name (`com/acme/Order$Line`).
pub name: String,
pub super_name: Option<String>,
pub interfaces: Vec<String>,
/// Classes named in the constant pool: references, descriptors, signatures, annotation types.
pub refs: BTreeSet<String>,
/// What other classes compile against: non-private, non-synthetic members and their
/// signatures, supertypes, nested classes, permitted subclasses, record components.
pub api: u64,
/// The compile-time constants (`static final` fields with a `ConstantValue`), which javac
/// copies into the classes that use them: a change can't be traced through references.
pub constants: u64,
}
const ACC_PRIVATE: u16 = 0x0002;
const ACC_SYNTHETIC: u16 = 0x1000;
struct Bytes<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Bytes<'a> {
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let end = self.pos.checked_add(n)?;
let slice = self.data.get(self.pos..end)?;
self.pos = end;
Some(slice)
}
fn u1(&mut self) -> Option<u8> {
Some(self.take(1)?[0])
}
fn u2(&mut self) -> Option<u16> {
let b = self.take(2)?;
Some(u16::from_be_bytes([b[0], b[1]]))
}
fn u4(&mut self) -> Option<u32> {
let b = self.take(4)?;
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
}
#[derive(Clone, Debug)]
enum Entry {
Empty,
Utf8(String),
Class(u16),
String(u16),
/// Integer, float, long, double: the raw bytes.
Number(Vec<u8>),
NameAndType(u16),
MethodType(u16),
Other,
}
struct Pool(Vec<Entry>);
impl Pool {
fn utf8(&self, index: u16) -> Option<&str> {
match self.0.get(index as usize)? {
Entry::Utf8(s) => Some(s),
_ => None,
}
}
fn class(&self, index: u16) -> Option<&str> {
match self.0.get(index as usize)? {
Entry::Class(name) => self.utf8(*name),
_ => None,
}
}
/// A `ConstantValue`'s value, as bytes.
fn constant(&self, index: u16) -> Option<Vec<u8>> {
match self.0.get(index as usize)? {
Entry::Number(bytes) => Some(bytes.clone()),
Entry::String(utf8) => Some(self.utf8(*utf8)?.as_bytes().to_vec()),
_ => None,
}
}
}
/// FNV-1a: stable across Rust versions, so recorded fingerprints stay comparable.
#[derive(Clone, Copy)]
struct Fnv(u64);
impl Fnv {
fn new() -> Self {
Fnv(0xcbf2_9ce4_8422_2325)
}
fn bytes(&mut self, bytes: &[u8]) {
for b in bytes {
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
}
// A separator, so `ab`+`c` and `a`+`bc` differ.
self.0 = (self.0 ^ 0xff).wrapping_mul(0x100_0000_01b3);
}
fn str(&mut self, s: &str) {
self.bytes(s.as_bytes());
}
fn u16(&mut self, v: u16) {
self.bytes(&v.to_be_bytes());
}
}
/// Adds the class names a descriptor or signature mentions (`Lcom/acme/Order<Lx/Y;>;`).
fn descriptor_refs(text: &str, out: &mut BTreeSet<String>) {
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'L'
&& (i == 0
|| matches!(
bytes[i - 1],
b'(' | b')'
| b'['
| b';'
| b'<'
| b'>'
| b'+'
| b'-'
| b':'
| b'*'
| b'I'
| b'J'
| b'Z'
| b'B'
| b'C'
| b'S'
| b'F'
| b'D'
| b'V'
| b'^'
))
{
let start = i + 1;
let mut end = start;
while end < bytes.len() && !matches!(bytes[end], b';' | b'<' | b'.') {
end += 1;
}
if end < bytes.len() && end > start {
let name = &text[start..end];
if name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'$' | b'_') || b >= 0x80) {
out.insert(name.to_owned());
}
}
i = end;
} else {
i += 1;
}
}
}
fn class_ref(name: &str, out: &mut BTreeSet<String>) {
if name.starts_with('[') {
descriptor_refs(name, out);
} else {
out.insert(name.to_owned());
}
}
struct Member {
access: u16,
name: String,
descriptor: String,
/// Fingerprint of the attributes that are part of the API.
extra: u64,
constant: Option<Vec<u8>>,
}
fn attributes(r: &mut Bytes, pool: &Pool, mut on: impl FnMut(&str, &[u8])) -> Option<()> {
let count = r.u2()?;
for _ in 0..count {
let name = pool.utf8(r.u2()?)?.to_owned();
let len = r.u4()? as usize;
let body = r.take(len)?;
on(&name, body);
}
Some(())
}
fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Vec<Member>> {
let count = r.u2()?;
let mut out = Vec::with_capacity(count as usize);
for _ in 0..count {
let access = r.u2()?;
let name = pool.utf8(r.u2()?)?.to_owned();
let descriptor = pool.utf8(r.u2()?)?.to_owned();
descriptor_refs(&descriptor, refs);
let mut extra = Fnv::new();
let mut constant = None;
attributes(r, pool, |attr, body| {
let mut b = Bytes { data: body, pos: 0 };
match attr {
"Signature" => {
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
descriptor_refs(sig, refs);
extra.str("S");
extra.str(sig);
}
}
"ConstantValue" => constant = b.u2().and_then(|i| pool.constant(i)),
"Exceptions" => {
let mut names: Vec<&str> = Vec::new();
if let Some(n) = b.u2() {
for _ in 0..n {
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
names.push(c);
}
}
}
names.sort_unstable();
extra.str("E");
for n in names {
extra.str(n);
}
}
// An annotation element's default value is compiled into its uses.
"AnnotationDefault" => {
extra.str("D");
element_value(&mut b, pool, refs, &mut extra);
}
_ => {}
}
})?;
out.push(Member { access, name, descriptor, extra: extra.0, constant });
}
Some(out)
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
if r.u4()? != 0xCAFE_BABE {
return None;
}
r.u2()?;
r.u2()?;
let count = r.u2()?;
let mut entries = vec![Entry::Empty];
let mut i = 1;
while i < count {
let tag = r.u1()?;
let entry = match tag {
1 => {
let len = r.u2()? as usize;
Entry::Utf8(String::from_utf8_lossy(r.take(len)?).into_owned())
}
3 | 4 => Entry::Number(r.take(4)?.to_vec()),
5 | 6 => Entry::Number(r.take(8)?.to_vec()),
7 => Entry::Class(r.u2()?),
8 => Entry::String(r.u2()?),
9..=11 => {
r.take(4)?;
Entry::Other
}
12 => {
r.u2()?;
Entry::NameAndType(r.u2()?)
}
15 => {
r.take(3)?;
Entry::Other
}
16 => Entry::MethodType(r.u2()?),
17 | 18 => {
r.take(4)?;
Entry::Other
}
19 | 20 => {
r.take(2)?;
Entry::Other
}
_ => return None,
};
let wide = matches!(tag, 5 | 6);
entries.push(entry);
i += 1;
if wide {
entries.push(Entry::Empty);
i += 1;
}
}
let pool = Pool(entries);
let mut refs = BTreeSet::new();
for entry in &pool.0 {
match entry {
Entry::Class(name) => class_ref(pool.utf8(*name)?, &mut refs),
Entry::NameAndType(descriptor) | Entry::MethodType(descriptor) => {
descriptor_refs(pool.utf8(*descriptor)?, &mut refs)
}
_ => {}
}
}
let access = r.u2()?;
let name = pool.class(r.u2()?)?.to_owned();
let super_index = r.u2()?;
let super_name = if super_index == 0 { None } else { Some(pool.class(super_index)?.to_owned()) };
let mut interfaces = Vec::new();
for _ in 0..r.u2()? {
interfaces.push(pool.class(r.u2()?)?.to_owned());
}
let fields = members(&mut r, &pool, &mut refs)?;
let methods = members(&mut r, &pool, &mut refs)?;
let mut api = Fnv::new();
// ACC_SUPER and ACC_SYNTHETIC say nothing about what compiles against the class.
api.u16(access & !(0x0020 | ACC_SYNTHETIC));
api.str(&name);
api.str(super_name.as_deref().unwrap_or(""));
let mut sorted = interfaces.clone();
sorted.sort();
for i in &sorted {
api.str(i);
}
let mut class_attrs: Vec<(String, u64)> = Vec::new();
attributes(&mut r, &pool, |attr, body| {
let mut b = Bytes { data: body, pos: 0 };
let mut h = Fnv::new();
match attr {
"Signature" => {
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
descriptor_refs(sig, &mut refs);
h.str(sig);
}
}
"PermittedSubclasses" => {
let mut names = Vec::new();
for _ in 0..b.u2().unwrap_or(0) {
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
names.push(c.to_owned());
}
}
names.sort();
names.iter().for_each(|n| h.str(n));
}
"Record" => {
for _ in 0..b.u2().unwrap_or(0) {
let (Some(n), Some(d)) = (b.u2().and_then(|i| pool.utf8(i)), b.u2().and_then(|i| pool.utf8(i)))
else {
break;
};
h.str(n);
h.str(d);
let mut component = |attr: &str, body: &[u8]| {
if attr == "Signature"
&& let Some(sig) = (Bytes { data: body, pos: 0 }).u2().and_then(|i| pool.utf8(i))
{
h.str(sig);
}
};
if attributes(&mut b, &pool, &mut component).is_none() {
break;
}
}
}
// Nested classes this class declares, and their access.
"InnerClasses" => {
let mut nested = Vec::new();
for _ in 0..b.u2().unwrap_or(0) {
let (Some(inner), Some(outer), Some(_), Some(flags)) = (b.u2(), b.u2(), b.u2(), b.u2()) else {
break;
};
let inner = pool.class(inner).unwrap_or("");
if outer != 0 && pool.class(outer) == Some(name.as_str()) && flags & ACC_PRIVATE == 0 {
nested.push(format!("{inner}:{flags}"));
}
}
nested.sort();
nested.iter().for_each(|n| h.str(n));
}
"RuntimeVisibleAnnotations" | "RuntimeInvisibleAnnotations" => {
// Annotation types are dependencies; their values aren't API.
annotation_types(body, &pool, &mut refs);
return;
}
_ => return,
}
class_attrs.push((attr.to_owned(), h.0));
})?;
class_attrs.sort();
for (attr, h) in &class_attrs {
api.str(attr);
api.bytes(&h.to_be_bytes());
}
let mut constants = Fnv::new();
let mut api_members: Vec<(u8, &str, &str, u16, u64)> = Vec::new();
for (kind, list) in [(0u8, &fields), (1u8, &methods)] {
for m in list.iter() {
if kind == 0
&& let Some(value) = &m.constant
{
// Private constants are inlined too, but only in their own class.
if m.access & ACC_PRIVATE == 0 {
constants.str(&m.name);
constants.str(&m.descriptor);
constants.bytes(value);
}
}
if m.access & (ACC_PRIVATE | ACC_SYNTHETIC) != 0 || m.name == "<clinit>" {
continue;
}
api_members.push((kind, &m.name, &m.descriptor, m.access & !ACC_SYNTHETIC, m.extra));
}
}
api_members.sort();
for (kind, name, descriptor, access, extra) in api_members {
api.bytes(&[kind]);
api.str(name);
api.str(descriptor);
api.u16(access);
api.bytes(&extra.to_be_bytes());
}
refs.remove(&name);
refs.retain(|r| !r.starts_with("java/"));
Some(ClassFile { name, super_name, interfaces, refs, api: api.0, constants: constants.0 })
}
/// Adds the types of the annotations in a `Runtime*Annotations` attribute.
fn annotation_types(body: &[u8], pool: &Pool, refs: &mut BTreeSet<String>) {
let mut b = Bytes { data: body, pos: 0 };
let Some(count) = b.u2() else { return };
let mut ignored = Fnv::new();
for _ in 0..count {
if annotation(&mut b, pool, refs, &mut ignored).is_none() {
return;
}
}
}
fn annotation(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
for _ in 0..b.u2()? {
h.str(pool.utf8(b.u2()?)?);
element_value(b, pool, refs, h)?;
}
Some(())
}
/// An annotation element value: its class names go to `refs`, its value (resolved, not the
/// constant pool indices) to `h`.
fn element_value(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
let tag = b.u1()?;
h.bytes(&[tag]);
match tag {
b'B' | b'C' | b'D' | b'F' | b'I' | b'J' | b'S' | b'Z' => h.bytes(&pool.constant(b.u2()?)?),
b's' => h.str(pool.utf8(b.u2()?)?),
b'e' => {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
h.str(pool.utf8(b.u2()?)?);
}
b'c' => {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
}
b'@' => annotation(b, pool, refs, h)?,
b'[' => {
for _ in 0..b.u2()? {
element_value(b, pool, refs, h)?;
}
}
_ => return None,
}
Some(())
}
/// The simple name of a class (`com/acme/Order$Line` → `Line`), which a new class can shadow.
pub fn simple_name(name: &str) -> &str {
let tail = name.rsplit('/').next().unwrap_or(name);
tail.rsplit('$').next().unwrap_or(tail)
}
+145
Переглянути файл
@@ -0,0 +1,145 @@
// OpenIDEA's Java build of a Gradle build (ide_build::jbuild). With -Popenidea.build.output=<dir>,
// every Java source set writes its classes and resources to <dir>/[<group>.]<project>/classes|test-classes,
// so neither the language server nor a terminal `gradle` writes what the IDE runs. The task
// `openideaBuildModel` (-Popenidea.build.model=<file>) runs what generates sources, processes the
// resources and writes, as JSON, each source set's roots, classpaths and how JavaCompile compiles it:
// the same model the Maven extension writes (java/java-build, BuildModel).
import groovy.json.JsonOutput
import org.gradle.api.tasks.compile.AbstractCompile
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.jvm.tasks.Jar
def property = { String name -> gradle.startParameter.projectProperties[name] }
def outRoot = property('openidea.build.output')
if (outRoot == null || gradle.parent != null) return
// The project's name in the build: unique, unlike `name`.
def nameOf = { Project p -> p == p.rootProject ? p.name : p.path.substring(1).replace(':', '.') }
def outputOf = { Project p, String set ->
def folder = p.group ? "${p.group}.${nameOf(p)}" : nameOf(p)
new File(outRoot, folder + '/' + (set == 'main' ? 'classes' : 'test-classes'))
}
def javaSets = { Project p ->
def sets = p.extensions.findByName('sourceSets')
sets == null ? [] : ['main', 'test'].collect { sets.findByName(it) }.findAll { it != null }
}
gradle.projectsEvaluated {
def root = gradle.rootProject
root.allprojects.each { p ->
javaSets(p).each { ss ->
def out = outputOf(p, ss.name)
ss.java.destinationDirectory.set(out)
ss.output.resourcesDir = out
p.tasks.named(ss.processResourcesTaskName).configure { destinationDir = out }
}
}
root.tasks.register('openideaBuildModel') {
// What compiling needs from the same project (generated sources), and the resources.
dependsOn {
root.allprojects.collectMany { p ->
javaSets(p).collectMany { ss ->
def compile = p.tasks.getByName(ss.compileJavaTaskName)
def generators = compile.taskDependencies.getDependencies(compile).findAll {
it.project == p && !(it instanceof AbstractCompile) && !(it instanceof Jar)
}
generators + [p.tasks.getByName(ss.processResourcesTaskName)]
}
}
}
doLast {
// Project artifacts resolve to the projects' outputs.
def artifacts = [:]
root.allprojects.each { p ->
def main = javaSets(p).find { it.name == 'main' }
if (main == null) return
def jar = p.tasks.findByName('jar')
if (jar instanceof Jar) artifacts[jar.archiveFile.get().asFile.canonicalPath] = outputOf(p, 'main')
}
def files = { collection ->
def out = []
try {
collection?.files?.each { f ->
def mapped = artifacts[f.canonicalPath] ?: f
if (!out.contains(mapped.canonicalPath)) out << mapped.canonicalPath
}
} catch (e) {
out << "!${e.message}".toString()
}
out
}
def included = gradle.includedBuilds.collect { it.name }
def projects = root.allprojects.findAll { !javaSets(it).isEmpty() }.collect { p ->
def problems = included.isEmpty() ? [] : ["it is a composite build (${included.join(', ')})".toString()]
def others = p.tasks.withType(AbstractCompile).findAll {
!(it instanceof JavaCompile) && it.name ==~ /(?i)compile.*(Kotlin|Groovy|Scala|Aspectj).*/
}.collect { "${it.class.name.replace('_Decorated', '')}@${it.name}".toString() }
def setModel = { String name ->
def ss = javaSets(p).find { it.name == name }
if (ss == null) return [sourceRoots: [], output: outputOf(p, name).path, classpath: [], runtimeClasspath: []]
JavaCompile compile = p.tasks.getByName(ss.compileJavaTaskName)
def o = compile.options
def classpath = files(compile.classpath)
def runtime = files(ss.runtimeClasspath)
(classpath + runtime).findAll { it.startsWith('!') }.each { problems << "Cannot resolve the dependencies: ${it.substring(1)}".toString() }
def processorPath = files(o.annotationProcessorPath)
def processorProblems = processorPath.findAll { it.startsWith('!') }
def projectProcessors = processorPath.findAll { path -> artifacts.values().any { it.canonicalPath == path } }
def home = null
try { home = compile.javaCompiler.orNull?.metadata?.installationPath?.asFile?.canonicalPath } catch (ignored) {}
[
sourceRoots: ss.java.srcDirs.collect { it.canonicalPath },
output: outputOf(p, name).canonicalPath,
classpath: classpath.findAll { !it.startsWith('!') },
runtimeClasspath: runtime.findAll { !it.startsWith('!') },
resources: ss.resources.srcDirs.collect { [directory: it.canonicalPath, filtering: false] },
compiler: [
compilerId: 'javac',
source: compile.sourceCompatibility,
target: compile.targetCompatibility,
release: o.release.orNull?.toString(),
encoding: o.encoding,
debug: o.debug,
debuglevel: o.debugOptions.debugLevel,
showWarnings: o.warnings,
showDeprecation: o.deprecation,
fork: home != null,
executable: home == null ? null : new File(home, 'bin/javac').path,
generatedSourcesDirectory: o.generatedSourceOutputDirectory.asFile.orNull?.canonicalPath,
includes: ss.java.includes as List,
excludes: ss.java.excludes as List,
compilerArgs: o.allCompilerArgs.collect { it.toString() },
processorPath: processorProblems.isEmpty() && projectProcessors.isEmpty() ? processorPath : null,
processorPathError: !processorProblems.isEmpty()
? processorProblems[0].substring(1)
: (projectProcessors.isEmpty() ? null : 'its annotation processors are built in the same build'),
],
]
}
def mainModel = setModel('main')
def testModel = setModel('test')
// Gradle compiles tests against the main classes: they're the main output here.
[
dir: p.projectDir.canonicalPath,
groupId: (p.group ?: '').toString(),
artifactId: nameOf(p),
version: p.version.toString(),
packaging: 'jar',
main: mainModel,
test: testModel,
otherCompilers: others,
testGenerators: [],
problems: problems,
gradlePath: p.path,
]
}
def modelFile = property('openidea.build.model')
if (modelFile != null) {
def file = new File(modelFile)
def temporary = new File(file.parentFile, file.name + '.tmp')
temporary.text = JsonOutput.toJson([version: 1, projects: projects])
temporary.renameTo(file) || { file.delete(); temporary.renameTo(file) }()
}
}
}
}
+216
Переглянути файл
@@ -0,0 +1,216 @@
//! Class-level incremental compilation (#4078 step 3). Each source set records, per class it
//! compiled, the source it came from, its supertypes, the classes its constant pool names and
//! fingerprints of its API and constants ([`super::classfile`]). A build compiles the changed
//! sources, then the sources of classes that refer to a class whose API changed (or to a
//! subclass of one), round after round until no API changes. Sets compiled against this one
//! read its log of API changes; a changed compile-time constant, which javac copies into the
//! classes that use it, recompiles the whole set and every set compiled against it.
use super::*;
use std::collections::BTreeSet;
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct ClassRecord {
/// The source javac compiled it from; `None` for classes an annotation processor wrote
/// without naming an originating source.
pub source: Option<PathBuf>,
pub file: PathBuf,
pub super_name: Option<String>,
#[serde(default)]
pub interfaces: Vec<String>,
#[serde(default)]
pub refs: Vec<String>,
pub api: u64,
pub constants: u64,
}
impl ClassRecord {
pub fn new(class: classfile::ClassFile, file: PathBuf, source: Option<PathBuf>) -> (String, Self) {
let record = ClassRecord {
source,
file,
super_name: class.super_name,
interfaces: class.interfaces,
refs: class.refs.into_iter().collect(),
api: class.api,
constants: class.constants,
};
(class.name, record)
}
fn has_constants(&self) -> bool {
self.constants != NO_CONSTANTS
}
}
/// The constant fingerprint of a class without compile-time constants.
pub(super) const NO_CONSTANTS: u64 = 0xcbf2_9ce4_8422_2325;
/// The classes whose API one compilation of a set changed.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct ApiChange {
/// The set's generation before and after the compilation.
pub since: u64,
pub generation: u64,
pub classes: Vec<String>,
/// Everything counts as changed: a constant changed, or there was nothing to compare with.
pub all: bool,
}
/// How many compilations' API changes a set keeps for the sets compiled against it; one that
/// fell further behind compiles from scratch.
const CHANGE_LOG: usize = 64;
/// The inputs of a source set that, when changed, compile it from scratch.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct SetStamp {
pub options: Vec<String>,
/// Classpath entries outside the reactor's outputs, with their stamps (folders have none).
pub libraries: Vec<(PathBuf, Option<FileStamp>)>,
/// The reactor outputs on the classpath, in order.
pub reactor: Vec<PathBuf>,
pub processor_path: Vec<(PathBuf, Option<FileStamp>)>,
pub java_home: PathBuf,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub(super) struct SetState {
pub stamp: SetStamp,
/// The sources as of the last compilation.
pub sources: BTreeMap<PathBuf, FileStamp>,
/// Changes whenever the set's classes do.
pub generation: u64,
/// The generation of each reactor output it was compiled against.
pub upstream: BTreeMap<PathBuf, u64>,
pub classes: BTreeMap<String, ClassRecord>,
/// Sources a failed compilation left uncompiled.
pub dirty: BTreeSet<PathBuf>,
pub changes: Vec<ApiChange>,
/// Sources annotation processors wrote, and other files they wrote without an originating
/// source (`META-INF/services`…): processors that aggregate. While there are any, a change
/// compiles the set from scratch.
pub generated: Vec<PathBuf>,
pub unowned: Vec<PathBuf>,
pub success: bool,
}
impl SetState {
/// The classes whose API changed since generation `since`; `None` when unknown (the log
/// doesn't reach back that far) or when everything counts as changed.
pub fn changes_since(&self, since: u64) -> Option<BTreeSet<String>> {
let mut changed = BTreeSet::new();
let mut at = since;
while at != self.generation {
let change = self.changes.iter().find(|c| c.since == at)?;
if change.all {
return None;
}
changed.extend(change.classes.iter().cloned());
at = change.generation;
}
Some(changed)
}
pub fn log(&mut self, generation: u64, classes: BTreeSet<String>, all: bool) {
self.changes.push(ApiChange {
since: self.generation,
generation,
classes: classes.into_iter().collect(),
all,
});
if self.changes.len() > CHANGE_LOG {
self.changes.drain(..self.changes.len() - CHANGE_LOG);
}
self.generation = generation;
}
}
pub(super) fn load_state(path: &Path) -> Option<SetState> {
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}
/// `seeds` and the classes of `classes` that extend or implement one of them, transitively:
/// a class that inherits a changed member changes for the classes that use it.
pub(super) fn with_subclasses(classes: &BTreeMap<String, ClassRecord>, seeds: &BTreeSet<String>) -> BTreeSet<String> {
let mut out = seeds.clone();
loop {
let before = out.len();
for (name, record) in classes {
if !out.contains(name)
&& (record.super_name.as_ref().is_some_and(|s| out.contains(s))
|| record.interfaces.iter().any(|i| out.contains(i)))
{
out.insert(name.clone());
}
}
if out.len() == before {
return out;
}
}
}
/// The sources of the classes that refer to one of `affected`.
pub(super) fn dependent_sources(
classes: &BTreeMap<String, ClassRecord>,
affected: &BTreeSet<String>,
) -> BTreeSet<PathBuf> {
if affected.is_empty() {
return BTreeSet::new();
}
classes
.iter()
.filter(|(name, r)| affected.contains(*name) || r.refs.iter().any(|x| affected.contains(x)))
.filter_map(|(_, r)| r.source.clone())
.collect()
}
/// The sources of the classes that refer to a class with the same simple name as one of
/// `added`: a new class can take a simple name over from an on-demand import.
pub(super) fn shadowed_sources(classes: &BTreeMap<String, ClassRecord>, added: &BTreeSet<String>) -> BTreeSet<PathBuf> {
let names: BTreeSet<&str> = added.iter().map(|n| classfile::simple_name(n)).collect();
if names.is_empty() {
return BTreeSet::new();
}
classes
.iter()
.filter(|(name, r)| {
!added.contains(*name)
&& r.refs.iter().any(|x| !added.contains(x) && names.contains(classfile::simple_name(x)))
})
.filter_map(|(_, r)| r.source.clone())
.collect()
}
/// What one round's classes changed, compared with the classes the round replaced.
#[derive(Debug, Default)]
pub(super) struct RoundDiff {
pub api: BTreeSet<String>,
pub added: BTreeSet<String>,
pub constants: bool,
}
pub(super) fn diff(old: &BTreeMap<String, ClassRecord>, new: &BTreeMap<String, ClassRecord>) -> RoundDiff {
let mut out = RoundDiff::default();
for (name, record) in new {
match old.get(name) {
Some(before) => {
if before.api != record.api {
out.api.insert(name.clone());
}
if before.constants != record.constants {
out.constants = true;
}
}
None => {
out.api.insert(name.clone());
out.added.insert(name.clone());
}
}
}
for (name, before) in old {
if !new.contains_key(name) {
out.api.insert(name.clone());
out.constants |= before.has_constants();
}
}
out
}
+263
Переглянути файл
@@ -0,0 +1,263 @@
//! Resident javac processes (`java/java-build`, `ai.openidea.javac.Server`): one JVM per JDK
//! and JVM options, kept warm between builds, compiling one request at a time in process.
use super::*;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// A message of the server about one request.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")]
pub enum Reply {
Diagnostic {
severity: String,
path: Option<PathBuf>,
/// 1-based.
line: Option<u32>,
/// 0-based UTF-16.
column: Option<u32>,
end_line: Option<u32>,
end_column: Option<u32>,
code: Option<String>,
message: String,
},
/// A class (or resource) file javac wrote, and the source it came from.
Output {
path: PathBuf,
source: Option<PathBuf>,
},
/// A source file an annotation processor wrote.
Generated {
path: PathBuf,
source: Option<PathBuf>,
},
OutputText {
text: String,
},
Done {
success: bool,
cancelled: bool,
},
}
#[derive(Debug, Serialize)]
struct Request<'a> {
id: u64,
op: &'static str,
options: &'a [String],
sources: &'a [PathBuf],
encoding: Option<&'a str>,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct ServerKey {
pub java_home: PathBuf,
/// Options of the compiler's JVM (`.mvn/jvm.config`: `--add-opens` for processors).
pub jvm_args: Vec<String>,
}
type Pending = Arc<Mutex<HashMap<u64, mpsc::Sender<Reply>>>>;
pub struct JavacServer {
child: Mutex<Child>,
stdin: Mutex<ChildStdin>,
pending: Pending,
alive: Arc<AtomicBool>,
next: AtomicU64,
pub version: String,
}
impl JavacServer {
fn start(jar: &Path, key: &ServerKey) -> IdeResult<Self> {
let java = key.java_home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" });
let mut cmd = Command::new(&java);
cmd.args(&key.jvm_args)
.args(["-XX:+UseSerialGC", "-XX:TieredStopAtLevel=1", "-Dfile.encoding=UTF-8", "-cp"])
.arg(jar)
.arg("ai.openidea.javac.Server")
.env("JAVA_HOME", &key.java_home)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
ide_core::process::prepare(&mut cmd);
ide_core::process::own_group(&mut cmd);
let mut child =
cmd.spawn().map_err(|e| IdeError::unavailable(format!("Cannot start javac ({}): {e}", java.display())))?;
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let pending: Pending = Arc::default();
let alive = Arc::new(AtomicBool::new(true));
let (ready_tx, ready_rx) = mpsc::channel::<Result<String, String>>();
{
let (pending, alive) = (pending.clone(), alive.clone());
std::thread::Builder::new()
.name("javac-server".into())
.spawn(move || {
let mut ready = Some(ready_tx);
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
match value.get("kind").and_then(|k| k.as_str()) {
Some("ready") => {
let version = value.get("version").and_then(|v| v.as_str()).unwrap_or("").to_owned();
if let Some(ready) = ready.take() {
let _ = ready.send(Ok(version));
}
continue;
}
Some("fatal") => {
let message = value.get("message").and_then(|v| v.as_str()).unwrap_or("").to_owned();
if let Some(ready) = ready.take() {
let _ = ready.send(Err(message));
}
continue;
}
_ => {}
}
let Some(id) = value.get("id").and_then(|v| v.as_u64()) else { continue };
let Ok(reply) = serde_json::from_value::<Reply>(value) else { continue };
let done = matches!(reply, Reply::Done { .. });
let mut pending = pending.lock().unwrap();
if let Some(tx) = pending.get(&id) {
let _ = tx.send(reply);
}
if done {
pending.remove(&id);
}
}
alive.store(false, Ordering::SeqCst);
// Requests still waiting learn that the server is gone.
for (_, tx) in pending.lock().unwrap().drain() {
let _ = tx.send(Reply::Diagnostic {
severity: "error".into(),
path: None,
line: None,
column: None,
end_line: None,
end_column: None,
code: None,
message: "The javac process exited".into(),
});
let _ = tx.send(Reply::Done { success: false, cancelled: false });
}
if let Some(ready) = ready.take() {
let _ = ready.send(Err("The javac process exited while starting".into()));
}
})
.map_err(|e| IdeError::internal(e.to_string()))?;
}
let version = match ready_rx.recv_timeout(Duration::from_secs(60)) {
Ok(Ok(version)) => version,
Ok(Err(message)) => {
ide_core::process::kill_tree(&mut child);
return Err(IdeError::unavailable(format!("Cannot start javac ({}): {message}", java.display())));
}
Err(_) => {
ide_core::process::kill_tree(&mut child);
return Err(IdeError::unavailable(format!("javac ({}) did not start", java.display())));
}
};
Ok(JavacServer {
child: Mutex::new(child),
stdin: Mutex::new(stdin),
pending,
alive,
next: AtomicU64::new(1),
version,
})
}
fn alive(&self) -> bool {
self.alive.load(Ordering::SeqCst)
}
fn send(&self, value: &impl Serialize) -> IdeResult<()> {
let mut line = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
line.push(b'\n');
let mut stdin = self.stdin.lock().unwrap();
stdin.write_all(&line).and_then(|()| stdin.flush()).map_err(|e| IdeError::internal(format!("javac: {e}")))
}
/// Compiles `sources` with javac `options`, passing each reply to `on_reply`, until the
/// compilation ends. Cancelling stops javac at its next phase.
pub fn compile(
&self,
options: &[String],
sources: &[PathBuf],
encoding: Option<&str>,
cancel: &CancellationToken,
mut on_reply: impl FnMut(&Reply),
) -> IdeResult<bool> {
let id = self.next.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = mpsc::channel();
self.pending.lock().unwrap().insert(id, tx);
if let Err(e) = self.send(&Request { id, op: "compile", options, sources, encoding }) {
self.pending.lock().unwrap().remove(&id);
return Err(e);
}
let mut cancelled = false;
loop {
match rx.recv_timeout(Duration::from_millis(100)) {
Ok(reply) => {
if let Reply::Done { success, cancelled: stopped } = reply {
if stopped || cancelled {
return Err(IdeError::cancelled());
}
return Ok(success);
}
on_reply(&reply);
}
Err(mpsc::RecvTimeoutError::Timeout) => {
if cancel.is_cancelled() && !cancelled {
cancelled = true;
let _ = self.send(&serde_json::json!({ "op": "cancel", "id": id }));
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err(IdeError::internal("The javac process exited"));
}
}
}
}
}
impl Drop for JavacServer {
fn drop(&mut self) {
let _ = self.send(&serde_json::json!({ "op": "exit" }));
let mut child = self.child.lock().unwrap();
for _ in 0..20 {
if child.try_wait().ok().flatten().is_some() {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
ide_core::process::kill_tree(&mut child);
}
}
/// The resident javac servers of one IDE process.
#[derive(Default)]
pub struct JavacPool {
servers: Mutex<HashMap<ServerKey, Arc<JavacServer>>>,
}
impl JavacPool {
/// The running server for `key`, started on first use (or after it died).
pub fn server(&self, jar: &Path, key: &ServerKey) -> IdeResult<Arc<JavacServer>> {
let mut servers = self.servers.lock().unwrap();
if let Some(server) = servers.get(key).filter(|s| s.alive()) {
return Ok(server.clone());
}
let server = Arc::new(JavacServer::start(jar, key)?);
servers.insert(key.clone(), server.clone());
Ok(server)
}
/// Stops every server (the project closed).
pub fn shutdown(&self) {
self.servers.lock().unwrap().clear();
}
}
File diff suppressed because it is too large. Load diff
+342
Переглянути файл
@@ -0,0 +1,342 @@
//! The build model of a Maven reactor or Gradle build as the build tool itself configures it,
//! recorded by the prepare run (`java/java-build` `BuildModel`, `gradle-build.init.gradle`), and when that run is due.
use super::*;
use std::fs;
/// `model.json` of the prepare run (see `BuildModel.java`).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReactorModel {
pub version: u32,
pub projects: Vec<ProjectModel>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectModel {
/// Absolute project directory.
pub dir: PathBuf,
pub group_id: String,
pub artifact_id: String,
pub version: String,
pub packaging: String,
pub main: SourceSet,
pub test: SourceSet,
/// Executions in the compile phases that aren't javac (`group:artifact:goal@id`).
#[serde(default)]
pub other_compilers: Vec<String>,
/// Test source generators the prepare run doesn't reach.
#[serde(default)]
pub test_generators: Vec<String>,
#[serde(default)]
pub problems: Vec<String>,
/// The Gradle project path (`:`, `:app`); `None` for Maven.
#[serde(default)]
pub gradle_path: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceSet {
pub source_roots: Vec<PathBuf>,
pub output: PathBuf,
pub classpath: Vec<PathBuf>,
pub runtime_classpath: Vec<PathBuf>,
#[serde(default)]
pub resources: Vec<ResourceRoot>,
pub compiler: Option<CompilerConfig>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourceRoot {
pub directory: PathBuf,
#[serde(default)]
pub filtering: bool,
pub target_path: Option<String>,
#[serde(default)]
pub includes: Vec<String>,
#[serde(default)]
pub excludes: Vec<String>,
}
/// maven-compiler-plugin's configuration of one source set, as its mojo was configured.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CompilerConfig {
pub compiler_id: Option<String>,
pub source: Option<String>,
pub target: Option<String>,
pub release: Option<String>,
pub encoding: Option<String>,
pub parameters: Option<bool>,
pub debug: Option<bool>,
pub debuglevel: Option<String>,
pub proc: Option<String>,
pub enable_preview: Option<bool>,
pub fork: Option<bool>,
pub executable: Option<String>,
pub skip: Option<bool>,
pub show_warnings: Option<bool>,
pub show_deprecation: Option<bool>,
pub generated_sources_directory: Option<PathBuf>,
#[serde(default)]
pub includes: Vec<String>,
#[serde(default)]
pub excludes: Vec<String>,
pub annotation_processors: Option<Vec<String>>,
#[serde(default)]
pub compiler_args: Vec<String>,
pub compiler_argument: Option<String>,
#[serde(default)]
pub compiler_arguments: BTreeMap<String, Option<String>>,
pub multi_release_output: Option<bool>,
pub processor_path: Option<Vec<PathBuf>>,
pub processor_path_error: Option<String>,
}
impl ProjectModel {
pub fn key(&self) -> String {
format!("{}:{}", self.group_id, self.artifact_id)
}
pub fn set(&self, test: bool) -> &SourceSet {
if test { &self.test } else { &self.main }
}
/// Why the IDE can't compile this project with javac itself, if it can't.
pub fn unsupported(&self, test: bool) -> Option<String> {
// What the build tool couldn't resolve or read: the model would be incomplete.
if let Some(problem) = self.problems.first() {
return Some(format!("{}: {problem}", self.artifact_id));
}
if !self.other_compilers.is_empty() {
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
}
if test && !self.test_generators.is_empty() {
return Some(format!(
"{} generates test sources with {}",
self.artifact_id,
self.test_generators.join(", ")
));
}
for set in [&self.main, &self.test] {
let Some(c) = &set.compiler else { continue };
if c.compiler_id.as_deref().is_some_and(|id| id != "javac") {
return Some(format!("{} compiles with {}", self.artifact_id, c.compiler_id.as_deref().unwrap()));
}
if c.multi_release_output == Some(true) {
return Some(format!("{} is a multi-release jar", self.artifact_id));
}
if let Some(error) = &c.processor_path_error {
return Some(format!("{}: {error}", self.artifact_id));
}
}
None
}
}
/// Where the IDE's build of the reactor at `top_dir` keeps its model and outputs.
pub(super) fn reactor_dir(cache: &Path, top_dir: &str) -> PathBuf {
let base = cache.join("java-build");
if top_dir.is_empty() { base.join("_root") } else { base.join(top_dir) }
}
/// The outputs of every project, `<out>/<groupId>.<artifactId>/classes`, as the extension
/// redirects them (`-Dopenidea.build.output=<out>`).
pub(super) fn output_root(cache: &Path, top_dir: &str) -> PathBuf {
reactor_dir(cache, top_dir).join("out")
}
/// What the recorded model was prepared from.
#[derive(Debug, Deserialize, Serialize)]
pub(super) struct PrepareRecord {
pub fingerprint: LaunchFingerprint,
pub model: ReactorModel,
}
const MODEL_VERSION: u32 = 1;
/// Files the model depends on: the POM chains, settings, toolchains, the Maven launcher,
/// and generator inputs (any `src/<set>/<dir>` that isn't Java sources or resources:
/// `proto`, `antlr4`, `avro`…), but not the Java sources and resources themselves.
pub(super) fn prepare_fingerprint(
root: &Path,
reactor: &[&maven::MavenProject],
step: &BuildStep,
local_repo: Option<PathBuf>,
jar_version: &str,
cancel: &CancellationToken,
) -> IdeResult<Option<LaunchFingerprint>> {
let Some(mut inputs) = maven::model_inputs(root, reactor, local_repo) else { return Ok(None) };
for project in reactor {
let src = subdir(root, &project.dir).join("src");
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
for dir in fs::read_dir(set.path()).into_iter().flatten().flatten() {
let name = dir.file_name();
if dir.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
inputs.push(dir.path());
}
}
}
}
for dir in step.cwd.ancestors() {
inputs.extend([dir.join(".mvn"), dir.join("mvnw"), dir.join("mvnw.cmd")]);
if dir == root {
break;
}
}
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
if let Some(home) = dirs::home_dir() {
inputs.extend([home.join(".m2/settings.xml"), home.join(".m2/toolchains.xml")]);
}
if let Some(home) = step.env.get("JAVA_HOME") {
inputs.push(Path::new(home).join("release"));
}
inputs.sort();
inputs.dedup();
let parameters = serde_json::to_string(&(MODEL_VERSION, jar_version, &step.program, &step.args, &step.env))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(Some(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?)))
}
pub(super) fn load_record(dir: &Path) -> Option<PrepareRecord> {
let record: PrepareRecord = serde_json::from_slice(&fs::read(dir.join("prepare.json")).ok()?).ok()?;
(record.model.version == MODEL_VERSION).then_some(record)
}
pub(super) fn save_record(dir: &Path, record: &PrepareRecord) -> IdeResult<()> {
write_json(&dir.join("prepare.json"), record)
}
pub(super) fn write_json(path: &Path, value: &impl Serialize) -> IdeResult<()> {
let parent = path.parent().ok_or_else(|| IdeError::internal("no parent folder"))?;
fs::create_dir_all(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
serde_json::to_writer(file.as_file_mut(), value).map_err(|e| IdeError::internal(e.to_string()))?;
file.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
/// Whether the generated source roots the model lists still exist: `mvn clean` removes them.
pub(super) fn generated_roots_exist(model: &ReactorModel) -> bool {
model.projects.iter().all(|p| {
[&p.main, &p.test].iter().all(|set| {
set.source_roots.iter().all(|root| {
root.exists() || !root.components().any(|c| c.as_os_str() == "target") || is_processor_output(set, root)
})
})
})
}
/// The annotation processors' output folder, which javac writes into and never reads as a root.
pub(super) fn is_processor_output(set: &SourceSet, root: &Path) -> bool {
set.compiler.as_ref().and_then(|c| c.generated_sources_directory.as_deref()).is_some_and(|dir| dir == root)
}
/// A Maven step at the reactor root running `goals` with the IDE's extension loaded.
pub(super) fn maven_step(
root: &Path,
top: &maven::MavenProject,
jar: &Path,
output_root: &Path,
model_file: Option<&Path>,
extra: &[String],
) -> BuildStep {
let mut step = maven_build_step(
&top.command,
&["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG],
&subdir(root, &top.dir),
);
step.args.extend(top.options.iter().cloned());
step.args.push(format!("-Dmaven.ext.class.path={}", jar.display()));
step.args.push(format!("-Dopenidea.build.output={}", output_root.display()));
if let Some(file) = model_file {
step.args.push(format!("-Dopenidea.build.model={}", file.display()));
}
step.args.extend(extra.iter().cloned());
step.env = top.env.clone();
step
}
/// The init script that gives a Gradle build the IDE's outputs and writes its model.
const GRADLE_INIT_SCRIPT: &str = include_str!("gradle-build.init.gradle");
/// Writes the init script into the build's state folder, and returns its path.
pub(super) fn gradle_init_script(dir: &Path) -> IdeResult<PathBuf> {
fs::create_dir_all(dir)?;
let path = dir.join("openidea-build.init.gradle");
if fs::read_to_string(&path).ok().as_deref() != Some(GRADLE_INIT_SCRIPT) {
fs::write(&path, GRADLE_INIT_SCRIPT)?;
}
Ok(path)
}
/// A Gradle step at the build's root running `tasks` with the IDE's init script.
pub(super) fn gradle_step(
root: &Path,
g: &crate::GradleModel,
init: &Path,
output_root: &Path,
model_file: Option<&Path>,
tasks: &[String],
) -> BuildStep {
let mut step = gradle_build_step(
&g.command,
// The init script configures the evaluated projects, which a configuration cache skips.
&["--console=plain", "--no-configuration-cache"],
&subdir(root, &g.dir),
);
step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]);
step.args.push(format!("-Popenidea.build.output={}", output_root.display()));
if let Some(file) = model_file {
step.args.push(format!("-Popenidea.build.model={}", file.display()));
}
step.args.extend(tasks.iter().cloned());
step.env = g.env.clone();
step
}
/// Files a Gradle build's model depends on: settings and build scripts (with what they apply),
/// properties, the wrapper and catalogs, `buildSrc`, and generator inputs.
pub(super) fn gradle_prepare_fingerprint(
root: &Path,
g: &crate::GradleModel,
step: &BuildStep,
jar_version: &str,
cancel: &CancellationToken,
) -> IdeResult<LaunchFingerprint> {
let mut inputs = crate::gradle::build_files(root, g);
let dir = subdir(root, &g.dir);
inputs.extend([dir.join("buildSrc"), dir.join("gradle"), dir.join("gradlew"), dir.join("gradlew.bat")]);
for project in &g.projects {
let src = subdir(root, &project.dir).join("src");
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
for generator in fs::read_dir(set.path()).into_iter().flatten().flatten() {
let name = generator.file_name();
if generator.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
inputs.push(generator.path());
}
}
}
}
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
if let Some(home) = dirs::home_dir() {
inputs.push(home.join(".gradle/gradle.properties"));
inputs.push(home.join(".gradle/init.d"));
}
if let Some(home) = step.env.get("JAVA_HOME") {
inputs.push(Path::new(home).join("release"));
}
inputs.sort();
inputs.dedup();
let parameters =
serde_json::to_string(&(MODEL_VERSION, jar_version, GRADLE_INIT_SCRIPT, &step.program, &step.args, &step.env))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?))
}
pub(super) fn read_model(path: &Path) -> IdeResult<ReactorModel> {
let bytes = fs::read(path).map_err(|e| IdeError::internal(format!("The build wrote no model ({e})")))?;
serde_json::from_slice(&bytes).map_err(|e| IdeError::internal(format!("Unreadable build model: {e}")))
}
+552
Переглянути файл
@@ -0,0 +1,552 @@
use super::*;
use crate::BuildModel;
use std::fs;
use std::sync::Mutex as StdMutex;
const JAR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../java/java-build/openidea-java-build.jar");
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
fn tools() -> Option<(PathBuf, PathBuf)> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
let mvn = ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path())?;
Some((home, mvn))
}
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
struct Fixture {
_tmp: tempfile::TempDir,
root: PathBuf,
cache: PathBuf,
model: BuildModel,
/// Where the build keeps its state under the cache (`Reactor::key`).
key: &'static str,
service: JavaBuildService,
events: StdMutex<Vec<BuildEvent>>,
}
impl Fixture {
fn new(files: &[(&str, &str)]) -> Option<Self> {
let Some((home, mvn)) = tools() else {
eprintln!("skipped: needs JAVA_HOME and mvn");
return None;
};
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
for (rel, text) in
[("pom.xml", ROOT_POM), ("lib/pom.xml", LIB_POM), ("app/pom.xml", APP_POM)].iter().chain(files)
{
write(&root, rel, text);
}
let cache = root.join(".cache");
let mut model = crate::load(&root, &cache, None);
for p in &mut model.maven.as_mut().unwrap().projects {
p.command = mvn.to_string_lossy().into_owned();
p.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
}
Some(Fixture {
_tmp: tmp,
root,
cache,
model,
key: "",
service: JavaBuildService::default(),
events: StdMutex::default(),
})
}
/// The same `lib` ← `app` build with Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the
/// search path).
fn gradle(files: &[(&str, &str)]) -> Option<Self> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir());
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
let (Some(home), Some(gradle)) = (home, gradle) else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return None;
};
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let build = [
// A persistent Gradle daemon can keep the fixture's output pipes open on Windows.
("gradle.properties", "org.gradle.daemon=false\n"),
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"),
(
"build.gradle",
"subprojects {\n apply plugin: 'java'\n group = 't'\n tasks.withType(JavaCompile).configureEach { options.release = 11; options.encoding = 'UTF-8' }\n}\n",
),
("lib/build.gradle", ""),
(
"app/build.gradle",
"dependencies { implementation project(':lib') }\nprocessResources { filesMatching('*.properties') { expand(version: '1') } }\n",
),
];
for (rel, text) in build.iter().chain(files) {
write(&root, rel, text);
}
let cache = root.join(".cache");
let mut model = crate::load(&root, &cache, None);
assert_eq!(model.gradle.len(), 1, "{model:?}");
let g = &mut model.gradle[0];
g.command = gradle.to_string_lossy().into_owned();
g.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
Some(Fixture {
_tmp: tmp,
root,
cache,
model,
key: "_gradle",
service: JavaBuildService::default(),
events: StdMutex::default(),
})
}
fn write(&self, rel: &str, text: &str) {
write(&self.root, rel, text);
}
fn out(&self, rel: &str) -> PathBuf {
model::output_root(&self.cache, self.key).join(rel)
}
/// Builds the launch of `app` (its tests when `test`).
fn launch(&self, test: bool) -> LaunchOutputs {
self.build(Target::Launch { module: &self.root.join("app"), test })
}
fn build(&self, target: Target) -> LaunchOutputs {
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &self.root,
model: &self.model,
cache: &self.cache,
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
service: &self.service,
jdk: &jdk,
};
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
Err(e) => panic!("{e:?}"),
}
}
/// The steps of the launch builds since the last call.
fn steps(&self) -> Vec<String> {
self.events
.lock()
.unwrap()
.drain(..)
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command),
_ => None,
})
.collect()
}
/// Builds and returns the steps it took, which must succeed.
fn steps_of_launch(&self) -> Vec<String> {
self.steps();
let built = self.launch(false);
assert_eq!(built.failure, None, "{:?}", built.messages);
self.steps()
}
}
#[test]
fn builds_maven_modules_with_javac_and_only_what_changed() {
let Some(f) = Fixture::new(&[
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
),
(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
),
("app/src/main/resources/app.properties", "version=${project.version}\n"),
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
]) else {
return;
};
// First build: Maven prepares the model, javac compiles lib then app into the IDE's outputs.
let first = f.launch(false);
assert_eq!(first.failure, None, "{:?}", first.messages);
assert_eq!(first.class_paths[0], f.out("t.app/classes"));
assert!(first.class_paths.contains(&f.out("t.lib/classes")), "{:?}", first.class_paths);
assert!(f.out("t.app/classes/a/A.class").is_file());
assert!(f.out("t.lib/classes/l/L.class").is_file());
assert!(!f.root.join("app/target/classes/a/A.class").exists());
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
let steps = f.steps();
assert!(steps[0].contains("process-resources"), "{steps:?}");
assert_eq!(steps[1..], ["javac lib (main, 1 file)", "javac app (main, 1 file)"]);
// Nothing changed: no Maven, no javac.
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
// A change inside a method compiles that class only, without Maven.
f.write(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib 2\"; } }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 file)"]);
// A resource change is processed by Maven (it filters), and compiles nothing.
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
// A deleted source leaves no class behind.
f.write("app/src/main/java/a/Gone.java", "package a;\nclass Gone {}\n");
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
assert!(f.out("t.app/classes/a/Gone.class").is_file());
fs::remove_file(f.root.join("app/src/main/java/a/Gone.java")).unwrap();
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
assert!(!f.out("t.app/classes/a/Gone.class").exists());
// Compile errors fail the build with positioned messages.
f.write("app/src/main/java/a/A.java", "package a;\npublic class A { int x = \"s\"; }\n");
let failed = f.launch(false);
let failure = failed.failure.expect("fails");
assert!(failure.contains("incompatible types"), "{failure}");
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).unwrap();
assert_eq!(error.path.as_deref(), Some(f.root.join("app/src/main/java/a/A.java").as_path()));
assert_eq!(error.range.unwrap().start, Pos::new(1, 25));
// It compiles again next time, even unchanged.
f.steps();
assert!(f.launch(false).failure.is_some());
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
// A test launch compiles the module's tests after its main classes.
f.write(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
let tests = f.launch(true);
assert_eq!(tests.failure, None, "{:?}", tests.messages);
assert_eq!(tests.class_paths[..2], [f.out("t.app/test-classes"), f.out("t.app/classes")]);
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
// Recompile compiles the file even unchanged.
f.steps();
let file = f.root.join("app/src/main/java/a/A.java");
assert_eq!(f.build(Target::File(&file)).failure, None);
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
// Build Project builds every module's main and test classes.
f.write("lib/src/test/java/l/LTest.java", "package l;\nclass LTest { String s = L.name(); }\n");
assert_eq!(f.build(Target::Project).failure, None);
assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]);
assert!(f.out("t.lib/test-classes/l/LTest.class").is_file());
// Build Module on the root aggregator compiles every submodule under it.
f.write("app/src/test/java/a/AggTest.java", "package a;\nclass AggTest { String s = l.L.name(); }\n");
assert_eq!(f.build(Target::Module(&f.root)).failure, None);
assert_eq!(f.steps(), ["javac app (tests, 1 of 2 files)"]);
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
}
#[test]
fn recompiles_the_classes_an_api_change_reaches() {
let Some(f) = Fixture::new(&[
("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int m() { return 1; } }\n"),
("lib/src/main/java/l/Sub.java", "package l;\npublic class Sub extends Base {}\n"),
("lib/src/main/java/l/User.java", "package l;\nclass User { int u(Sub s) { return s.m(); } }\n"),
("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 1; }\n"),
("lib/src/main/java/l/ConstUser.java", "package l;\nclass ConstUser { int c() { return Const.X; } }\n"),
("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 1; } }\n"),
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new l.Other().o(); } }\n"),
("app/src/main/java/a/B.java", "package a;\nclass B { int b() { return l.Const.X; } }\n"),
]) else {
return;
};
assert_eq!(f.steps_of_launch()[1..], ["javac lib (main, 6 files)", "javac app (main, 2 files)"]);
// A body change: that class only, and nothing downstream.
f.write("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 2; } }\n");
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)"]);
// An API change reaches the classes that use the class or a subclass of it.
f.write(
"lib/src/main/java/l/Base.java",
"package l;\npublic class Base { public int m() { return 1; } public int n() { return 2; } }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac lib (main, 2 of 6 files)"]);
// Across modules: only the classes that use it.
f.write(
"lib/src/main/java/l/Other.java",
"package l;\npublic class Other { public int o() { return 2; } public void p() {} }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac app (main, 1 of 2 files)"]);
// A compile-time constant is copied into its uses: everything compiled against it compiles again.
f.write("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 2; }\n");
assert_eq!(
f.steps_of_launch(),
["javac lib (main, 1 of 6 files)", "javac lib (main, 5 of 6 files)", "javac app (main, 2 files)"]
);
// A removed method fails the classes that still call it.
f.write("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int n() { return 2; } }\n");
let failed = f.launch(false);
assert!(failed.failure.expect("fails").contains("User.java"));
}
#[test]
fn an_api_change_from_a_failed_build_still_reaches_other_modules() {
let Some(f) = Fixture::new(&[
("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int m() { return 1; } }\n"),
("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.m(); } }\n"),
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.m(); } }\n"),
]) else {
return;
};
assert_eq!(f.launch(false).failure, None);
// L compiles, then U, which still calls the removed method, fails lib before app compiles.
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int n() { return 1; } }\n");
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
// Once lib compiles, app learns that L changed, and A fails too instead of keeping a class
// that calls a method L no longer has.
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
let failed = f.launch(false);
assert!(failed.failure.expect("app fails").contains("A.java"), "{:?}", failed.messages);
// So does a changed constant: C compiles, then the whole set, where U fails.
f.write("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.n() + l.C.X; } }\n");
let c = |x: u32, y: &str| format!("package l;\npublic class C {{ public static final int X = {x};{y} }}\n");
f.write("lib/src/main/java/l/C.java", &c(1, " public static int y() { return 0; }"));
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n() + C.y(); } }\n");
assert_eq!(f.launch(false).failure, None);
f.write("lib/src/main/java/l/C.java", &c(2, ""));
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
f.steps();
assert_eq!(f.launch(false).failure, None);
let steps = f.steps();
assert!(steps.contains(&"javac app (main, 1 file)".to_owned()), "{steps:?}");
}
#[test]
fn reads_what_a_class_file_declares() {
let Some((home, _)) = tools() else { return };
let tmp = tempfile::tempdir().unwrap();
let compile = |text: &str| {
write(tmp.path(), "p/C.java", text);
let status = std::process::Command::new(home.join("bin/javac"))
.args(["-d", "out", "p/C.java"])
.current_dir(tmp.path())
.status()
.unwrap();
assert!(status.success());
classfile::parse(&fs::read(tmp.path().join("out/p/C.class")).unwrap()).unwrap()
};
let a = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public x.Y g() { return null; }\n private int hidden() { return 1; }\n}\nclass Z {}\n"
.replace("x.Y", "Object")
.as_str(),
);
assert_eq!(a.name, "p/C");
assert_eq!(a.super_name.as_deref(), Some("java/lang/Thread"));
assert_eq!(a.interfaces, ["java/lang/Runnable"]);
assert!(a.refs.contains("javax/swing/JButton"), "{:?}", a.refs);
assert!(!a.refs.iter().any(|r| r.starts_with("java/")), "{:?}", a.refs);
// Private members and method bodies aren't API; constants have their own fingerprint.
let b = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n private long hidden2() { return 1; }\n}\nclass Z {}\n",
);
assert_eq!((a.api, a.constants), (b.api, b.constants));
let c = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"changed\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
);
assert_eq!(a.api, c.api);
assert_ne!(a.constants, c.constants);
let d = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JLabel> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
);
assert_ne!(a.api, d.api);
}
#[test]
fn follows_api_changes_through_the_log() {
let mut state = SetState { generation: 1, ..Default::default() };
state.log(2, ["a/A".to_owned()].into(), false);
state.log(3, ["a/B".to_owned()].into(), false);
assert_eq!(state.changes_since(3), Some(BTreeSet::new()));
assert_eq!(state.changes_since(2), Some(["a/B".to_owned()].into()));
assert_eq!(state.changes_since(1), Some(["a/A".to_owned(), "a/B".to_owned()].into()));
// Unknown generations, and a log entry where everything changed, mean everything.
assert_eq!(state.changes_since(0), None);
state.log(4, BTreeSet::new(), true);
assert_eq!(state.changes_since(3), None);
}
#[test]
fn ant_patterns_match_like_maven() {
assert!(ant_match("**/*.java", "a/b/C.java"));
assert!(ant_match("**/*.java", "C.java"));
assert!(ant_match("com/acme/**", "com/acme/x/Y.java"));
assert!(!ant_match("com/acme/**", "com/other/Y.java"));
assert!(ant_match("**/generated/", "x/generated/Y.java"));
assert!(ant_match("**/*Test?.java", "a/FooTest1.java"));
assert!(!ant_match("*.java", "a/B.java"));
}
#[test]
fn javac_options_follow_the_compiler_configuration() {
let set = SourceSet {
output: PathBuf::from("/o"),
compiler: Some(CompilerConfig {
release: Some("17".into()),
source: Some("1.8".into()),
encoding: Some("UTF-8".into()),
parameters: Some(true),
debuglevel: Some("lines,vars".into()),
proc: Some("none".into()),
processor_path: Some(vec![PathBuf::from("/p.jar")]),
annotation_processors: Some(vec!["a.P".into()]),
compiler_args: vec!["-Xlint:unchecked".into()],
compiler_arguments: [("Akey=v".to_owned(), None)].into(),
show_warnings: Some(false),
..Default::default()
}),
..Default::default()
};
let args = javac_options(&set, &[PathBuf::from("/lib.jar")], Path::new("/gen"), Some(21));
let joined = args.join(" ");
let separator = if cfg!(windows) { ";" } else { ":" };
assert!(joined.starts_with(&format!("-d /o -classpath /o{separator}/lib.jar -sourcepath -s /gen")), "{joined}");
for expected in [
"-processorpath /p.jar",
"-processor a.P",
"-proc:none",
"-g:lines,vars",
"-parameters",
"-nowarn",
"-encoding UTF-8",
"--release 17",
"-Akey=v",
] {
assert!(joined.contains(expected), "{expected} in {joined}");
}
assert!(joined.ends_with("-Xlint:unchecked"), "{joined}");
// JDK 8 has no --release: source and target instead.
let old = javac_options(&set, &[], Path::new("/gen"), Some(8)).join(" ");
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
}
#[test]
fn builds_gradle_projects_with_javac_and_only_what_changed() {
let Some(f) = Fixture::gradle(&[
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
),
(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
),
("app/src/main/resources/app.properties", "version=${version}\n"),
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
]) else {
return;
};
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 3, "{steps:?}");
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
assert!(steps[1].starts_with("javac lib (main"), "{steps:?}");
assert!(steps[2].starts_with("javac app (main"), "{steps:?}");
assert!(f.out("t.lib/classes/l/L.class").is_file());
assert!(f.out("t.app/classes/a/A.class").is_file());
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
// Gradle's own outputs stay untouched.
assert!(!f.root.join("app/build/classes").exists());
let built = f.launch(false);
assert!(built.class_paths.iter().any(|p| p.ends_with("t.lib/classes")), "{:?}", built.class_paths);
assert!(!built.class_paths.iter().any(|p| p.extension().is_some_and(|e| e == "jar")), "{:?}", built.class_paths);
assert_eq!(f.steps(), Vec::<String>::new(), "nothing changed");
f.write(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name() + 1); } }\n",
);
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].starts_with("javac app (main"), "{steps:?}");
f.write("app/src/main/resources/app.properties", "version=${version}\nname=app\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains(":app:processResources"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nname=app\n");
// Tests compile against the main classes.
f.steps();
let built = f.launch(true);
assert_eq!(built.failure, None, "{:?}", built.messages);
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
// A changed build script prepares again.
f.write("lib/build.gradle", "// changed\n");
let steps = f.steps_of_launch();
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
// An error is a javac diagnostic on the source.
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static String name() { return 1; } }\n");
let built = f.launch(false);
assert!(built.failure.is_some());
let error = built.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
}
#[test]
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
let Some(f) = Fixture::gradle(&[
("app/build.gradle", "apply plugin: 'groovy'\ndependencies { implementation project(':lib') }\n"),
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
]) else {
return;
};
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &f.root,
model: &f.model,
cache: &f.cache,
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
service: &f.service,
jdk: &jdk,
};
let target = Target::Launch { module: &f.root.join("app"), test: false };
match build.build(target, BuildKind::Build, &CancellationToken::new(), &|_| {}) {
Ok(Built::Unsupported(reason)) => assert!(reason.contains("GroovyCompile"), "{reason}"),
Ok(Built::Done(outputs)) => panic!("built: {outputs:?}"),
Err(e) => panic!("{e:?}"),
}
}
+4 -2
Переглянути файл
@@ -9,6 +9,7 @@ pub mod application_update;
pub mod compile;
pub mod gradle;
mod gradle_deps;
pub mod jbuild;
pub mod kotlin_bridge;
pub mod maven;
pub mod pom_edit;
@@ -163,12 +164,13 @@ pub fn maven_external_roots(
gradle::external_roots(root, owned.iter().map(String::as_str))
}
/// Source, resource and build folders of the last Gradle sync, absolute.
/// Source, resource and build folders of the last Gradle sync, with the folder of the
/// project reporting each; all absolute.
pub fn gradle_source_roots(
root: &Path,
cache_dir: &Path,
settings: &ide_core::settings::GradleSettings,
) -> Vec<(PathBuf, gradle::ReportedRoot)> {
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
let reported = gradle::linked_dirs(root, settings)
.iter()
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
+26 -4
Переглянути файл
@@ -753,7 +753,26 @@ pub(crate) fn launch_inputs(
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
) -> Option<Vec<PathBuf>> {
fn roots(el: &Element, parent: &str, dir: &Path, out: &mut Vec<PathBuf>) -> Option<()> {
project_inputs(root, projects, local_repo, true)
}
/// The POM chains (with imported BOMs) of `projects` and the files their profiles activate
/// on: what Maven's model of them is built from, without their sources.
pub(crate) fn model_inputs(
root: &Path,
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
) -> Option<Vec<PathBuf>> {
project_inputs(root, projects, local_repo, false)
}
fn project_inputs(
root: &Path,
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
sources: bool,
) -> Option<Vec<PathBuf>> {
fn roots(el: &Element, parent: &str, dir: &Path, sources: bool, out: &mut Vec<PathBuf>) -> Option<()> {
let input =
matches!(el.name.as_str(), "sourceDirectory" | "testSourceDirectory" | "sourceDir" | "testSourceDir")
|| (matches!(parent, "sources" | "sourceDirs" | "testSources" | "testSourceDirs")
@@ -762,6 +781,7 @@ pub(crate) fn launch_inputs(
|| (parent == "filters" && el.name == "filter");
// Profile activation may depend on the presence of an otherwise unrelated file.
let activation = parent == "file" && matches!(el.name.as_str(), "exists" | "missing");
let input = input && sources;
if input || activation {
// A source root under Maven's build directory is generated by the build itself.
// Skip it without resolving the property: `<build><directory>` may be custom, and
@@ -787,7 +807,7 @@ pub(crate) fn launch_inputs(
}
}
for child in &el.children {
roots(child, &el.name, dir, out)?;
roots(child, &el.name, dir, sources, out)?;
}
Some(())
}
@@ -796,7 +816,9 @@ pub(crate) fn launch_inputs(
for project in projects {
let dir = root.join(&project.dir);
// Include all conventional language/resource roots, including nonstandard files under src.
out.push(dir.join("src"));
if sources {
out.push(dir.join("src"));
}
let pom = root.join(&project.pom);
resolver.context(&pom, 0);
let mut path = pom;
@@ -808,7 +830,7 @@ pub(crate) fn launch_inputs(
}
out.push(path.clone());
let text = xml::read_text(&path)?;
roots(&xml::parse(&text)?, "", &dir, &mut out)?;
roots(&xml::parse(&text)?, "", &dir, sources, &mut out)?;
let raw = resolver.pom(&path)?;
let Some(parent) = raw.parent else { break };
path = resolver.parent_path(path.parent()?, &parent)?;
+52 -4
Переглянути файл
@@ -9,7 +9,7 @@ use std::io::{BufRead, BufReader, Read};
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::Duration;
use std::time::{Duration, Instant};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stream {
@@ -28,6 +28,8 @@ pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
const LINE_QUEUE: usize = 64;
/// How long output may keep arriving after the child exits before the run stops reading it.
const OUTPUT_AFTER_EXIT: Duration = Duration::from_secs(1);
/// What [`pump_bounded`] reads from a pipe at a time.
const PUMP_CHUNK: usize = 64 * 1024;
@@ -236,6 +238,10 @@ fn run_with_env_capture(
let mut tail_bytes = 0usize;
let mut total = 0usize;
let mut truncated = false;
// When the child exited. A process it left running (a Gradle daemon on Windows) can inherit
// the pipes and keep them open long after; the run ends once they have been quiet this long.
let mut exited: Option<Instant> = None;
let mut pipes_held = false;
loop {
if cancel.is_cancelled() {
kill_tree(&mut child);
@@ -244,6 +250,9 @@ fn run_with_env_capture(
match rx.recv_timeout(Duration::from_millis(100)) {
Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {}
Ok((stream, line)) => {
if exited.is_some() {
exited = Some(Instant::now());
}
on_line(stream, &line);
if !bounded {
// The caller parses a complete model from `text`, so keep every line.
@@ -274,12 +283,26 @@ fn run_with_env_capture(
}
}
}
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Timeout) => match exited {
Some(at) if at.elapsed() >= OUTPUT_AFTER_EXIT => {
pipes_held = true;
break;
}
Some(_) => {}
None => {
if child.try_wait()?.is_some() {
exited = Some(Instant::now());
}
}
},
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
for r in readers.into_iter().flatten() {
let _ = r.join();
// Readers still blocked on a pipe that a leftover process holds end with it, on their own.
if !pipes_held {
for r in readers.into_iter().flatten() {
let _ = r.join();
}
}
let status = child.wait()?;
let mut text = head;
@@ -392,6 +415,31 @@ mod tests {
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
#[test]
fn a_process_left_holding_the_pipes_does_not_hold_the_run() {
if cfg!(windows) {
return;
}
let tmp = tempfile::tempdir().unwrap();
// The background child inherits stdout and stderr, as a Gradle daemon can on Windows.
let script = "echo built; (sleep 30) & echo done >&2";
let started = Instant::now();
let mut lines = Vec::new();
let out = run(
"sh",
&["-c".into(), script.into()],
tmp.path(),
&BTreeMap::new(),
&CancellationToken::new(),
|_, l| lines.push(l.to_owned()),
)
.unwrap();
assert!(started.elapsed() < Duration::from_secs(10), "took {:?}", started.elapsed());
assert!(out.success);
lines.sort();
assert_eq!(lines, ["built", "done"]);
}
#[test]
fn cancel_kills_grandchildren() {
if cfg!(windows) {
+4 -3
Переглянути файл
@@ -807,12 +807,13 @@ mod tests {
Some(gradle::ProcessedResources { task: "processResources".into(), dir: "/p/build/resources/main".into() })
);
let src = |p: &str| PathBuf::from(core_src(p));
let core = PathBuf::from(format!("{b}/modules/core"));
assert_eq!(
gradle::reported_source_roots(&projects),
[
(src("main/java"), gradle::ReportedRoot::Source),
(src("main/resources"), gradle::ReportedRoot::Resources),
(src("test/java"), gradle::ReportedRoot::Test),
(src("main/java"), gradle::ReportedRoot::Source, core.clone()),
(src("main/resources"), gradle::ReportedRoot::Resources, core.clone()),
(src("test/java"), gradle::ReportedRoot::Test, core),
]
);
let mut model = gradle::load(&root).unwrap();
+37 -4
Переглянути файл
@@ -58,9 +58,10 @@ pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
imp::set_text(text, owner)
}
/// The clipboard's plain text, None when it holds none. macOS only (main thread);
/// Linux reads it asynchronously through GTK in the app, Windows through the WebView.
#[cfg(target_os = "macos")]
/// The clipboard's plain text. None when macOS holds none, or when Windows cannot
/// open the clipboard; empty when Windows holds none. Call on the main thread on
/// macOS; Linux reads it asynchronously through GTK in the app.
#[cfg(any(windows, target_os = "macos"))]
pub fn text() -> Option<String> {
imp::text()
}
@@ -255,6 +256,15 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
out
}
/// A `CF_UNICODETEXT` block as a string: UTF-16LE up to the first NUL. The block
/// may be larger than the text, and a malformed one may lack the NUL.
#[cfg(any(windows, test))]
fn unicode_text(bytes: &[u8]) -> String {
let units: Vec<u16> =
bytes.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|&unit| unit != 0).collect();
String::from_utf16_lossy(&units)
}
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
#[cfg(any(windows, test))]
const BI_RGB: u32 = 0;
@@ -310,7 +320,7 @@ fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
#[cfg(windows)]
mod imp {
use super::{HEADER, decode, dib_to_png, encode, names_text};
use super::{HEADER, decode, dib_to_png, encode, names_text, unicode_text};
use std::ffi::c_void;
use std::path::PathBuf;
use std::ptr;
@@ -394,6 +404,19 @@ mod imp {
image
}
pub fn text() -> Option<String> {
// Empty rather than None: a None falls back to the WebView, which prompts the user.
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
return Some(String::new());
}
if !open() {
return None;
}
let text = read_block(CF_UNICODETEXT).map(|bytes| unicode_text(&bytes));
unsafe { CloseClipboard() };
text
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn GlobalAlloc(flags: u32, bytes: usize) -> Handle;
@@ -890,6 +913,16 @@ mod tests {
assert!(set_png(&header, 0).is_err());
}
#[test]
fn unicode_text_stops_at_the_nul() {
let mut bytes: Vec<u8> = "héllo\r\n世界".encode_utf16().chain([0, 0x41]).flat_map(u16::to_le_bytes).collect();
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
// No terminator, and a stray odd byte, still read the whole text.
bytes.truncate(bytes.len() - 4);
bytes.push(7);
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
}
fn paths(list: &[&str]) -> Vec<PathBuf> {
list.iter().map(PathBuf::from).collect()
}
+1
Переглянути файл
@@ -19,6 +19,7 @@ pub mod java_runtime;
pub mod jsonc;
pub mod memory;
pub mod output_encoding;
pub mod output_rate;
pub mod platform;
pub mod process;
pub mod project_dir;
+58
Переглянути файл
@@ -0,0 +1,58 @@
//! How often the terminal and Run console pumps hand output to the UI, from
//! Settings › Tools › Terminal › Max FPS (#5897). The frontend paints at most that
//! often anyway; batching at half its frame interval keeps a fresh batch ready for
//! every frame while cutting the IPC events (and their handling on the UI thread)
//! that would only be buffered there.
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
/// Frames per second; 0 is Unlimited.
static MAX_FPS: AtomicU32 = AtomicU32::new(0);
/// Applies the `terminal.maxFps` setting: `"unlimited"` or a number of frames per second.
/// Running sessions pick it up at their next batch.
pub fn set_max_fps(setting: &str) {
MAX_FPS.store(setting.trim().parse::<u32>().unwrap_or(0), Ordering::Relaxed);
}
/// The batch interval for a pump whose Unlimited interval is `unlimited`.
pub fn batch_interval(unlimited: Duration) -> Duration {
interval_for(MAX_FPS.load(Ordering::Relaxed), unlimited)
}
/// Half the paint interval, within 4–200 ms, and never faster than the Unlimited rate.
fn interval_for(fps: u32, unlimited: Duration) -> Duration {
if fps == 0 {
return unlimited;
}
Duration::from_millis((500 / u64::from(fps)).clamp(4, 200)).max(unlimited)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interval_is_half_the_frame_and_clamped() {
let terminal = Duration::from_millis(4);
let run = Duration::from_millis(8);
let ms = |fps, unlimited| interval_for(fps, unlimited).as_millis();
assert_eq!(ms(0, terminal), 4, "Unlimited keeps the pump's own rate");
assert_eq!(ms(0, run), 8);
assert_eq!([60, 30, 15, 10, 5].map(|fps| ms(fps, terminal)), [8, 16, 33, 50, 100]);
assert_eq!(ms(1, terminal), 200, "upper bound");
assert_eq!(ms(1000, terminal), 4, "lower bound");
assert_eq!(ms(1000, run), 8, "never faster than Unlimited");
}
#[test]
fn setting_values_parse_and_unknown_means_unlimited() {
set_max_fps("30");
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 16);
set_max_fps("unlimited");
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 4);
set_max_fps("fast");
assert_eq!(batch_interval(Duration::from_millis(8)).as_millis(), 8);
}
}
+10 -11
Переглянути файл
@@ -95,8 +95,6 @@ pub struct AgentSettings {
pub show_usage_limits: bool,
/// What the session has cost so far, as the agent reports it.
pub show_cost: bool,
/// A finished turn's work folds into one line under its message, leaving the reply.
pub fold_turns: bool,
/// Streaming text is revealed at a steady pace rather than chunk by chunk.
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
@@ -145,7 +143,6 @@ impl Default for AgentSettings {
show_work_time: true,
show_usage_limits: true,
show_cost: false,
fold_turns: false,
smooth_text: true,
fit_window_width: false,
thinking: ThinkingDisplay::Auto,
@@ -420,10 +417,10 @@ impl Default for McpServerSettings {
}
}
/// Tools › Download sources: a mirror the installer tries when `github.com` is slow or
/// unreachable.
/// Tools › Download sources: mirrors the installer tries, in order, when `github.com` is slow
/// or unreachable.
///
/// The mirror is a proxy prefix: the official URL is appended to it unchanged
/// A mirror is a proxy prefix: the official URL is appended to it unchanged
/// (`https://mirror.example/https://github.com/o/r/releases/download/…`), which is what the
/// public GitHub proxies speak. Only `github.com` downloads are affected — those proxies
/// hard-code that host, so Eclipse JDT LS and Open VSX keep their official addresses. Empty by
@@ -431,8 +428,9 @@ impl Default for McpServerSettings {
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ToolDownloadSettings {
/// Proxy prefix prepended to `https://github.com/…` archive addresses only; empty keeps
/// every download on its official host.
/// Proxy prefixes prepended to `https://github.com/…` archive addresses only, separated by
/// commas or whitespace and tried in order before the official host; empty keeps every
/// download on its official host.
pub github_mirror: String,
}
@@ -826,6 +824,8 @@ pub struct AppearanceSettings {
pub contrast_scrollbars: bool,
/// Adjust colours for red-green vision deficiency.
pub red_green_vision: bool,
/// Turn off animations and transitions (also on when the OS asks for reduced motion).
pub reduce_motion: bool,
pub different_tool_window_background: bool,
pub compact_mode: bool,
/// IDEA "Use smaller indents in trees": tool window trees indent less per level.
@@ -966,6 +966,7 @@ impl Default for AppearanceSettings {
ui_font_fallback: String::new(),
contrast_scrollbars: false,
red_green_vision: false,
reduce_motion: false,
different_tool_window_background: false,
compact_mode: false,
small_tree_indents: false,
@@ -2120,14 +2121,12 @@ mod tests {
#[test]
fn agent_meters_default_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true}}"#).unwrap();
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true,"foldTurns":true}}"#).unwrap();
assert!(old.agents.show_cost);
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
assert!(!old.agents.fit_window_width);
assert!(!old.agents.fold_turns);
assert!(!Settings::default().agents.show_cost);
assert!(!Settings::default().agents.fit_window_width);
assert!(!Settings::default().agents.fold_turns);
let mut settings = Settings::default();
settings.agents.show_usage_limits = false;
settings.agents.fit_window_width = true;
+24 -2
Переглянути файл
@@ -450,6 +450,21 @@ fn no_session(s: DebugSessionId) -> IdeError {
IdeError::not_found(format!("no debug session {}", s.0))
}
/// debugpy hands a subprocess (`subProcess: true`, forked or spawned) over as an `attach` whose
/// `connect` is its own client listener: the child session is another connection to the running
/// adapter, as VS Code makes it, not a new adapter that would take that port for a debug server.
fn subprocess_connection(configuration: &Value, spec: &AdapterSpec) -> Option<(AdapterSpec, u16)> {
configuration.get("subProcessId")?;
let connect = configuration.get("connect")?;
let port = u16::try_from(connect.get("port")?.as_u64()?).ok()?;
let mut spec = spec.clone();
if let Some(host) = connect.get("host").and_then(Value::as_str) {
let loopback = host == "localhost" || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
spec.server_host = (!loopback).then(|| host.to_owned());
}
Some((spec, port))
}
/// The name of a child session: the adapter's, or the parent's when it gives none. js-debug
/// names a browser page's session after the page the browser starts on, before the URL
/// loads (`about:blank`, or nothing in a new profile), which says nothing about what is debugged.
@@ -1032,6 +1047,13 @@ impl DebugManager {
if let Some(obj) = configuration.as_object_mut() {
obj.entry("request").or_insert_with(|| request.clone().into());
}
let (spec, port) = match parent.port {
Some(port) => (parent.spec.clone(), Some(port)),
None => match subprocess_connection(&configuration, &parent.spec) {
Some((spec, port)) => (spec, Some(port)),
None => (parent.spec.clone(), None),
},
};
self.start_session(
DebugSessionId::next(),
parent.owner.clone(),
@@ -1040,8 +1062,8 @@ impl DebugManager {
Some(parent.id),
request,
configuration,
parent.spec.clone(),
parent.port,
spec,
port,
None,
)
.await
+15 -1
Переглянути файл
@@ -1017,6 +1017,13 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
}
}
/// `text` as a terminal sends it when typed: Enter is CR. A Unix terminal turns CR into the
/// newline a line read waits for, but Windows' ConPTY reads LF as Ctrl+J, so a program blocked
/// in `input()` never sees its line end (#6041).
fn as_typed(text: &str) -> std::borrow::Cow<'_, str> {
if text.contains('\n') { text.replace("\r\n", "\r").replace('\n', "\r").into() } else { text.into() }
}
/// A `runInTerminal` program and the pseudo-terminal it runs in.
pub(crate) struct ProgramTerminal {
writer: Arc<ide_core::input::InputWriter>,
@@ -1030,7 +1037,7 @@ pub(crate) struct ProgramTerminal {
impl ProgramTerminal {
pub(crate) fn write(&mut self, text: &str) -> std::io::Result<()> {
self.writer.write(text.as_bytes())
self.writer.write(as_typed(text).as_bytes())
}
/// The program's process id while it runs.
@@ -1386,6 +1393,13 @@ fn parse_jdwp_port(line: &str) -> Option<u16> {
#[cfg(test)]
mod tests {
#[test]
fn typed_input_ends_lines_with_enter() {
assert_eq!(super::as_typed("42\n"), "42\r");
assert_eq!(super::as_typed("a\r\nb\n"), "a\rb\r");
assert_eq!(super::as_typed("no newline"), "no newline");
}
use super::{Suspension, kotlin_jvm_args, parse_jdwp_port};
#[test]
+46 -2
Переглянути файл
@@ -122,6 +122,8 @@ struct Script {
run_in_terminal: Option<Vec<String>>,
/// Send a `startDebugging` reverse request (child session) when a non-child `launch` arrives.
start_debugging: bool,
/// The child's `startDebugging` arguments instead of a js-debug style `launch`.
child_request: Option<Value>,
ignore_configuration_done: bool,
source_path: Option<String>,
/// Report this process id in the adapter's `process` event (the program being debugged).
@@ -201,6 +203,7 @@ impl Default for Script {
Self {
run_in_terminal: None,
start_debugging: false,
child_request: None,
ignore_configuration_done: false,
source_path: None,
debuggee_pid: None,
@@ -365,10 +368,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
);
}
if script.start_debugging && msg["arguments"]["isChild"] != true {
send!(
let arguments = script.child_request.clone().unwrap_or_else(
// Like js-debug, the child's configuration repeats the launch's `type`.
json!({"type": "request", "command": "startDebugging", "arguments": {"request": "launch", "configuration": {"name": "child", "isChild": true, "type": msg["arguments"]["type"]}}})
|| json!({"request": "launch", "configuration": {"name": "child", "isChild": true, "type": msg["arguments"]["type"]}}),
);
send!(json!({"type": "request", "command": "startDebugging", "arguments": arguments}));
}
if script.pending_startup != Some(false) {
tokio::time::sleep(script.initialized_delay).await;
@@ -1193,6 +1197,46 @@ async fn child_of(h: &Harness, parent: DebugSessionId) -> DebugSessionId {
panic!("no child session of {parent:?}");
}
/// debugpy's subprocess (`subProcess: true`): an `attach` whose `connect` is the running adapter's
/// client listener, so the child session connects there instead of starting another adapter.
#[tokio::test]
async fn a_debugpy_subprocess_connects_to_the_running_adapter() {
/// Each launch's reused port and remote host.
type Launches = Arc<Mutex<Vec<(Option<u16>, Option<String>)>>>;
struct CaptureLauncher {
inner: FakeLauncher,
launches: Launches,
}
impl AdapterLauncher for CaptureLauncher {
fn launch(&self, spec: AdapterSpec, reuse: Option<u16>) -> LaunchFuture {
self.launches.lock().push((reuse, spec.server_host.clone()));
self.inner.launch(spec, reuse)
}
}
let child = |host: &str| {
json!({"request": "attach", "configuration": {"name": "Subprocess 42", "isChild": true, "subProcessId": 42,
"connect": {"host": host, "port": 51234}}})
};
for (host, server_host) in [("127.0.0.1", None), ("10.0.0.5", Some("10.0.0.5".to_owned()))] {
let launches: Launches = Arc::default();
let script = Script { start_debugging: true, child_request: Some(child(host)), ..Script::default() };
let launcher =
CaptureLauncher { inner: FakeLauncher { log: Arc::default(), script }, launches: launches.clone() };
let manager =
DebugManager::with_launcher(Arc::new(LanguageRegistry::from_configs(Vec::new())), Arc::new(launcher));
let (owner, _) = recording_owner("main");
let parent = manager.start(config(), owner).await.unwrap();
for _ in 0..200 {
if launches.lock().len() == 2 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(*launches.lock(), [(None, None), (Some(51234), server_host)], "{host}");
manager.stop(parent).await.unwrap();
}
}
#[tokio::test]
async fn a_browser_page_session_has_the_page_capability() {
let h = harness(Script { start_debugging: true, ..Script::default() });
+236 -64
Переглянути файл
@@ -135,7 +135,7 @@ impl Context {
}
macro_rules! sqlx_pool {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $initialize:ident, $unfinished:expr) => {
pub struct $manager {
options: $options,
init: Arc<Vec<String>>,
@@ -164,41 +164,28 @@ macro_rules! sqlx_pool {
}
}
impl $manager {
async fn initialize(&self, mut conn: $connection) -> Result<$handle, sqlx::Error> {
let context = Context::new($initialize(&self.options, &mut conn, &self.init).await?);
Ok($handle {
conn: Some(conn),
context,
options: self.options.clone(),
init: self.init.clone(),
timeout: self.timeout,
in_transaction: false,
})
}
}
impl ManageConnection for $manager {
type Connection = $handle;
type Error = sqlx::Error;
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
tokio::time::timeout(self.timeout, async {
let mut conn = self.options.connect().await?;
let context_sql = |value: Option<String>| {
value.map(|v| {
if $driver == DbDriver::Postgres {
format!("SET search_path TO {v}")
} else {
crate::sql::use_schema($driver, &v).expect("switchable driver")
}
})
};
for sql in self.init.iter() {
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
}
$(if !self.init.is_empty() {
self.options.$after_init(&mut conn).await?;
})?
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
let context = Context::new(context_sql(row.try_get(0)?));
Ok($handle {
conn: Some(conn),
context,
options: self.options.clone(),
init: self.init.clone(),
timeout: self.timeout,
in_transaction: false,
})
})
.await
.map_err(|_| sqlx::Error::PoolTimedOut)?
tokio::time::timeout(self.timeout, async { self.initialize(self.options.connect().await?).await })
.await
.map_err(|_| sqlx::Error::PoolTimedOut)?
}
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
@@ -206,16 +193,24 @@ macro_rules! sqlx_pool {
}
fn has_broken(&self, conn: &mut Self::Connection) -> bool {
conn.conn.is_none()
conn.conn.is_none() || ($unfinished)(conn)
}
}
};
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum PgReadOnly {
Off,
Session,
Transaction,
}
#[derive(Clone)]
struct PostgresOptions {
connection: PgConnectOptions,
read_only: bool,
read_only: PgReadOnly,
local_settings: Arc<[String]>,
}
const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
@@ -230,7 +225,7 @@ impl PostgresOptions {
}
async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
if self.read_only == PgReadOnly::Session && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL did not enable the requested default_transaction_read_only setting. \
@@ -244,7 +239,7 @@ impl PostgresOptions {
async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
self.verify_read_only(conn).await?;
if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
if self.read_only == PgReadOnly::Session && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
"The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
));
@@ -285,19 +280,53 @@ fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
error
}
sqlx_pool!(
PgManager,
PgHandle,
PostgresOptions,
PgConnection,
DbDriver::Postgres,
"SHOW search_path",
verify_startup_script
);
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
async fn initialize_postgres(
options: &PostgresOptions,
conn: &mut PgConnection,
init: &[String],
) -> Result<Option<String>, sqlx::Error> {
let guarded = options.read_only == PgReadOnly::Transaction;
if guarded {
sqlx::raw_sql(pg_read_only::BEGIN).execute(&mut *conn).await?;
}
for sql in init {
if guarded {
pg_read_only::check_single(conn, sql).await?;
}
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
}
if !guarded && !init.is_empty() {
options.verify_startup_script(conn).await?;
}
let row = sqlx::raw_sql("SHOW search_path").fetch_one(&mut *conn).await?;
let path: Option<String> = row.try_get(0)?;
if guarded {
sqlx::raw_sql("COMMIT").execute(conn).await?;
return Ok(path);
}
Ok(path.map(|v| format!("SET search_path TO {v}")))
}
async fn initialize_mysql(
_: &MySqlConnectOptions,
conn: &mut MySqlConnection,
init: &[String],
) -> Result<Option<String>, sqlx::Error> {
for sql in init {
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
}
let row = sqlx::raw_sql("SELECT DATABASE()").fetch_one(conn).await?;
Ok(row.try_get::<Option<String>, _>(0)?.and_then(|v| crate::sql::use_schema(DbDriver::Mysql, &v)))
}
sqlx_pool!(PgManager, PgHandle, PostgresOptions, PgConnection, initialize_postgres, |c: &PgHandle| c.options.read_only
== PgReadOnly::Transaction
&& c.in_transaction);
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, initialize_mysql, |_: &MysqlHandle| false);
pub struct ServerPool<M: ManageConnection> {
inner: Bb8Pool<M>,
transaction_read_only: bool,
closed: AtomicBool,
}
@@ -774,7 +803,9 @@ macro_rules! backend_id {
}
mod cursor;
mod pg_read_only;
pub(crate) use cursor::{Cursors, Key as CursorKey};
pub(crate) use pg_read_only::validate as validate_pg_read_only;
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
/// leaves the session as it was.
@@ -947,6 +978,10 @@ impl Setup {
}
impl Pool {
pub(crate) fn transaction_read_only(&self) -> bool {
matches!(self, Pool::Postgres(p) if p.transaction_read_only)
}
pub fn driver(&self) -> DbDriver {
match self {
Pool::Sqlite(_) => DbDriver::Sqlite,
@@ -1058,27 +1093,68 @@ impl Pool {
if let Some(p) = password {
opts = opts.password(p);
}
if !setup.params.is_empty() {
opts = opts.options(setup.params);
}
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
}
let options = PostgresOptions { connection: opts, read_only: source.read_only };
let mut manager = PgManager { options, init: init.clone(), timeout };
// Open once directly so authentication failures retain their database error.
let first = match manager.connect().await {
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
manager.connect().await
}
first => first,
// Remove only the option supplied by the Read-only checkbox on a retry.
let fallback = source.read_only.then(|| {
let opts = opts.clone().statement_cache_capacity(0);
if setup.params.len() == 1 { opts } else { opts.options(setup.params.iter().skip(1).cloned()) }
});
if !setup.params.is_empty() {
opts = opts.options(setup.params);
}
.map_err(|e| postgres_connect_error(e, source.read_only))?;
let mode = if source.read_only { PgReadOnly::Session } else { PgReadOnly::Off };
let mut manager = PgManager {
options: PostgresOptions { connection: opts, read_only: mode, local_settings: Arc::default() },
init: init.clone(),
timeout,
};
let mut fallback = fallback;
let mut try_plain = source.ssl == DbSslMode::Prefer;
let first = loop {
let mut login_failed = false;
let result = tokio::time::timeout(timeout, async {
let mut conn =
manager.options.connection.connect().await.inspect_err(|_| login_failed = true)?;
manager.options.verify_read_only(&mut conn).await?;
manager.initialize(conn).await
})
.await
.unwrap_or(Err(sqlx::Error::PoolTimedOut));
match result {
Err(e) if login_failed && try_plain && tls_failed(&e) => {
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
try_plain = false;
manager.options.connection =
manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
fallback = fallback.map(|opts| opts.ssl_mode(PgSslMode::Disable));
}
Err(e)
if login_failed
&& fallback.is_some()
&& e.as_database_error().is_some_and(|db| {
postgres_read_only_hint(true, db.code().as_deref(), db.message()).is_some()
}) =>
{
manager.options.connection =
fallback.take().expect("read-only startup option was supplied");
manager.options.read_only = PgReadOnly::Transaction;
try_plain = false;
let (startup, settings) = pg_read_only::startup(&init).map_err(IdeError::invalid)?;
manager.init = Arc::new(startup);
manager.options.local_settings = settings.into();
tracing::info!(
"PostgreSQL endpoint rejected read-only startup; using read-only transactions"
);
}
result => break result.map_err(|e| postgres_connect_error(e, source.read_only))?,
}
};
let transaction_read_only = manager.options.read_only == PgReadOnly::Transaction;
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
let _ = pool.add(first);
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
Ok(Pool::Postgres(ServerPool { inner: pool, transaction_read_only, closed: AtomicBool::new(false) }))
}
DbDriver::Mysql => {
let mut opts = MySqlConnectOptions::new()
@@ -1139,7 +1215,11 @@ impl Pool {
let first = first.map_err(db_err)?;
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
let _ = pool.add(first);
Ok(Pool::Mysql(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
Ok(Pool::Mysql(ServerPool {
inner: pool,
transaction_read_only: false,
closed: AtomicBool::new(false),
}))
}
DbDriver::SqlServer => {
use tiberius::Config;
@@ -1204,6 +1284,29 @@ impl Pool {
matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_))
}
async fn cancel_query(&self, sql: String) {
if let Pool::Postgres(p) = self
&& p.transaction_read_only
{
// The target owns its backend until cancellation finishes; all regular pool slots may be busy.
let control = async {
let mut c = p.inner.dedicated_connection().await.map_err(db_err)?;
c.start_read_only().await?;
Ok::<_, IdeError>(c)
};
// Never queue a late cancel after giving up the backend whose PID it names.
if let Ok(Ok(mut conn)) = tokio::time::timeout(Duration::from_secs(2), control).await {
let _ = sqlx::raw_sql(sqlx::AssertSqlSafe(format!("{sql}; ROLLBACK"))).execute(&mut *conn).await;
} else {
tracing::debug!(
"No PostgreSQL backend available to signal cancellation; discarding the client connection"
);
}
} else {
let _ = self.rows(&sql, 1).await;
}
}
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
if let Pool::Jdbc(p) = self {
@@ -1217,8 +1320,13 @@ impl Pool {
}
let mut conn = Held::acquire(self).await?;
conn.apply_context(None).await?;
let fetched = conn.fetch_rows(sql, max).await;
Ok(fetched?.1)
let owned = conn.begin_read_only().await?;
let result = async {
conn.check_protected_statement(sql).await?;
conn.fetch_rows(sql, max).await
}
.await;
Ok(conn.finish_read_only(owned, result).await?.1)
}
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
@@ -1260,6 +1368,9 @@ impl Pool {
/// Runs `statements` in one transaction; each must change `expect_one`
/// row when flagged (table editor submits).
pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult<u64> {
if self.transaction_read_only() {
return Err(IdeError::invalid("Cannot submit table changes on a read-only PostgreSQL source"));
}
match self {
Pool::Jdbc(_) => Err(IdeError::invalid("Custom JDBC table editing is unsupported")),
Pool::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
@@ -1426,6 +1537,15 @@ impl Held {
Held::Oracle(_) => DbDriver::Oracle,
_ => return Ok(()),
};
if let Held::Postgres(c) = self
&& c.options.read_only == PgReadOnly::Transaction
{
let wanted = schema
.filter(|s| !s.is_empty())
.map(|s| crate::sql::quote_ident(driver, s))
.or_else(|| c.context.default.clone());
return c.select_path(wanted).await;
}
let context = self.context().expect("switchable connection");
let wanted = context.wanted(driver, schema);
if context.known && context.current == wanted {
@@ -1467,6 +1587,7 @@ impl Held {
}
async fn fetch_rows(&mut self, sql: &str, max: usize) -> IdeResult<Fetched> {
self.require_read_only_transaction()?;
self.before_statement(sql);
let result = match self {
Held::Sqlite(c) => fetch!(&mut **c, sql, max, Cells::Text),
@@ -1484,6 +1605,31 @@ impl Held {
/// Runs a statement without results (`BEGIN`, `COMMIT`, `ROLLBACK`).
pub async fn command(&mut self, sql: &str) -> IdeResult<()> {
let owned = self.begin_read_only().await?;
let result = async {
self.check_protected_statement(sql).await?;
self.run_command(sql).await
}
.await;
self.finish_read_only(owned, result).await
}
pub(crate) async fn begin_manual(&mut self, driver: DbDriver) -> IdeResult<()> {
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction) {
self.begin_read_only().await?;
return Ok(());
}
self.run_command(begin_statement(driver)).await
}
pub(crate) async fn finish_manual(&mut self, commit: bool) -> IdeResult<()> {
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction) {
return self.end_read_only(commit).await;
}
self.run_command(if commit { "COMMIT" } else { "ROLLBACK" }).await
}
async fn run_command(&mut self, sql: &str) -> IdeResult<()> {
self.before_statement(sql);
let result = self.raw_command(sql).await;
if result.is_ok() {
@@ -1493,6 +1639,7 @@ impl Held {
}
async fn raw_command(&mut self, sql: &str) -> IdeResult<()> {
self.require_read_only_transaction()?;
match self {
Held::SqlServer(c) => mssql_command(c, sql).await,
Held::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
@@ -1575,6 +1722,31 @@ impl Held {
if let Held::Snowflake(c, schema) = self {
return c.execute_in(schema.as_deref(), sql, skip, max_rows, cancel).await;
}
let owned = self.begin_read_only().await?;
let result = async {
self.check_protected_statement(sql).await?;
self.run_statement(pool, sql, skip, max_rows, cancel).await
}
.await;
if cancel.is_cancelled()
&& let Held::Postgres(c) = self
&& c.options.read_only == PgReadOnly::Transaction
{
c.conn.take();
return Err(IdeError::cancelled());
}
self.finish_read_only(owned, result).await
}
async fn run_statement(
&mut self,
pool: &Pool,
sql: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
self.require_read_only_transaction()?;
self.before_statement(sql);
let started = Instant::now();
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
@@ -1590,7 +1762,7 @@ impl Held {
};
if cancel.is_cancelled() {
if let Some(b) = backend {
let _ = pool.rows(&$kill(b), 1).await;
pool.cancel_query($kill(b)).await;
}
return Err(IdeError::cancelled());
}
+24 -9
Переглянути файл
@@ -95,6 +95,7 @@ impl Cursors {
skip: usize,
max: usize,
cancel: &CancellationToken,
protected: bool,
) -> Option<IdeResult<Fetched>> {
let (id, reads) = {
let mut registry = self.registry.lock();
@@ -110,7 +111,7 @@ impl Cursors {
self.finish(id, &fetched);
Some(Ok(fetched))
}
Some(Err(e)) if e.kind == ErrorKind::Cancelled => {
Some(Err(e)) if protected || e.kind == ErrorKind::Cancelled => {
self.close(id);
Some(Err(e))
}
@@ -196,6 +197,19 @@ impl Cursors {
/// nobody asks for [`IDLE`], or it is released (its channel closes).
async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Receiver<Read>) {
let Some(first) = reads.recv().await else { return held.discard().await };
let prepare = async {
let owned = held.begin_read_only().await?;
held.check_protected_statement(&sql).await?;
Ok(owned)
}
.await;
let owned = match prepare {
Ok(owned) => owned,
Err(error) => {
let _ = first.reply.send(Err(error));
return;
}
};
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
// Evaluates to whether the connection can go back to its pool (the stream was read to
// its end); otherwise it is closed rather than left to be drained.
@@ -217,7 +231,7 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
};
if cancel.is_cancelled() {
if let Some(b) = backend {
let _ = pool.rows(&$kill(b), 1).await;
pool.cancel_query($kill(b)).await;
}
let _ = reply.send(Err(IdeError::cancelled()));
break;
@@ -236,13 +250,13 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
}
Err(e) => {
let _ = reply.send(Err(e));
reusable = true;
reusable = !owned;
break;
}
}
}
drop(stream);
if let Some((reply, mut fetched)) = last {
if let Some((_, fetched)) = &mut last {
if fetched.0.is_empty() && looks_like_query(&sql) {
fetched.0 = (&mut **$conn)
.prepare(sqlx::AssertSqlSafe(sql.clone()).into_sql_str())
@@ -250,12 +264,11 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
.map(|s| statement_columns(&s))
.unwrap_or_default();
}
let _ = reply.send(Ok(fetched));
}
reusable
(reusable, last)
}};
}
let reusable = match &mut held {
let (reusable, last) = match &mut held {
Held::Sqlite(c) => serve!(c, None::<&str>, |_: String| String::new()),
Held::Postgres(c) => {
serve!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
@@ -263,7 +276,9 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
Held::Mysql(c) => serve!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
_ => unreachable!("only the sqlx drivers keep cursors"),
};
if !reusable {
if let Some((reply, fetched)) = last {
let _ = reply.send(held.finish_read_only(owned, Ok(fetched)).await);
} else if !reusable {
held.discard().await;
}
}
@@ -452,7 +467,7 @@ mod tests {
});
let resumed = tokio::spawn({
let (cursors, key) = (cursors.clone(), key.clone());
async move { cursors.resume(&key, 1, 1, &CancellationToken::new()).await.is_some() }
async move { cursors.resume(&key, 1, 1, &CancellationToken::new(), false).await.is_some() }
});
in_read.notified().await;
cursors.release(&key);
+248
Переглянути файл
@@ -0,0 +1,248 @@
//! PostgreSQL transaction-pool connections whose endpoint rejects the read-only startup option.
use super::{Context, Held, PgConnection, PgHandle, PgReadOnly, db_err};
use ide_core::{IdeError, IdeResult};
use sqlx::{Executor, SqlSafeStr};
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
fn leading_word<'a>(input: &mut &'a str) -> &'a str {
loop {
*input = input.trim_start_matches([' ', '\t', '\r', '\n', '\x0c', '\x0b', ';']);
if let Some(comment) = input.strip_prefix("--") {
*input = &comment[comment.find(['\r', '\n']).unwrap_or(comment.len())..];
} else if let Some(mut comment) = input.strip_prefix("/*") {
let mut depth = 1usize;
while depth > 0 {
let Some(at) = comment.find(['/', '*']) else { return "" };
comment = &comment[at..];
if let Some(rest) = comment.strip_prefix("/*") {
depth += 1;
comment = rest;
} else if let Some(rest) = comment.strip_prefix("*/") {
depth -= 1;
comment = rest;
} else {
comment = &comment[1..];
}
}
*input = comment;
} else {
let end = input.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$')).unwrap_or(input.len());
let (word, rest) = input.split_at(end);
*input = rest;
return word;
}
}
}
fn control(mut sql: &str) -> Option<&'static str> {
let first = leading_word(&mut sql);
for name in ["BEGIN", "COMMIT", "END", "ROLLBACK", "ABORT"] {
if first.eq_ignore_ascii_case(name) {
return Some(name);
}
}
let second = leading_word(&mut sql);
if second.eq_ignore_ascii_case("TRANSACTION") {
return [("START", "START TRANSACTION"), ("PREPARE", "PREPARE TRANSACTION"), ("SET", "SET TRANSACTION")]
.into_iter()
.find_map(|(verb, name)| first.eq_ignore_ascii_case(verb).then_some(name));
}
(first.eq_ignore_ascii_case("SET")
&& second.eq_ignore_ascii_case("SESSION")
&& leading_word(&mut sql).eq_ignore_ascii_case("CHARACTERISTICS"))
.then_some("SET SESSION CHARACTERISTICS")
}
pub(crate) fn validate(sql: &str) -> Result<(), String> {
if sql.contains('\0') {
return Err("PostgreSQL statements cannot contain a null byte".into());
}
let blocked = control(sql).or_else(|| {
sql.contains(';')
.then(|| crate::split::split(sql, crate::DbDriver::Postgres))
.and_then(|statements| statements.iter().find_map(|s| control(&s.text)))
});
if let Some(name) = blocked {
return Err(format!("{name} is unavailable while OpenIDEA manages the read-only transaction"));
}
Ok(())
}
/// A startup SET must follow the client to its next backend without changing the next client's session.
pub(super) fn startup(statements: &[String]) -> Result<(Vec<String>, Vec<String>), String> {
let mut init = Vec::with_capacity(statements.len());
let mut settings = Vec::new();
for sql in statements {
validate(sql)?;
let mut rest = sql.as_str();
let verb = leading_word(&mut rest);
if verb.eq_ignore_ascii_case("RESET") || verb.eq_ignore_ascii_case("DISCARD") {
return Err(format!("{verb} in a startup script cannot be preserved across pooled read-only transactions"));
}
if verb.eq_ignore_ascii_case("SET") {
let after_set = rest;
let kind = leading_word(&mut rest);
if !kind.eq_ignore_ascii_case("LOCAL") && !kind.eq_ignore_ascii_case("CONSTRAINTS") {
let mut after_session = rest;
let local = if kind.eq_ignore_ascii_case("SESSION")
&& !leading_word(&mut after_session).eq_ignore_ascii_case("AUTHORIZATION")
{
rest
} else {
after_set
};
let sql = format!("SET LOCAL {local}");
settings.push(sql.clone());
init.push(sql);
continue;
}
}
init.push(sql.clone());
}
Ok((init, settings))
}
// Keep the text result format of raw_sql. For SQL containing a delimiter, PostgreSQL's Parse
// validates that the text denotes a single command, including under the server's quoting rules.
pub(super) async fn check_single(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
if sql.contains(';') {
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
}
Ok(())
}
impl PgHandle {
pub(super) async fn start_read_only(&mut self) -> IdeResult<()> {
self.in_transaction = true;
let result = async {
sqlx::raw_sql(BEGIN).execute(&mut **self).await.map_err(db_err)?;
let settings = self.options.local_settings.clone();
for sql in settings.iter() {
check_single(self, sql).await.map_err(db_err)?;
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut **self).await.map_err(db_err)?;
}
self.apply_local_path().await
}
.await;
if result.is_err() {
self.conn.take();
}
result
}
async fn apply_local_path(&mut self) -> IdeResult<()> {
if let Some(path) = &self.context.current {
let path = path.clone();
sqlx::query("SELECT pg_catalog.set_config('search_path', $1, true)")
.bind(path)
.execute(&mut **self)
.await
.map_err(db_err)?;
}
Ok(())
}
pub(super) async fn select_path(&mut self, wanted: Option<String>) -> IdeResult<()> {
if !self.context.known || self.context.current != wanted {
self.context.current = wanted;
if self.in_transaction {
self.apply_local_path().await?;
}
self.context.known = true;
}
Ok(())
}
}
impl Held {
pub(super) fn require_read_only_transaction(&self) -> IdeResult<()> {
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction && (!c.in_transaction || c.conn.is_none()))
{
return Err(IdeError::internal("PostgreSQL read-only transaction has not started"));
}
Ok(())
}
fn guarded_postgres(&mut self) -> Option<&mut PgHandle> {
match self {
Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction => Some(c),
_ => None,
}
}
/// Returns true when this operation owns the transaction and must finish it.
pub(super) async fn begin_read_only(&mut self) -> IdeResult<bool> {
if let Some(c) = self.guarded_postgres()
&& !c.in_transaction
{
c.start_read_only().await?;
return Ok(true);
}
Ok(false)
}
pub(super) async fn check_protected_statement(&mut self, sql: &str) -> IdeResult<()> {
self.require_read_only_transaction()?;
if let Some(c) = self.guarded_postgres() {
validate(sql).map_err(IdeError::invalid)?;
check_single(c, sql).await.map_err(db_err)?;
}
Ok(())
}
pub(super) async fn end_read_only(&mut self, commit: bool) -> IdeResult<()> {
if let Some(c) = self.guarded_postgres() {
if c.conn.is_none() {
return Err(IdeError::invalid("The read-only PostgreSQL transaction lost its connection"));
}
let end = if commit { "COMMIT" } else { "ROLLBACK" };
if let Err(error) = sqlx::raw_sql(end).execute(&mut **c).await {
c.conn.take();
return Err(db_err(error));
}
c.in_transaction = false;
c.context = Context::new(c.context.default.clone());
}
Ok(())
}
pub(super) async fn finish_read_only<T>(&mut self, owned: bool, result: IdeResult<T>) -> IdeResult<T> {
if owned && let Err(error) = self.end_read_only(result.is_ok()).await {
return Err(result.err().unwrap_or(error));
}
result
}
}
#[cfg(test)]
mod tests {
use super::validate;
#[test]
fn names_transaction_control_and_accepts_quoted_text() {
for name in [
"BEGIN",
"COMMIT",
"END",
"ROLLBACK",
"ABORT",
"START TRANSACTION",
"PREPARE TRANSACTION",
"SET TRANSACTION",
"SET SESSION CHARACTERISTICS",
] {
let statement = name.to_lowercase().replace(' ', " /* note */ ");
let sql = format!(" -- preceding comment\n /* outer /* nested */ block */ {statement}");
assert!(validate(&sql).unwrap_err().contains(name), "{sql}");
}
assert!(validate("SELECT 1; COMMIT").unwrap_err().contains("COMMIT"));
for sql in
["SELECT 'a; COMMIT'", "SELECT $$;ROLLBACK$$", "SELECT 1 /* END */", "SET LOCAL search_path TO public"]
{
assert!(validate(sql).is_ok(), "{sql}");
}
}
}
+99 -12
Переглянути файл
@@ -178,6 +178,18 @@ pub struct TableDetails {
pub triggers: Vec<TriggerInfo>,
}
/// One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted
/// by `grantor` (unknown on MySQL), and may grant it on when `grantable`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTableGrant")]
pub struct TableGrant {
pub grantee: String,
pub grantor: Option<String>,
pub privilege: String,
pub grantable: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbCompletionColumn")]
@@ -394,7 +406,7 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
async fn end_session(session: &Session) {
let held = session.lock().await.take();
if let Some(mut conn) = held
&& (conn.command("ROLLBACK").await.is_err() || conn.restore_default().await.is_err())
&& (conn.finish_manual(false).await.is_err() || conn.restore_default().await.is_err())
{
conn.discard().await;
}
@@ -658,8 +670,7 @@ impl DbManager {
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
self.ssh.set_secret(&c, secret, save);
return Ok(());
return self.ssh.set_secret(&c, secret, save);
}
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
}
@@ -760,7 +771,9 @@ impl DbManager {
} else {
if let Some(s) = ssh_secret {
let save = self.ssh.config(config)?.save_secret;
self.ssh.set_secret(config, Some(s), save);
if let Err(e) = self.ssh.set_secret(config, Some(s), save) {
tracing::warn!("could not save the SSH credential: {}", e.message);
}
}
self.ssh.session(config).await?
})
@@ -836,11 +849,18 @@ impl DbManager {
_ => pool.rows(version, 1).await,
};
pool.close().await;
let strict =
source.external_tunnel.is_some() || matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let strict = pool.transaction_read_only()
|| source.external_tunnel.is_some()
|| matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let rows = if strict { result? } else { result.unwrap_or_default() };
let v = rows.into_iter().next().and_then(|r| r.into_iter().next().flatten());
Ok(v.unwrap_or_else(|| "Connected".into()))
let mut message = v.unwrap_or_else(|| "Connected".into());
if pool.transaction_read_only() {
message.push_str(
"\nRead-only queries use BEGIN READ ONLY because this endpoint rejected the startup setting.",
);
}
Ok(message)
}
/// Runs `job` with the client tool at `executable` against target `id`, connected like the
@@ -1156,6 +1176,28 @@ impl DbManager {
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
}
/// The object privileges granted on `table`; empty, without a query, on the engines
/// [`sql::table_grants`] doesn't cover.
pub async fn table_grants(&self, id: &str, schema: &str, table: &str) -> IdeResult<Vec<TableGrant>> {
let pool = self.pool(id).await?;
let Some(q) = sql::table_grants(pool.driver(), schema, table) else {
return Ok(Vec::new());
};
Ok(pool
.rows(&q, MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
let grantee = it.next().flatten()?;
let grantor = it.next().flatten().filter(|g| !g.is_empty());
let privilege = it.next().flatten()?.to_ascii_uppercase();
let grantable = flag(&it.next().flatten());
Some(TableGrant { grantee, grantor, privilege, grantable })
})
.collect())
}
/// The routines and sequences of `schema`.
pub async fn schema_objects(&self, id: &str, schema: &str) -> IdeResult<SchemaObjects> {
let pool = self.pool(id).await?;
@@ -1454,6 +1496,22 @@ impl DbManager {
self.execute_from(id, statement, 0, max_rows, cancel, None).await
}
/// Refuses transaction control anywhere in a guarded console script before running its first statement.
pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> {
if statements.len() > 1
&& self.source(id).is_ok_and(|s| s.driver == DbDriver::Postgres && s.read_only)
&& self.pool(id).await?.transaction_read_only()
{
for statement in statements {
if let Err(error) = conn::validate_pg_read_only(&statement.text) {
self.finish_transaction(id, false).await?;
return Err(IdeError::invalid(error));
}
}
}
Ok(())
}
/// [`execute`](Self::execute), reading past the first `skip` rows without keeping
/// them: a later page of a result, where only that page is decoded and returned.
/// `schema` is a query console's active context: the connection that runs the
@@ -1589,16 +1647,23 @@ impl DbManager {
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
}
let session = self.sessions.lock().get(id).cloned();
if !conn::cursor_statement(statement) {
let protected = pool.transaction_read_only();
let cursor = protected || conn::cursor_statement(statement);
if !cursor || (protected && skip == 0 && paging) {
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
self.cursors.release_target(id);
}
if paging && session.is_none() && skip > 0 && pool.keeps_cursors() && conn::cursor_statement(statement) {
if paging && session.is_none() && (skip > 0 || protected) && pool.keeps_cursors() && cursor {
let key = conn::CursorKey::new(id, statement, schema);
let started = std::time::Instant::now();
let page = match self.cursors.resume(&key, skip, max_rows, cancel).await {
let page = match self.cursors.resume(&key, skip, max_rows, cancel, protected).await {
Some(page) => page,
None => {
if protected && skip > 0 {
return Err(IdeError::invalid(
"This read-only result is no longer open at this page. Run the query again.",
));
}
let mut held = Held::acquire(&pool).await?;
held.apply_context(schema).await?;
self.cursors.start(held, pool.clone(), key, skip, max_rows, cancel).await
@@ -1626,10 +1691,32 @@ impl DbManager {
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
}
let mut held = session.lock().await;
if pool.transaction_read_only() {
// Own the session during awaits so a dropped request cannot return an unfinished transaction.
let mut conn = match held.take() {
Some(conn) => conn,
None => {
let mut conn = Held::acquire(&pool).await?;
conn.begin_manual(pool.driver()).await?;
conn
}
};
let result = async {
conn.apply_context(schema).await?;
conn.execute_from(&pool, statement, skip, max_rows, cancel).await
}
.await;
if result.is_ok() {
*held = Some(conn);
} else if cancel.is_cancelled() || conn.finish_manual(false).await.is_err() {
conn.discard().await;
}
return result;
}
if held.is_none() {
let mut conn = Held::acquire(&pool).await?;
conn.apply_context(schema).await?;
conn.command(conn::begin_statement(pool.driver())).await?;
conn.begin_manual(pool.driver()).await?;
*held = Some(conn);
}
let conn = held.as_mut().expect("opened above");
@@ -1675,7 +1762,7 @@ impl DbManager {
let Some(session) = session else { return Ok(()) };
let mut held = session.lock().await;
let Some(mut conn) = held.take() else { return Ok(()) };
if let Err(e) = conn.command(if commit { "COMMIT" } else { "ROLLBACK" }).await {
if let Err(e) = conn.finish_manual(commit).await {
// Discarding a Snowflake connection doesn't end its session, which the data source's
// other targets share: the transaction stays open, so it stays held to be ended again.
if matches!(conn, conn::Held::Snowflake(..)) {
+22
Переглянути файл
@@ -673,6 +673,28 @@ pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
}
}
/// `grantee, grantor, privilege, grantable` rows of `table`'s object privileges, for the
/// engines whose catalog keeps them per table: PostgreSQL's ACL (its implicit owner
/// privileges when `relacl` is null) and MySQL's `TABLE_PRIVILEGES` (no grantor). `None`
/// for the other engines, which then run no query.
pub fn table_grants(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
DbDriver::Postgres => Some(format!(
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
pg_get_userbyid(a.grantor), a.privilege_type, CASE WHEN a.is_grantable THEN 'YES' ELSE 'NO' END \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
CROSS JOIN LATERAL aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) a \
WHERE n.nspname = {s} AND c.relname = {t} ORDER BY 1, 2"
)),
DbDriver::Mysql => Some(format!(
"SELECT grantee, NULL, privilege_type, is_grantable FROM information_schema.table_privileges \
WHERE table_schema = {s} AND table_name = {t} ORDER BY 1"
)),
_ => None,
}
}
/// `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();
+36
Переглянути файл
@@ -322,3 +322,39 @@ async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> Id
}
Ok(())
}
#[tokio::test]
async fn table_grants_list_table_privileges() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
let c = CancellationToken::new();
for stmt in [
"DROP DATABASE IF EXISTS oi_grants",
"DROP USER IF EXISTS 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'",
"CREATE USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'",
"CREATE DATABASE oi_grants",
"CREATE TABLE oi_grants.shared (id INT)",
"CREATE TABLE oi_grants.private (id INT)",
"GRANT SELECT ON oi_grants.shared TO 'oi_grant_reader'@'%'",
"GRANT INSERT, UPDATE ON oi_grants.shared TO 'oi_grant_writer'@'%' WITH GRANT OPTION",
] {
db.execute("m", stmt, 10, &c).await?;
}
let grants = db.table_grants("m", "oi_grants", "shared").await?;
let mut rows: Vec<_> =
grants.iter().map(|g| (g.grantee.as_str(), g.privilege.as_str(), g.grantable, g.grantor.clone())).collect();
rows.sort();
assert_eq!(
rows,
[
("'oi_grant_reader'@'%'", "SELECT", false, None),
("'oi_grant_writer'@'%'", "INSERT", true, None),
("'oi_grant_writer'@'%'", "UPDATE", true, None),
]
);
assert!(db.table_grants("m", "oi_grants", "private").await?.is_empty());
for stmt in ["DROP DATABASE oi_grants", "DROP USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'"] {
db.execute("m", stmt, 10, &c).await?;
}
Ok(())
}
+208 -1
Переглянути файл
@@ -5,11 +5,174 @@ use ide_core::{CancellationToken, IdeResult};
use ide_db::{DataSource, DbDriver, DbManager};
fn server() -> Option<(String, u16, String, String)> {
let v = std::env::var("OPENIDEA_TEST_POSTGRES").ok()?;
endpoint("OPENIDEA_TEST_POSTGRES")
}
fn endpoint(variable: &str) -> Option<(String, u16, String, String)> {
let v = std::env::var(variable).ok()?;
let mut it = v.splitn(4, ':');
Some((it.next()?.into(), it.next()?.parse().ok()?, it.next()?.into(), it.next().unwrap_or("").into()))
}
/// A disposable PgBouncer transaction pool which rejects default_transaction_read_only at startup
/// (`OPENIDEA_TEST_PGBOUNCER`, same format). PgBouncer 1.24 rejects it; 1.26 tracks it per client,
/// which keeps the startup option in use and fails the fallback assertion below.
#[tokio::test]
async fn transaction_pooler_runs_read_only_work_on_the_assigned_backend() -> IdeResult<()> {
let Some((host, port, user, password)) = endpoint("OPENIDEA_TEST_PGBOUNCER") else { return Ok(()) };
let dir = tempfile::tempdir()?;
let root = dir.path();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
let mut source = DataSource {
id: "ro".into(),
name: "Pooler".into(),
driver: DbDriver::Postgres,
host,
port: Some(port),
user,
read_only: true,
..Default::default()
};
let normal = DataSource { id: "rw".into(), read_only: false, ..source.clone() };
source.options.startup_script =
"SET search_path = pg_catalog, public; SET statement_timeout = '17s'; SELECT 1".into();
db.save_sources(vec![source.clone(), normal]).await?;
for id in ["rw", "ro"] {
db.set_password(id, Some(password.clone()), false).await?;
}
let message = db.test(&source, Some(password.clone()), None).await?;
assert!(message.contains("PostgreSQL") && message.contains("BEGIN READ ONLY"), "{message}");
let c = CancellationToken::new();
let table = format!("public.oi_pooler_{}", uuid::Uuid::new_v4().simple());
let write = format!("INSERT INTO {table} VALUES (1)");
pooler_modes(&db, &table, &write, &c).await?;
pooler_rotation(&db, &c).await?;
pooler_manual(&db, &write, &c).await?;
pooler_paging(&db, &c).await?;
pooler_cancellation(&db, &c).await?;
source.options.time_zone = "Europe/Paris".into();
source.options.startup_script = "SELECT 'read;only'".into();
let configured = ide_db::Pool::connect(&source, Some(&password), None).await?;
assert_eq!(configured.rows("SHOW TimeZone", 1).await?, [[Some("Europe/Paris".into())]]);
configured.close().await;
source.options.startup_script = "SELECT 1/0; COMMIT".into();
let error = db.test(&source, Some(password), None).await.unwrap_err();
assert!(error.message.contains("COMMIT"), "{}", error.message);
db.execute("rw", &format!("DROP TABLE {table}"), 1, &c).await?;
Ok(())
}
async fn pooler_modes(db: &DbManager, table: &str, write: &str, c: &CancellationToken) -> IdeResult<()> {
let mode = "SHOW transaction_read_only";
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
assert_eq!(db.execute("rw", mode, 1, c).await?.rows, [[Some("off".into())]]);
db.execute("rw", &format!("CREATE TABLE {table} (n int)"), 1, c).await?;
assert!(db.execute("ro", write, 1, c).await.unwrap_err().message.contains("25006"));
assert_eq!(db.pool("ro").await?.rows(mode, 1).await?, [[Some("on".into())]]);
Ok(())
}
async fn pooler_rotation(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
let status = "SELECT pg_backend_pid(), current_setting('transaction_read_only'), current_setting('search_path'), current_setting('statement_timeout')";
let pool = db.pool("ro").await?;
let mut client = ide_db::Held::acquire(&pool).await?;
let first_pid = client.execute(&pool, status, 1, c).await?.rows[0][0].clone();
let writable = db.pool("rw").await?;
let mut blockers = Vec::new();
let mut previous_backend = loop {
let mut other = ide_db::Held::acquire(&writable).await?;
other.command("BEGIN").await?;
let pid = other.execute(&writable, status, 1, c).await?.rows[0][0].clone();
if pid == first_pid {
break other;
}
blockers.push(other);
assert!(blockers.len() < 4, "the fixture must offer the original backend");
};
for mut other in blockers {
other.command("ROLLBACK").await?;
}
let rerouted = client.execute(&pool, status, 1, c).await?;
assert_ne!(rerouted.rows[0][0], first_pid);
assert_eq!(rerouted.rows[0][1..], [Some("on".into()), Some("pg_catalog, public".into()), Some("17s".into())]);
let ordinary = previous_backend.execute(&writable, status, 1, c).await?;
assert_ne!(ordinary.rows[0][2].as_deref(), Some("pg_catalog, public"));
assert_ne!(ordinary.rows[0][3].as_deref(), Some("17s"));
previous_backend.command("ROLLBACK").await?;
drop(client);
Ok(())
}
async fn pooler_manual(db: &DbManager, write: &str, c: &CancellationToken) -> IdeResult<()> {
let mode = "SHOW transaction_read_only";
db.set_manual_commit("ro", true).await?;
for commit in [true, false] {
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
db.finish_transaction("ro", commit).await?;
}
db.execute("ro", write, 1, c).await.unwrap_err();
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
let timestamp = "SELECT transaction_timestamp()";
for batch in [false, true] {
let before = db.execute("ro", timestamp, 1, c).await?.rows;
let error = if batch {
let script = ide_db::split::split("SELECT 1/0; COMMIT", DbDriver::Postgres);
db.validate_script("ro", &script).await.unwrap_err()
} else {
db.execute("ro", "COMMIT", 1, c).await.unwrap_err()
};
assert!(error.message.contains("COMMIT"), "{}", error.message);
assert_ne!(db.execute("ro", timestamp, 1, c).await?.rows, before);
}
db.set_manual_commit("ro", false).await?;
Ok(())
}
async fn pooler_paging(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
let query = "SELECT current_setting('transaction_read_only'), pg_backend_pid(), transaction_timestamp(), n FROM generate_series(1, 12) n";
let first = db.execute_from("ro", query, 0, 2, c, None).await?;
let page = db.execute_from("ro", query, 2, 2, c, None).await?;
let next = db.execute_from("ro", query, 4, 2, c, None).await?;
assert_eq!(page.rows[0][0].as_deref(), Some("on"));
assert_eq!(page.rows[0][..3], first.rows[0][..3]);
assert_eq!(next.rows[0][..3], page.rows[0][..3]);
assert_eq!(next.rows[0][3].as_deref(), Some("5"));
db.release_result("ro", query, None);
let expired = db.execute_from("ro", query, 6, 2, c, None).await.unwrap_err();
assert!(expired.message.contains("Run the query again"), "{}", expired.message);
let chosen = db.execute_from("ro", "SELECT current_schema()", 0, 1, c, Some("public")).await?;
assert_eq!(chosen.rows, [[Some("public".into())]]);
assert_eq!(db.execute("ro", "SELECT current_schema()", 1, c).await?.rows, [[Some("pg_catalog".into())]]);
Ok(())
}
async fn pooler_cancellation(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
let writable = db.pool("rw").await?;
let mode = "SHOW transaction_read_only";
let stop = CancellationToken::new();
let slow = "SELECT pg_sleep(10) AS oi_pooler_cancel";
let (outcome, observed) = tokio::join!(db.execute("ro", slow, 1, &stop), async {
for _ in 0..40 {
let live = writable.rows("SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND query = 'SELECT pg_sleep(10) AS oi_pooler_cancel'", 1).await.unwrap();
if live[0][0].as_deref() == Some("1") {
stop.cancel();
return true;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
stop.cancel();
false
});
assert!(observed, "the slow statement reached PostgreSQL before cancellation");
assert_eq!(outcome.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
let active = writable.rows("SELECT count(*) FROM pg_stat_activity WHERE state <> 'idle' AND query = 'SELECT pg_sleep(10) AS oi_pooler_cancel'", 1).await?;
assert_eq!(active, [[Some("0".into())]]);
Ok(())
}
async fn manager(tmp: &tempfile::TempDir) -> Option<DbManager> {
let (host, port, user, password) = server()?;
let root = tmp.path().to_path_buf();
@@ -572,3 +735,47 @@ async fn external_startup_does_not_block_another_source_and_disconnect_cancels_i
assert!(matches!(result, Err(error) if error.kind == ide_core::error::ErrorKind::Cancelled));
Ok(())
}
#[tokio::test]
async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
for stmt in [
"DROP SCHEMA IF EXISTS oi_grants CASCADE",
"DROP ROLE IF EXISTS oi_grant_reader",
"DROP ROLE IF EXISTS oi_grant_writer",
"CREATE ROLE oi_grant_reader",
"CREATE ROLE oi_grant_writer",
"CREATE SCHEMA oi_grants",
"CREATE TABLE oi_grants.shared (id INT)",
"CREATE TABLE oi_grants.private (id INT)",
"GRANT SELECT ON oi_grants.shared TO oi_grant_reader, PUBLIC",
"GRANT INSERT, UPDATE ON oi_grants.shared TO oi_grant_writer WITH GRANT OPTION",
] {
db.execute("p", stmt, 10, &c).await?;
}
let owner = db.execute("p", "SELECT current_user", 1, &c).await?.rows[0][0].clone().unwrap();
let grants = db.table_grants("p", "oi_grants", "shared").await?;
let of = |grantee: &str| {
let mut v: Vec<_> = grants
.iter()
.filter(|g| g.grantee == grantee)
.map(|g| (g.privilege.as_str(), g.grantable, g.grantor.as_deref() == Some(owner.as_str())))
.collect();
v.sort();
v
};
assert_eq!(of("oi_grant_reader"), [("SELECT", false, true)], "{grants:?}");
assert_eq!(of("PUBLIC"), [("SELECT", false, true)], "{grants:?}");
assert_eq!(of("oi_grant_writer"), [("INSERT", true, true), ("UPDATE", true, true)], "{grants:?}");
assert!(of(&owner).contains(&("TRUNCATE", false, true)), "{grants:?}");
// No ACL yet: the owner's implicit privileges.
let private = db.table_grants("p", "oi_grants", "private").await?;
assert!(private.iter().all(|g| g.grantee == owner), "{private:?}");
assert!(private.iter().any(|g| g.privilege == "SELECT"), "{private:?}");
for stmt in ["DROP SCHEMA oi_grants CASCADE", "DROP ROLE oi_grant_reader", "DROP ROLE oi_grant_writer"] {
db.execute("p", stmt, 10, &c).await?;
}
Ok(())
}
+1 -1
Переглянути файл
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.16.0";
pub const ENGINE_VERSION: &str = "1.17.0";
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
pub const LEGACY_API: &str = "0.1";
/// Marketplace categories, in the order they are shown.
+70 -3
Переглянути файл
@@ -283,6 +283,47 @@ fn minimal_edits(text: &str, edits: Vec<TextEdit>) -> Vec<TextEdit> {
.collect()
}
/// The edits on the lines of `range`. Some servers (Intelephense, #6055) answer a range request
/// with edits across the whole file; Reformat Code with a selection changes only the selected
/// lines. An edit that reaches past them and keeps its line count is split into one per line.
fn within_lines(text: &str, edits: Vec<TextEdit>, range: Range) -> Vec<TextEdit> {
let from = Pos::new(range.start.line, 0);
// A selection ending at a line start leaves that line out.
let to = if range.end.col == 0 && range.end.line > range.start.line {
range.end
} else {
Pos::new(range.end.line + 1, 0)
};
let doc = ide_text::Document::new(text);
edits
.into_iter()
.flat_map(|e| if e.range.start >= from && e.range.end <= to { vec![e] } else { per_line(&doc, e) })
.filter(|e| e.range.start >= from && e.range.end <= to)
.collect()
}
/// `edit` as one edit per line when it replaces as many lines as it inserts, else nothing.
fn per_line(doc: &ide_text::Document, edit: TextEdit) -> Vec<TextEdit> {
let Range { start, end } = edit.range;
let lines: Vec<&str> = edit.new_text.split('\n').collect();
if lines.len() as u32 != end.line - start.line + 1 {
return Vec::new();
}
let width = |line: u32| doc.line(line).map_or(0, |l| l.encode_utf16().count() as u32);
lines
.into_iter()
.zip(start.line..=end.line)
.map(|(new_text, line)| TextEdit {
range: Range::new(
Pos::new(line, if line == start.line { start.col } else { 0 }),
Pos::new(line, if line == end.line { end.col } else { width(line) }),
),
new_text: new_text.to_owned(),
})
.filter(|e| doc.slice(doc.pos_to_offset(e.range.start), doc.pos_to_offset(e.range.end)) != e.new_text)
.collect()
}
pub async fn format(
host: &Host,
window: &str,
@@ -514,9 +555,15 @@ async fn provider_edits(
None => project.lsp.format_text(&snap.path, &snap.language, &snap.text, options).await?,
};
let text = snap.text;
return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits)))
.await
.map_err(|e| IdeError::internal(e.to_string()));
return tokio::task::spawn_blocking(move || {
let edits = minimal_edits(&text, edits);
Some(match range {
Some(range) => within_lines(&text, edits, range),
None => edits,
})
})
.await
.map_err(|e| IdeError::internal(e.to_string()));
};
let tool_settings = settings.languages.formatter(selected);
// Black takes over from the language server in its projects, so Format on save runs it too.
@@ -1050,6 +1097,26 @@ mod tests {
const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
#[test]
fn range_formatting_changes_only_the_selected_lines() {
// Intelephense answers a range request for lines 2-3 with edits across the file (#6055).
let text = "<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n";
let formatted = "<?php\nf('a');\n$x = 1;\n$y = 2;\nf('b');\n";
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
let edits = minimal_edits(text, whole);
let selected = Range::new(Pos::new(2, 0), Pos::new(3, 8));
assert_eq!(
after(text, &within_lines(text, edits.clone(), selected)),
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
);
// Selected up to the start of line 4: line 4 stays as it is.
let to_line_start = Range::new(Pos::new(2, 3), Pos::new(3, 0));
assert_eq!(
after(text, &within_lines(text, edits, to_line_start)),
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
);
}
#[test]
fn a_whole_file_edit_becomes_one_edit_per_changed_region() {
let text = "a\n b\nc\nd\n e\n";
+115 -48
Переглянути файл
@@ -118,6 +118,8 @@ pub struct Host {
pub(crate) heap_windows: Mutex<HashMap<ide_heap::HeapSnapshotId, String>>,
pub(crate) heap_requests: ops::heap::HeapRequests,
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
/// The IDE's Java build: resident javac processes shared by every window's launches.
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
/// SSH connections of Settings › SSH Configurations.
pub ssh: Arc<ide_ssh::SshManager>,
/// SFTP deployment, remote file editing and runs on run targets.
@@ -144,11 +146,31 @@ pub struct Host {
requests: requests::Requests,
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
/// Shutdowns of projects closed with [`Host::close_project_detached`].
closing: parking_lot::Mutex<Vec<std::thread::JoinHandle<()>>>,
closing: parking_lot::Mutex<Vec<DetachedClose>>,
/// One open at a time per window (see [`Host::opening`]).
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
}
struct DetachedClose {
root: Option<std::path::PathBuf>,
handle: std::thread::JoinHandle<()>,
}
struct ShutdownWork {
notebooks: Vec<Arc<notebook::NotebookService>>,
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
lsp: Option<Arc<ide_lsp::LspManager>>,
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
agents: Vec<Arc<ide_agent::AgentManager>>,
terminals: Option<ide_terminal::DetachedTerminals>,
processes: Option<ide_run::DetachedProcessKills>,
retired: Option<Arc<Project>>,
}
fn roots_overlap(a: &std::path::Path, b: &std::path::Path) -> bool {
a == b || a.starts_with(b) || b.starts_with(a)
}
/// How long exit waits for project shutdown before giving up.
const EXIT_SHUTDOWN_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
@@ -190,6 +212,8 @@ impl Host {
let sink_for: SinkFactory = diagnostics_store::recording_sink_factory(diagnostics.clone(), sink_for);
let global_settings = SettingsStore::load(&config_dir, None);
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
let migration = ssh.clone();
runtime.spawn_blocking(move || migration.start_password_migration());
ssh.set_configs(global_settings.effective().ssh.configs);
let host = Self {
plugin_host: RwLock::default(),
@@ -225,6 +249,7 @@ impl Host {
heap_windows: Mutex::default(),
heap_requests: Default::default(),
rebase_editors: Default::default(),
java_build: Default::default(),
languages,
syntax,
config_dir,
@@ -331,7 +356,7 @@ impl Host {
/// [`Self::close_project_detached`] there.
pub fn close_project(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
self.wait_blocking(shutdown);
self.wait_blocking(shutdown.handle);
}
}
@@ -341,15 +366,15 @@ impl Host {
pub fn close_project_detached(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
let mut closing = self.closing.lock();
closing.retain(|handle| !handle.is_finished());
closing.retain(|entry| !entry.handle.is_finished());
closing.push(shutdown);
}
}
/// Detaches the project from `window` and stops what it started, synchronously,
/// so the window can open another project at once. Returns the thread that
/// finishes shutting down its workers.
fn begin_close(&self, window: &str) -> Option<std::thread::JoinHandle<()>> {
/// Detaches the project from `window` synchronously so the caller (including the UI
/// event-loop thread) never blocks on disk I/O or process shutdown, and returns the
/// background handle that stops its workers, agents, terminals and processes.
fn begin_close(&self, window: &str) -> Option<DetachedClose> {
self.mcp_reports.forget_window(window);
self.mcp_requests.forget_window(window);
self.mcp_agent_runs.forget_window(window);
@@ -396,78 +421,115 @@ impl Host {
phpstan.stop();
}
project.documents.clear_workspace_edit_history();
project.agents.shutdown();
project.agents.detach_sinks();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
project.notebooks.stop_admission();
// What the closing window started goes with it — the builds and searches it
// asked for, its runs, its shells and its debug sessions — and its language
// servers shut down.
self.processes.kill_project(&project.root);
self.terminals.kill_key(self.owner_window(window));
Some(self.spawn_project_shutdown(
vec![project.notebooks.clone()],
project.kotlin_bridge.iter().cloned().collect(),
Some(project.lsp.clone()),
// Detach runs and terminals synchronously so a new project opened in the same window
// never collides with them, then terminate them and shut down agents on the background thread.
let processes = self.processes.detach_project_kills(&project.root);
let terminals = self.terminals.detach_key(self.owner_window(window));
let root = (!project.light).then(|| project.root.clone());
let handle = self.spawn_project_shutdown(ShutdownWork {
notebooks: vec![project.notebooks.clone()],
bridges: project.kotlin_bridge.iter().cloned().collect(),
lsp: Some(project.lsp.clone()),
// Debug sessions under the root belong to windows: a project served without one starts none.
Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
Some(project),
))
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
agents: vec![project.agents.clone()],
terminals: Some(terminals),
processes: Some(processes),
retired: Some(project),
});
Some(DetachedClose { root, handle })
}
/// Project/window destruction must finish owned kernel cleanup, not enqueue
/// Project/window destruction must finish owned kernel and agent cleanup, not enqueue
/// work which can be lost as the desktop runtime exits: the returned thread is
/// joined by the closer or, for a detached close, before exit.
fn spawn_project_shutdown(
&self,
notebooks: Vec<Arc<notebook::NotebookService>>,
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
lsp: Option<Arc<ide_lsp::LspManager>>,
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
retired: Option<Arc<Project>>,
) -> std::thread::JoinHandle<()> {
for bridge in &bridges {
fn spawn_project_shutdown(&self, work: ShutdownWork) -> std::thread::JoinHandle<()> {
for bridge in &work.bridges {
bridge.stop();
}
for service in &notebooks {
for service in &work.notebooks {
service.stop_admission();
}
let runtime = self.runtime.clone();
std::thread::spawn(move || {
if let Some(processes) = work.processes {
processes.kill();
}
if let Some(terminals) = work.terminals {
terminals.terminate();
}
let agents = (!work.agents.is_empty()).then(|| {
let agents = work.agents;
std::thread::spawn(move || {
for manager in agents {
manager.shutdown();
}
})
});
// Dropping the project stops its file watcher and index worker, which first finish the
// batch they are applying (many file events while a build writes its output), so it
// isn't done on the closing caller's thread (the UI thread for a window close).
let retired = retired.map(|project| std::thread::spawn(move || drop(project)));
let retired = work.retired.map(|project| std::thread::spawn(move || drop(project)));
runtime.block_on(async move {
for bridge in bridges {
for bridge in work.bridges {
bridge.shutdown().await;
}
for service in notebooks {
for service in work.notebooks {
service.shutdown().await;
}
if let Some(lsp) = lsp {
if let Some(lsp) = work.lsp {
lsp.shutdown_all().await;
}
if let Some((debug, key, root)) = debug {
if let Some((debug, key, root)) = work.debug {
debug.stop_key(&key).await;
if let Some(root) = root {
debug.stop_under(&root).await;
}
}
});
if let Some(agents) = agents {
let _ = agents.join();
}
if let Some(retired) = retired {
let _ = retired.join();
}
})
}
/// Waits for detached closes, so a project opened next never races the
/// language servers of one still shutting down (e.g. over a shared workspace).
/// Waits for every detached close to finish.
#[cfg(test)]
pub(crate) fn wait_detached_closes(&self) {
let pending: Vec<_> = self.closing.lock().drain(..).collect();
for shutdown in pending {
self.wait_blocking(shutdown);
self.wait_blocking(shutdown.handle);
}
}
/// Waits only for detached closes whose root overlaps `root`, so opening an unrelated project
/// never blocks on another project's background shutdown.
pub(crate) fn wait_detached_closes_for(&self, root: &std::path::Path) {
let matching = {
let mut closing = self.closing.lock();
closing.retain(|entry| !entry.handle.is_finished());
let mut wait = Vec::new();
let mut keep = Vec::new();
for entry in closing.drain(..) {
if entry.root.as_deref().is_some_and(|other| roots_overlap(other, root)) {
wait.push(entry.handle);
} else {
keep.push(entry);
}
}
*closing = keep;
wait
};
for handle in matching {
self.wait_blocking(handle);
}
}
@@ -493,18 +555,23 @@ impl Host {
/// Called before the desktop runtime exits, including update/restart exits, on
/// the event-loop thread: waits for detached closes and the open projects'
/// kernels, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
/// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
/// stuck on the event loop cannot keep the process from exiting.
pub fn shutdown_notebooks_on_exit(&self) {
let projects = self.projects();
let mut pending: Vec<_> = self.closing.lock().drain(..).collect();
pending.push(self.spawn_project_shutdown(
projects.iter().map(|project| project.notebooks.clone()).collect(),
projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
None,
None,
None,
));
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
if !projects.is_empty() {
pending.push(self.spawn_project_shutdown(ShutdownWork {
notebooks: projects.iter().map(|project| project.notebooks.clone()).collect(),
bridges: projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
lsp: None,
debug: None,
agents: projects.iter().map(|project| project.agents.clone()).collect(),
terminals: None,
processes: None,
retired: None,
}));
}
let deadline = std::time::Instant::now() + EXIT_SHUTDOWN_WAIT;
while pending.iter().any(|handle| !handle.is_finished()) {
if std::time::Instant::now() >= deadline {
+1
Переглянути файл
@@ -513,6 +513,7 @@ async fn resolve_jvm_application(
call.window(),
std::path::PathBuf::from(&module),
test == Some(true),
false,
policy,
&cancel,
None,
+98 -4
Переглянути файл
@@ -9,6 +9,7 @@ use crate::{Host, Project};
use ide_command::command;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::jbuild::Target;
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::sources;
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
@@ -970,16 +971,44 @@ pub async fn build_run(
host.require_trust(window)?;
let project = host.project(window)?;
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
let file = file.map(|f| ide_core::project_roots::resolve(&root, &f));
let settings = project.settings.effective();
let detected = project.detected_roots.read().clone();
let config_dir = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let launch_project = project.clone();
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
let result = blocking(move || {
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
// A Maven or Gradle project builds with the IDE's Java build (#4078), unless its
// settings ask for the build tool, or it can't.
if single {
let model = with_profiles(load(&root, &cache, &settings), &cache);
let served = match file.as_deref() {
Some(module) => super::java::served_by_service(&root, &model, &settings, module),
None => super::java::project_served_by_service(&model, &settings),
};
if served {
let service = super::java::ServiceBuild {
service: &service,
data_dir: &data_dir,
root: &root,
cache: &cache,
settings: &settings,
model: &model,
};
let target = match file.as_deref() {
Some(file) => Target::Module(file),
None => Target::Project,
};
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
return Ok(result);
}
}
}
// Fast path (#2476): an unchanged single-project Maven build skips
// Maven entirely. Previous diagnostics stay: nothing changed, so they
// are still accurate.
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
if single && kind == BuildKind::Build {
let model = with_profiles(load(&root, &cache, &settings), &cache);
if compile::menu_up_to_date(&cache, &root, &model, file.as_deref(), &token) {
@@ -1102,13 +1131,59 @@ pub async fn build_run(
let outcome = result?;
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
// folders the build wrote are attached. An up-to-date build skips Maven and
// still needs this: the classes can already be on disk.
if outcome.system == ide_build::compile::BuildSystem::Maven {
// still needs this: the classes can already be on disk. The IDE's Java build
// generates them with Maven too.
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
project.lsp.sync_maven_generated_sources(&project.root).await;
}
Ok(outcome)
}
/// A menu build by the IDE's Java build, as the Build window shows it; `None` when Maven builds.
/// Diagnostics of `clear` are cleared once the service builds; its messages are published.
#[allow(clippy::too_many_arguments)]
fn service_build_result(
service: &super::java::ServiceBuild,
target: Target,
kind: BuildKind,
clear: &[std::path::PathBuf],
sink: &ide_core::SharedSink,
token: &CancellationToken,
on_event: &Channel<BuildEvent>,
) -> IdeResult<Option<BuildResult>> {
let started = std::time::Instant::now();
let title = std::sync::Mutex::new(String::new());
let forward = |event: BuildEvent| {
if let BuildEvent::Started { title: t, .. } = &event {
*title.lock().unwrap() = t.clone();
}
let _ = on_event.send(event);
};
let built = service.build(target, kind, token, &forward)?;
let Some(outputs) = built else { return Ok(None) };
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.clone().into(),
source: compile::DIAGNOSTICS_SOURCE.into(),
items: Vec::new(),
});
}
for (path, items) in compile::diagnostics(&outputs.messages) {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
}
let count =
|severity: ide_core::Severity| outputs.messages.iter().filter(|m| m.severity == severity).count() as u32;
Ok(Some(BuildResult {
system: compile::BuildSystem::Javac,
title: title.into_inner().unwrap(),
success: outputs.failure.is_none(),
errors: count(ide_core::Severity::Error),
warnings: count(ide_core::Severity::Warning),
duration_ms: started.elapsed().as_secs_f64() * 1000.0,
messages: outputs.messages,
}))
}
fn plan_compile_file(
root: &Path,
cache: &Path,
@@ -1167,7 +1242,26 @@ pub async fn build_compile_file(
};
let sink = project.sink.clone();
let token = host.begin_project_request(window, request);
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
let result = blocking(move || {
{
let model = with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache);
if super::java::served_by_service(&scope.root, &model, &scope.settings, &file) {
let service = super::java::ServiceBuild {
service: &service,
data_dir: &data_dir,
root: &scope.root,
cache: &scope.cache,
settings: &scope.settings,
model: &model,
};
let target = Target::File(&file);
let kind = BuildKind::Build;
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
return Ok(result);
}
}
}
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.into(),
@@ -1190,7 +1284,7 @@ pub async fn build_compile_file(
.await;
host.end_request(request);
let outcome = result?;
if outcome.system == ide_build::compile::BuildSystem::Maven {
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
project.lsp.sync_maven_generated_sources(&scope_root).await;
}
Ok(outcome)
+16 -1
Переглянути файл
@@ -9,7 +9,7 @@ use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
use ide_db::split::SqlStatement;
use ide_db::{
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode,
QueryResult, SchemaObjects, SortKey, TableDetails, TableInfo, TablePage,
QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -293,6 +293,19 @@ pub async fn db_table_details(
db.table_details(&id, &schema, &table).await
}
#[command(trust = trusted)]
pub async fn db_table_grants(
host: &Host,
window: &str,
id: String,
schema: String,
table: String,
) -> IdeResult<Vec<TableGrant>> {
// Who may read or change `table` (PostgreSQL and MySQL; empty elsewhere).
let db = host.project(window)?.db.clone();
db.table_grants(&id, &schema, &table).await
}
#[command(trust = trusted)]
pub async fn db_ddl(host: &Host, window: &str, id: String, schema: String, table: String) -> IdeResult<String> {
// The DDL of table or view `table` (Go to DDL, Generate DDL).
@@ -481,6 +494,7 @@ async fn execute_statements(
let db = host.project(window)?.db.clone();
let cancel = host.begin_request(request);
let result = async {
db.validate_script(id, &statements).await?;
for (index, statement) in statements.into_iter().enumerate() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -690,6 +704,7 @@ ide_command::domain!(
db_sources,
db_statements,
db_table_details,
db_table_grants,
db_table_page,
db_tables,
db_test,
+126
Переглянути файл
@@ -0,0 +1,126 @@
//! HTTP Client commands shared by the desktop shell's IPC commands and the remote server: a remote
//! window sends its requests from the project host and keeps their history there.
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, IpcPath, Location, RequestId};
use ide_http::{HistoryEntry, HttpExchange};
use std::path::PathBuf;
use super::blocking;
/// The root of the window's project, when one is open.
fn root(host: &Host, window: &str) -> Option<PathBuf> {
host.project(window).ok().map(|p| p.root.clone())
}
/// Environment names from the `http-client(.private).env.json` files that apply to `path`.
#[command(trust = trusted)]
pub async fn http_environments(host: &Host, window: &str, path: Option<IpcPath>) -> IdeResult<Vec<String>> {
let root = root(host, window);
blocking(move || ide_http::environments(path.as_deref(), root.as_deref())).await
}
/// Sends request `index` of `text` (the editor buffer of `path`) and records
/// the exchange in the response history. Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn http_execute(
host: &Host,
window: &str,
request: RequestId,
path: Option<IpcPath>,
text: String,
index: u32,
env: Option<String>,
) -> IdeResult<HttpExchange> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let input = ide_http::RunInput {
text: &text,
index,
file: path.as_deref(),
root: Some(&project.root),
env: env.as_deref(),
};
let result = ide_http::run(input, &cancel).await;
host.end_request(request);
let exchange = result?;
let history = project.http_history.clone();
let saved = exchange.clone();
tokio::task::spawn_blocking(move || {
if let Err(e) = history.add(&saved) {
tracing::warn!("http history: {}", e.message);
}
});
Ok(exchange)
}
#[command(trust = trusted)]
pub fn http_history(host: &Host, window: &str) -> IdeResult<Vec<HistoryEntry>> {
Ok(host.project(window)?.http_history.list())
}
#[command(trust = trusted)]
pub fn http_history_get(host: &Host, window: &str, id: String) -> IdeResult<HttpExchange> {
host.project(window)?.http_history.get(&id)
}
#[command(trust = trusted)]
pub fn http_history_clear(host: &Host, window: &str) -> IdeResult<()> {
host.project(window)?.http_history.clear()
}
/// Convert to cURL and Copy: request `index` of `text` (the editor buffer of `path`), with
/// the variables of `env` substituted, as a cURL command.
#[command(trust = trusted)]
pub async fn http_curl(
host: &Host,
window: &str,
path: Option<IpcPath>,
text: String,
index: u32,
env: Option<String>,
) -> IdeResult<String> {
let root = root(host, window);
blocking(move || {
ide_http::curl(&ide_http::RunInput {
text: &text,
index,
file: path.as_deref(),
root: root.as_deref(),
env: env.as_deref(),
})
})
.await
}
/// The environment file for the request file `path` (`is_private`: the private one): the nearest
/// existing one, else a new one next to it.
#[command(trust = trusted)]
pub async fn http_environment_file(host: &Host, window: &str, path: IpcPath, is_private: bool) -> IdeResult<IpcPath> {
let root = root(host, window);
blocking(move || ide_http::env::environment_file(&path, root.as_deref(), is_private).map(IpcPath::from)).await
}
/// Where `{{name}}` is defined in the environment files that apply to request file `path`
/// (Navigate › Declaration on a variable), private file first.
#[command(trust = trusted)]
pub async fn http_variable_definitions(
host: &Host,
window: &str,
path: IpcPath,
name: String,
) -> IdeResult<Vec<Location>> {
let root = root(host, window);
blocking(move || Ok(ide_http::env::variable_definitions(&path, root.as_deref(), &name))).await
}
ide_command::domain!(
http: http_curl,
http_environment_file,
http_environments,
http_execute,
http_history,
http_history_clear,
http_history_get,
http_variable_definitions,
);
+236 -16
Переглянути файл
@@ -9,6 +9,7 @@ use super::build::{load, with_profiles, workspace};
use cache::LaunchEvents;
use ide_build::BuildModel;
use ide_build::compile::{self, BuildEvent};
use ide_build::jbuild::{Built, JavaBuild, JavaBuildService, LaunchOutputs, Target};
use ide_core::error::ErrorKind;
use ide_core::settings::Settings;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
@@ -22,12 +23,16 @@ use std::path::{Path, PathBuf};
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
/// whose build another launch's build joins receives that build's events.
/// A Maven module is built by the IDE's Java build, except for a `debug` launch the language
/// server serves: java-debug's HotSwap reloads the classes the language server compiles.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn java_resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
test: bool,
debug: bool,
policy: BuildPolicy,
request: RequestId,
on_event: Channel<BuildEvent>,
@@ -39,16 +44,18 @@ pub async fn java_resolve_launch(
let events: LaunchEvents = std::sync::Arc::new(move |event| {
let _ = on_event.send(event);
});
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
let result = resolve_launch(host, window, module, test, debug, policy, &cancel, Some(events)).await;
host.end_request(request);
result
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
test: bool,
debug: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
@@ -73,13 +80,12 @@ pub(crate) async fn resolve_launch(
}
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, is_maven) = {
let (model, external, mut delegated, is_maven, non_java, served) = {
let scope = scope.clone();
let launches = launches.clone();
let module = module.clone();
@@ -89,6 +95,7 @@ pub(crate) async fn resolve_launch(
let model = load_launch_model(&scope);
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
let served = served_by_service(root, &model, &scope.settings, &module);
let delegated = build
&& delegates_to_external_build(
is_maven,
@@ -98,11 +105,65 @@ pub(crate) async fn resolve_launch(
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated, is_maven)
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
};
// A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
// either way.
if served && !non_java && !debug {
let built = {
let (service, data_dir, scope, model, module, cancel, events) = (
host.java_build.clone(),
host.local_data_dir.clone(),
scope.clone(),
model.clone(),
module.clone(),
cancel.clone(),
events.clone(),
);
tokio::task::spawn_blocking(move || {
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let kind = build.then_some(build_kind);
build_with_service(&service, &data_dir, &scope, &model, &module, test, kind, &cancel, &on_event)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
if let Some(outputs) = built {
progress("Resolving the classpath");
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
return tokio::task::spawn_blocking(move || {
// javac's verdict replaces JDT's, as a Maven build's does.
if build {
apply_external_build_result(&mut info, outputs.failure, true);
}
info.class_paths = outputs.class_paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
apply_library_classpath(&mut info, &scope.root, &scope.settings.project_structure.libraries, test);
finish_launch(&mut info, &scope.root, &module, &scope.settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
tracing::info!(
total_ms = started.elapsed().as_millis(),
"Java launch resolved with the IDE's Java build"
);
Ok(info)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
}
}
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let mut external_build =
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
if build && !delegated {
@@ -124,7 +185,6 @@ pub(crate) async fn resolve_launch(
drop_processor_recreate_errors(&mut info);
}
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
} else {
@@ -217,6 +277,104 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Builds the launch of a Maven module with the IDE's Java build (#4078): javac in a resident
/// process with the configuration Maven gives the compiler, into outputs in the project cache
/// that neither the language server nor a terminal `mvn` writes. `None` when the module needs
/// Maven's own build (another compiler, a multi-release jar, a Java module…), which then runs.
/// Without `kind` (no build before launch), the outputs of its last build, if any.
#[allow(clippy::too_many_arguments)]
fn build_with_service(
service: &JavaBuildService,
data_dir: &Path,
scope: &workspace::Scope,
model: &BuildModel,
module: &Path,
test: bool,
kind: Option<compile::BuildKind>,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Option<LaunchOutputs>> {
let service =
ServiceBuild { service, data_dir, root: &scope.root, cache: &scope.cache, settings: &scope.settings, model };
match kind {
Some(kind) => service.build(Target::Launch { module, test }, kind, cancel, on_event),
// No build: the outputs of the last one, when there was one.
None => Ok(service
.with(module, |build| build.recorded_launch(module, test))
.flatten()
.map(|class_paths| LaunchOutputs { class_paths, ..Default::default() })),
}
}
/// A build of the IDE's Java build service in one project (or workspace member).
pub(crate) struct ServiceBuild<'a> {
pub service: &'a JavaBuildService,
pub data_dir: &'a Path,
pub root: &'a Path,
pub cache: &'a Path,
pub settings: &'a Settings,
pub model: &'a BuildModel,
}
impl ServiceBuild<'_> {
/// Runs `f` with the build, its JDKs resolved for `module`; `None` when the build jar
/// can't be installed.
fn with<R>(&self, module: &Path, f: impl FnOnce(&JavaBuild) -> R) -> Option<R> {
let jar = ide_sdk::java::java_build_jar(self.data_dir)?;
let (root, settings) = (self.root, self.settings);
let jdk = |release: Option<u32>| {
ide_sdk::apply::module_jdk(root, module, settings)
.or_else(|| ide_sdk::java::pick_jdk(&ide_sdk::java::installed_jdks(), release).cloned())
.map(|jdk| jdk.home)
};
let version = ide_sdk::java::java_build_version();
let build = JavaBuild {
root,
model: self.model,
cache: self.cache,
jar: &jar,
jar_version: &version,
local_repo: ide_sdk::apply::maven_local_repository(root, settings),
service: self.service,
jdk: &jdk,
};
Some(f(&build))
}
/// Builds `target`; `None` when the build tool has to (the service doesn't build it, or failed).
pub fn build(
&self,
target: Target,
kind: compile::BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Option<LaunchOutputs>> {
let module = match target {
Target::Launch { module, .. } | Target::Module(module) | Target::File(module) => module,
Target::Project => self.root,
};
let Some(built) = self.with(module, |build| build.build(target, kind, cancel, on_event)) else {
return Ok(None);
};
match built {
Ok(Built::Done(outputs)) => Ok(Some(outputs)),
Ok(Built::Unsupported(reason)) => {
tracing::info!(module = %module.display(), reason, "Building with the build tool");
Ok(None)
}
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
Err(e) => {
tracing::warn!(module = %module.display(), "The IDE's Java build failed: {}", e.message);
on_event(BuildEvent::Output {
text: format!("The IDE's Java build failed, so the build tool builds it: {}\n", e.message),
stderr: true,
});
Ok(None)
}
}
}
}
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
}
@@ -225,6 +383,39 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
/// when Settings › Gradle › Build and run using asks for the IDE.
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
// The deepest module holding it; Maven's when both build the folder.
let module = maven
.chain(gradle)
.filter(|(dir, _)| path.starts_with(dir))
.max_by_key(|(dir, maven)| (dir.components().count(), *maven));
match module {
Some((_, true)) => !settings.languages.java.maven.delegate_build,
Some((_, false)) => gradle_served(settings),
None => false,
}
}
/// Whether the IDE's Java build builds the whole project: it has Maven or Gradle builds, and
/// builds them all.
pub(crate) fn project_served_by_service(model: &BuildModel, settings: &Settings) -> bool {
let maven = model.maven.as_ref().map(|_| !settings.languages.java.maven.delegate_build);
let gradle = (!model.gradle.is_empty()).then(|| gradle_served(settings));
match (maven, gradle) {
(None, None) => false,
(maven, gradle) => maven.unwrap_or(true) && gradle.unwrap_or(true),
}
}
fn gradle_served(settings: &Settings) -> bool {
settings.languages.java.gradle.run_using == ide_core::settings::GradleRunUsing::Ide
}
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
#[allow(clippy::too_many_arguments)]
@@ -241,8 +432,9 @@ async fn resolve_launch_without_jdtls(
let started = std::time::Instant::now();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (model, built, by_service) = {
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let on_event = |event: BuildEvent| {
@@ -250,12 +442,33 @@ async fn resolve_launch_without_jdtls(
events(event);
}
};
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
};
(model, built)
if policy == BuildPolicy::NoBuild {
return (model, None, false);
}
if served_by_service(&scope.root, &model, &scope.settings, &module)
&& !compile::launch_has_non_java_sources(&scope.root, &model, &module, test)
{
match build_with_service(
&service,
&data_dir,
&scope,
&model,
&module,
test,
Some(kind),
&cancel,
&on_event,
) {
Ok(Some(outputs)) => {
let built = compile::LaunchBuild { class_dirs: outputs.class_paths, failure: outputs.failure };
return (model, Some(Ok(built)), true);
}
Ok(None) => {}
Err(e) => return (model, Some(Err(e)), false),
}
}
let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event);
(model, Some(built), false)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -294,6 +507,12 @@ async fn resolve_launch_without_jdtls(
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
}
None if by_service => {}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
@@ -683,7 +902,8 @@ pub async fn java_build_workspace(
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
/// Maven Central), and,
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
#[command(trust = trusted)]
pub async fn java_junit_runner(
@@ -707,13 +927,13 @@ pub async fn java_junit_runner(
let runner = ide_sdk::java::junit_runner_jar(&data_dir)
.ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?;
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
ide_sdk::java::JunitLauncher::OnClasspath => None,
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
ide_sdk::java::JunitLauncher::NoPlatform => {
return Err(IdeError::unavailable(
"No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \
Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
through Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
));
}
};
+2
Переглянути файл
@@ -19,6 +19,7 @@ pub mod flutter;
pub mod fs;
pub mod heap;
pub mod history;
pub mod http;
pub mod java;
pub mod jvm_icons;
pub mod lsp;
@@ -92,6 +93,7 @@ ide_command::domains!(
fs: crate::ops::fs,
heap: crate::ops::heap,
history: crate::ops::history,
http: crate::ops::http,
java: crate::ops::java,
jvm_icons: crate::ops::jvm_icons,
lsp: crate::ops::lsp,
+3
Переглянути файл
@@ -122,6 +122,9 @@ pub fn settings_set(
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
if key == "terminal" || key.starts_with("terminal.") {
super::term::apply_output_rate(host, window);
}
let sink = host.window_sink(window);
sink.emit(IdeEvent::SettingsChanged { key });
if let Some(root) = applied.roots_changed {
+1
Переглянути файл
@@ -319,6 +319,7 @@ pub async fn run_start(
on_output: Channel<OutputChunk>,
request: Option<ide_core::RequestId>,
) -> IdeResult<RunInfo> {
super::term::apply_output_rate(host, window);
let on_output: Emit<OutputChunk> = Arc::new(move |chunk| {
let _ = on_output.send(chunk);
});
+21 -3
Переглянути файл
@@ -4,8 +4,10 @@
//! given belong to the server's [`ide_ssh::SshManager`], not the desktop's.
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use ide_core::event::NotifyLevel;
use ide_core::remote_settings::SshConfiguration;
use ide_core::{IdeError, IdeEvent, IdeResult};
use ide_ssh::secrets::LegacyPasswordAction;
/// Test Connection: connects with `config` as edited (not necessarily saved).
#[command(trust = always)]
@@ -15,8 +17,23 @@ pub async fn ssh_test(host: &Host, config: SshConfiguration, secret: Option<Stri
/// Remembers the password / passphrase of configuration `id` (`None` forgets it).
#[command(trust = always)]
pub fn ssh_set_secret(host: &Host, id: String, secret: Option<String>, save: bool) {
host.ssh.set_secret(&id, secret, save);
pub fn ssh_set_secret(host: &Host, window: &str, id: String, secret: Option<String>, save: bool) {
if let Err(e) = host.ssh.set_secret(&id, secret, save) {
host.window_sink(window).emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: "Could not save credential".into(),
body: Some(e.message),
});
}
}
/// `Some` means legacy credentials remain in plaintext on this host.
#[command(trust = always)]
pub async fn ssh_legacy_passwords(host: &Host, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
let ssh = host.ssh.clone();
tokio::task::spawn_blocking(move || ssh.resolve_legacy_passwords(action))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Whether a password is saved under `key` (an FTP deployment server's).
@@ -52,6 +69,7 @@ ide_command::domain!(
ssh:
ssh_connected,
ssh_disconnect,
ssh_legacy_passwords,
ssh_needs_secret,
ssh_password_saved,
ssh_set_secret,
+12
Переглянути файл
@@ -29,6 +29,7 @@ pub async fn term_spawn(
mut options: TerminalOptions,
on_output: Channel<String>,
) -> IdeResult<TerminalInfo> {
apply_output_rate(host, window);
if !host.project(window).is_ok_and(|p| p.is_trusted()) {
// Project terminal settings can otherwise start a command as soon as a tab restores.
let global = host.global_settings.effective().terminal;
@@ -61,6 +62,17 @@ pub async fn term_spawn(
Ok(info)
}
/// Settings › Tools › Terminal › Max FPS also paces the terminal and Run console output
/// pumps (#5897): applied from the window's effective settings when a session starts and
/// when the setting changes. The rate is process-wide; the last window to apply it wins.
pub(crate) fn apply_output_rate(host: &Host, window: &str) {
let terminal = match host.project(window) {
Ok(project) => project.settings.effective().terminal,
Err(_) => host.global_settings.effective().terminal,
};
ide_core::output_rate::set_max_fps(&terminal.max_fps);
}
/// Tools › Start SSH Session: a login shell on SSH configuration `id`, opened by the
/// built-in client with the configuration's saved password, key or agent.
pub async fn spawn_ssh(
+48 -1
Переглянути файл
@@ -4826,7 +4826,18 @@ impl PluginApi {
if let Some(icon) = file.as_ref().and_then(|f| f.icon.as_ref()) {
ide_extension::validate_item_id(icon, "file icon id").map_err(HostError::Invalid)?;
}
items.retain(|d| decoration_style(&d.style));
for colors in items.iter_mut().filter_map(|d| d.colors.as_mut()) {
for color in [&mut colors.foreground, &mut colors.background].into_iter().flatten() {
*color = decoration_color(color).ok_or_else(|| {
HostError::Invalid(format!("decoration color '{color}' is not #rrggbb or #rrggbbaa"))
})?;
}
}
items
.iter_mut()
.for_each(|d| d.colors = d.colors.take().filter(|c| c.foreground.is_some() || c.background.is_some()));
// An item with its own colors (API 1.17) may leave the style empty.
items.retain(|d| decoration_style(&d.style) || (d.style.is_empty() && d.colors.is_some()));
if items.iter().any(|d| d.range.start > d.range.end) {
return Err(HostError::Invalid("reversed decoration range".into()));
}
@@ -4924,6 +4935,13 @@ impl PluginApi {
Ok(())
}
}
/// A `set-styled` color as the editor renders it: `#rrggbb` or `#rrggbbaa`, lower case.
fn decoration_color(color: &str) -> Option<String> {
let hex = color.strip_prefix('#')?;
((hex.len() == 6 || hex.len() == 8) && hex.bytes().all(|b| b.is_ascii_hexdigit()))
.then(|| format!("#{}", hex.to_ascii_lowercase()))
}
fn decoration_style(style: &str) -> bool {
matches!(
style,
@@ -5058,9 +5076,38 @@ mod workbench_tests {
hover: None,
after: Some("after".into()),
markdown_hover: None,
colors: None,
};
api.decorations(Some(&path), "set", vec![item("highlight"), item("unknown")]).unwrap();
assert_eq!(api.shared.decoration_sets()["test"][0].items.len(), 1);
// Styled items (API 1.17): colors are validated and normalized; an empty style needs colors.
let colored = |style: &str, foreground: Option<&str>, background: Option<&str>| ide_plugin::Decoration {
colors: Some(ide_plugin::DecorationColors {
foreground: foreground.map(Into::into),
background: background.map(Into::into),
}),
..item(style)
};
api.decorations(
Some(&path),
"styled",
vec![
colored("", Some("#1A1A1A"), Some("#FFEB3BFF")),
colored("highlight", None, Some("#00e5ff")),
colored("", None, None),
item(""),
],
)
.unwrap();
let styled = api.shared.decoration_sets()["test"].iter().find(|s| s.set_id == "styled").unwrap().items.clone();
assert_eq!(styled.len(), 2);
let first = styled[0].colors.as_ref().unwrap();
assert_eq!((first.foreground.as_deref(), first.background.as_deref()), (Some("#1a1a1a"), Some("#ffeb3bff")));
for bad in ["red", "#fff", "#12345g", "rgb(0,0,0)", "#1234567", "#ffffff; x: y"] {
let err = api.decorations(Some(&path), "styled", vec![colored("", Some(bad), None)]).unwrap_err();
assert!(matches!(err, HostError::Invalid(ref m) if m.contains("#rrggbb")), "{bad}: {err}");
}
api.decorations(None, "styled", vec![]).unwrap();
// Decorations follow the file: a path outside the open project is accepted too.
api.decorations(Some(&root.join("../outside.txt")), "set", vec![]).unwrap();
assert_eq!(api.shared.decoration_sets()["test"].len(), 2);
+3
Переглянути файл
@@ -385,6 +385,9 @@ impl PluginHost {
}
);
let fetched = self.fetch_market_package(&candidate.url, &entry, &archive);
if let Some(mirror) = &candidate.mirror {
mirror::report(mirror, fetched.is_ok());
}
if let Err(e) = &fetched {
tracing::warn!("plugins: {} from {} failed: {}", entry.id, candidate.url, e.message);
}
+65 -11
Переглянути файл
@@ -125,8 +125,8 @@ impl Host {
// A window takes the root over from the MCP server's background project, whose
// shutdown the wait below sits out; none opens until this open is over.
let _claim = (!crate::mcp::BackgroundProjects::is_key(window)).then(|| self.mcp_background.claim(self, &root));
self.close_project(window);
self.wait_detached_closes();
self.close_project_detached(window);
self.wait_detached_closes_for(&root);
let sink: SharedSink = (self.sink_for)(window);
// Before anything the project starts: its children get the project's environment.
let trusted = Arc::new(AtomicBool::new(self.trust.window_trusted(&root)?));
@@ -867,8 +867,10 @@ impl Host {
}
return Ok(current);
}
self.close_project(window);
self.wait_detached_closes();
self.close_project_detached(window);
if let Some(dir) = watch_dir {
self.wait_detached_closes_for(dir);
}
let sink: SharedSink = (self.sink_for)(window);
let settings = Arc::new(SettingsStore::load(&self.config_dir, None));
let effective = settings.effective();
@@ -2004,7 +2006,7 @@ fn with_gradle_roots(
use ide_build::gradle::ReportedRoot;
use ide_workspace::roots::RootKind;
let mut out: Vec<SourceFolder> = Vec::new();
for (dir, kind) in ide_build::gradle_source_roots(root, build_cache, settings) {
for (dir, kind, project) in ide_build::gradle_source_roots(root, build_cache, settings) {
if !dir.is_dir() {
continue;
}
@@ -2017,7 +2019,16 @@ fn with_gradle_roots(
ReportedRoot::Excluded => RootKind::Excluded,
};
if !out.iter().any(|f| f.path == path) {
out.push(SourceFolder { path, kind, detected_from: Some("Gradle".into()) });
// `<module>/Gradle`, like the `<module>/build.gradle` static detection reports, so the
// UI still finds the module after a sync. Projects outside the root stay `Gradle`:
// the UI reads the folder as project-relative.
let detected_from = match project.strip_prefix(root) {
Ok(rel) if !rel.as_os_str().is_empty() => {
format!("{}/Gradle", ide_workspace::roots::normalize(&rel.to_string_lossy()))
}
_ => "Gradle".into(),
};
out.push(SourceFolder { path, kind, detected_from: Some(detected_from) });
}
}
out.extend(detected.iter().filter(|d| !out.iter().any(|o| o.path == d.path)).cloned().collect::<Vec<_>>());
@@ -2397,6 +2408,48 @@ mod gradle_roots_tests {
use super::*;
use ide_workspace::RootKind;
#[test]
fn gradle_sync_roots_keep_the_module_they_belong_to() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let cache = root.join(".cache");
for d in [root.join("src/main/java"), root.join("lib/src/main/java"), root.join("lib/build"), cache.clone()] {
std::fs::create_dir_all(d).unwrap();
}
std::fs::write(root.join("build.gradle"), "").unwrap();
let s = |p: PathBuf| p.to_string_lossy().into_owned();
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
{ "path": ":", "dir": s(root.clone()), "sourceSets": [
{ "name": "main", "test": false, "src": [s(root.join("src/main/java"))], "res": [] } ] },
{ "path": ":lib", "dir": s(root.join("lib")), "buildDir": s(root.join("lib/build")), "sourceSets": [
{ "name": "main", "test": false, "src": [s(root.join("lib/src/main/java"))], "res": [] } ] },
]});
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
// What static detection reports for this layout before the first sync.
let detected = [
SourceFolder {
path: "src/main/java".into(),
kind: RootKind::Source,
detected_from: Some("build.gradle".into()),
},
SourceFolder {
path: "lib/src/main/java".into(),
kind: RootKind::Source,
detected_from: Some("lib/build.gradle".into()),
},
];
let out = with_gradle_roots(&root, &cache, &Default::default(), &detected);
let got: Vec<_> = out.iter().map(|f| (f.path.as_str(), f.detected_from.as_deref())).collect();
assert_eq!(
got,
[
("src/main/java", Some("Gradle")),
("lib/src/main/java", Some("lib/Gradle")),
("lib/build", Some("lib/Gradle")),
]
);
}
#[test]
fn gradle_sync_roots_win_and_reach_outside_the_project() {
let tmp = tempfile::tempdir().unwrap();
@@ -2420,14 +2473,15 @@ mod gradle_roots_tests {
std::fs::write(root.join("build.gradle"), "").unwrap();
let out = with_gradle_roots(&root, &cache, &Default::default(), &[guessed, other.clone()]);
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
let got: Vec<(String, RootKind)> = out.iter().map(|f| (f.path.clone(), f.kind)).collect();
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.kind, f.detected_from.as_deref())).collect();
// A project outside the root is not a module the UI could address.
assert_eq!(
got,
[
("src/it/java".into(), RootKind::Test),
(abs(svc.join("src/main/java")), RootKind::Source),
(abs(svc.join("build")), RootKind::Excluded),
("web".into(), RootKind::Source),
("src/it/java".into(), RootKind::Test, Some("Gradle")),
(abs(svc.join("src/main/java")), RootKind::Source, Some("Gradle")),
(abs(svc.join("build")), RootKind::Excluded, Some("Gradle")),
("web".into(), RootKind::Source, None),
]
);
}
+36
Переглянути файл
@@ -156,6 +156,7 @@ const SHELL_OWN: &[&str] = &["PWD", "OLDPWD", "SHLVL", "_"];
pub(crate) fn read_login_env(shell: &str, timeout: std::time::Duration) -> Option<Vec<(OsString, OsString)>> {
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use std::time::Instant;
@@ -182,6 +183,11 @@ pub(crate) fn read_login_env(shell: &str, timeout: std::time::Duration) -> Optio
cmd.env_remove(k);
}
ide_core::process::prepare(&mut cmd);
// An interactive shell takes job control from its inherited terminal. A new session leaves it
// without a controlling terminal, so it cannot stop its parent's process group with SIGTTIN.
unsafe {
cmd.pre_exec(|| rustix::process::setsid().map(|_| ()).map_err(Into::into));
}
let mut child = cmd
.args(["-ilc", &format!("printf '{MARK}'; /usr/bin/env -0; printf '{MARK}'")])
.stdin(Stdio::null())
@@ -271,6 +277,36 @@ mod tests {
assert_eq!(get(&third, "OPENIDEA_TEST_SEEN").as_deref(), Some("unset"));
}
#[test]
fn login_shell_gets_a_new_session() {
let tmp = tempfile::tempdir().unwrap();
let (shell, rc) = fake_shell(tmp.path());
// macOS `ps` has no session id column; a session leader also leads its own process group.
let column = if cfg!(target_os = "linux") { "sid" } else { "pgid" };
std::fs::write(
&rc,
format!("export OPENIDEA_TEST_PID=$$\nexport OPENIDEA_TEST_SID=$(ps -o {column}= -p $$)\n"),
)
.unwrap();
let env = read_login_env(&shell, Duration::from_secs(10)).unwrap();
let get = |k: &str| {
env.iter()
.find(|(name, _)| name == k)
.map(|(_, value)| value.to_string_lossy().trim().parse::<i32>().unwrap())
.unwrap()
};
let shell_pid = get("OPENIDEA_TEST_PID");
let shell_sid = get("OPENIDEA_TEST_SID");
let test_sid = if cfg!(target_os = "linux") {
rustix::process::getsid(None).unwrap().as_raw_nonzero().get()
} else {
rustix::process::getpgrp().as_raw_nonzero().get()
};
assert_eq!(shell_sid, shell_pid);
assert_ne!(shell_sid, test_sid);
}
#[test]
fn a_shell_that_hangs_times_out() {
let tmp = tempfile::tempdir().unwrap();
+20
Переглянути файл
@@ -2,6 +2,26 @@ mod common;
use ide_host::{Host, HostConfig, ops};
#[tokio::test]
async fn startup_moves_legacy_ssh_credentials_without_opening_a_project_or_connection() {
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
use_memory_store();
let tmp = tempfile::tempdir().unwrap();
let config = common::host_config(tmp.path());
std::fs::create_dir_all(&config.data_dir).unwrap();
std::fs::write(config.data_dir.join("ssh-passwords.json"), r#"{"box":"legacy-fixture"}"#).unwrap();
let host = Host::new(config);
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while !files_containing(tmp.path(), "legacy-fixture").is_empty() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("startup migration");
assert_eq!(host.ssh.password("box").as_deref(), Some("legacy-fixture"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn split_storage_keeps_user_history_and_uses_local_tools_and_caches() {
let tmp = tempfile::tempdir().unwrap();
+215
Переглянути файл
@@ -0,0 +1,215 @@
mod common;
use ide_build::compile::BuildEvent;
use ide_core::RequestId;
use ide_host::{Host, ops};
use ide_run::BuildPolicy;
use ide_workspace::{SettingsStore, settings::SettingsScope};
use std::fs;
use std::path::Path;
use std::sync::{Arc, Mutex};
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
/// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache)
/// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn maven_launch_compiles_with_the_ides_java_build() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() {
eprintln!("skipped: needs JAVA_HOME and mvn");
return;
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
write(
&root,
"pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>"#,
);
write(
&root,
"lib/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
);
write(
&root,
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
);
write(
&root,
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
// No language server: the build tool compiles the launch.
let global = SettingsStore::load(&base.join("config"), None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
let info = ops::java::java_resolve_launch(
&host,
"main",
root.join("app"),
false,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
let steps: Vec<String> = events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command.clone()),
_ => None,
})
.collect();
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
assert!(!steps.iter().any(|s| s.contains("-am")), "{steps:?}");
let first = Path::new(&info.class_paths[0]);
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
assert!(first.join("a/A.class").is_file());
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
assert!(!root.join("app/target/classes").exists());
// Build › Build Project compiles with it too, and reports javac's errors.
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
let built = ops::build::build_run(
&host,
"main",
ide_build::compile::BuildKind::Build,
None,
None,
RequestId::next(),
Vec::new(),
ops::Channel::new(|_: BuildEvent| {}),
)
.await
.unwrap();
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
assert!(!built.success);
assert_eq!(built.errors, 1, "{:?}", built.messages);
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
assert!(!root.join("lib/target/classes").exists());
host.shutdown().await;
}
/// With Settings › Gradle › Build and run using: IDE, a Gradle launch and Build Project compile
/// with the IDE's Java build too. Needs a JDK (`JAVA_HOME`) and Gradle (`OPENIDEA_TEST_GRADLE`).
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn gradle_launch_compiles_with_the_ides_java_build() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
let Some(gradle) = std::env::var_os("OPENIDEA_TEST_GRADLE").filter(|_| has_jdk) else {
eprintln!("skipped: needs JAVA_HOME and OPENIDEA_TEST_GRADLE");
return;
};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
write(&root, "settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n");
write(&root, "build.gradle", "subprojects {\n apply plugin: 'java'\n group = 't'\n}\n");
write(&root, "lib/build.gradle", "");
write(&root, "app/build.gradle", "dependencies { implementation project(':lib') }\n");
write(&root, "gradlew", &format!("#!/bin/sh\nexec '{}' \"$@\"\n", Path::new(&gradle).display()));
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(root.join("gradlew"), fs::Permissions::from_mode(0o755)).unwrap();
write(
&root,
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
);
write(
&root,
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
let global = SettingsStore::load(&base.join("config"), None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
global.set(SettingsScope::Global, "languages.java.gradle.runUsing", serde_json::json!("ide")).unwrap();
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
let info = ops::java::java_resolve_launch(
&host,
"main",
root.join("app"),
false,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
let steps: Vec<String> = events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command.clone()),
_ => None,
})
.collect();
assert!(steps.iter().any(|s| s.contains("openideaBuildModel")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
let first = Path::new(&info.class_paths[0]);
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
assert!(first.join("a/A.class").is_file());
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
assert!(!root.join("app/build/classes").exists());
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
let built = ops::build::build_run(
&host,
"main",
ide_build::compile::BuildKind::Build,
None,
None,
RequestId::next(),
Vec::new(),
ops::Channel::new(|_: BuildEvent| {}),
)
.await
.unwrap();
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
assert_eq!(built.errors, 1, "{:?}", built.messages);
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
host.shutdown().await;
}
+3 -3
Переглянути файл
@@ -1572,7 +1572,7 @@ async fn a_run_started_without_confirmation_works_in_a_background_project_and_ho
id: "serve".into(),
name: "serve stock".into(),
kind: "shell".into(),
command: "sleep 30".into(),
command: "cat".into(),
args: vec![],
cwd: None,
env: Default::default(),
@@ -1598,11 +1598,11 @@ async fn a_run_started_without_confirmation_works_in_a_background_project_and_ho
// The call still waits for the run: it holds the project first, the run second.
let held = h.host.mcp_background.snapshot(&h.host, std::time::Instant::now()).remove(0);
assert_eq!(held.kept_open_by, Some(ide_host::mcp::McpBackgroundHold::Request));
h.host.processes.stop(run.id).unwrap();
h.host.processes.close_stdin(run.id).unwrap();
};
let (result, ()) = tokio::join!(call, observe);
let result: Value = serde_json::from_str(&result.unwrap()).unwrap();
assert!(result["exitCode"].is_number() || result["exitCode"].is_null(), "{result}");
assert_eq!(result["exitCode"], 0, "{result}");
let loaded = h.host.mcp_background.snapshot(&h.host, std::time::Instant::now()).remove(0);
assert_eq!(loaded.kept_open_by, None, "the call is over and the run has exited");
}
+25
Переглянути файл
@@ -7010,6 +7010,31 @@ fn markdown_decorations_publish_a_hover_card_and_clear() {
assert!(f.host.decoration_sets()["decorations"].is_empty());
}
/// API 1.17: `set-styled` items carry their own colors, normalized by the host, and replace
/// the set's earlier kind of items.
#[test]
fn styled_decorations_carry_normalized_colors() {
let f = fixture(Limits::default());
f.install(&sample("decorations"));
f.run("decorations", "publish", Some("src/notes.txt")).unwrap();
f.run("decorations", "styled", Some("src/notes.txt")).unwrap();
let sets = f.host.decoration_sets();
let set = &sets["decorations"][0];
assert_eq!(set.set_id, "example");
let colors: Vec<_> = set.items.iter().map(|d| (d.style.as_str(), d.colors.clone().unwrap())).collect();
assert_eq!(
colors,
[
(
"",
ide_plugin::DecorationColors { foreground: Some("#1a1a1a".into()), background: Some("#ffeb3b".into()) }
),
("", ide_plugin::DecorationColors { foreground: None, background: Some("#00e5ff80".into()) }),
]
);
f.run("decorations", "clear", None).unwrap();
}
// ─── Project window groups ────────────────────────────────────────────────────
// A group's container root holds only `.openidea` metadata; the files live in
// the member projects. The plugin surface reaches them like the editor and the
+14 -2
Переглянути файл
@@ -136,7 +136,8 @@ async fn ssh_server(home: &Path, server_home: &Path, project: &Path) -> Arc<ide_
save_secret: true,
..Default::default()
}]);
ssh.set_secret("local-test", Some("secret".into()), true);
ide_ssh::secrets::testing::use_memory_store();
ssh.set_secret("local-test", Some("secret".into()), true).unwrap();
assert!(ssh.session("local-test").await.is_err(), "unknown host key first");
ssh.trust_host("local-test").await.unwrap();
ssh.session("local-test").await.unwrap()
@@ -744,7 +745,18 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
.unwrap();
until("old backend socket", || guard.0.exists()).await;
let old_open = || async {
let mut stream = UnixStream::connect(&guard.0).await.unwrap();
// bind() creates the socket file before listen(): a connect in between is refused.
let mut stream = 'connect: {
for _ in 0..600 {
match UnixStream::connect(&guard.0).await {
Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
tokio::time::sleep(Duration::from_millis(15)).await;
}
other => break 'connect other.unwrap(),
}
}
panic!("the old backend never accepted a connection");
};
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
assert_eq!(stream.read_u8().await.unwrap(), b'A');
let (reader, writer) = stream.into_split();
+21
Переглянути файл
@@ -308,6 +308,18 @@ async fn serves_projects_files_documents_search_and_runs() {
assert!(found.iter().any(|d| d["type"] == "file"), "{found:?}");
assert_eq!(found.last().unwrap()["type"], "done");
// HTTP Client requests and their history are served by the project host.
let history = invoke(&peer, "http_history", json!({})).await.unwrap();
assert_eq!(history, json!([]));
let curl = invoke(
&peer,
"http_curl",
json!({ "path": null, "text": "GET http://localhost/x\n", "index": 0, "env": null }),
)
.await
.unwrap();
assert!(curl.as_str().unwrap().contains("http://localhost/x"), "{curl}");
// A run's output streams through a channel and its exit is an event.
let config = json!({ "id": "echo", "name": "echo", "kind": "shell", "command": "echo", "args": ["remote-hi"],
"cwd": null, "env": {}, "detected": false, "isTest": false, "debugAdapter": null });
@@ -371,6 +383,14 @@ async fn local_deployment_runs_on_the_project_host() {
"remote_mkdir",
"remote_rename",
"remote_download_into",
"http_environments",
"http_execute",
"http_history",
"http_history_get",
"http_history_clear",
"http_curl",
"http_environment_file",
"http_variable_definitions",
"db_sources",
"db_save_sources",
"db_set_password",
@@ -387,6 +407,7 @@ async fn local_deployment_runs_on_the_project_host() {
"db_schemas",
"db_tables",
"db_table_details",
"db_table_grants",
"db_ddl",
"db_schema_objects",
"db_object_ddl",
+26 -1
Переглянути файл
@@ -10,6 +10,30 @@ use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
#[tokio::test]
async fn a_failed_credential_save_warns_the_window_but_keeps_the_session_password() {
let tmp = tempfile::tempdir().unwrap();
let config = common::host_config(tmp.path());
std::fs::create_dir_all(config.data_dir.join("ssh-passwords.json")).unwrap();
let (tx, rx) = mpsc::channel();
let host = Host::new(HostConfig {
sink_for: Box::new(move |_| {
let tx = tx.clone();
Arc::new(move |e| tx.send(e).unwrap())
}),
..config
});
ide_host::ops::ssh::ssh_set_secret(&host, "main", "box".into(), Some("test-value".into()), true);
let warning = rx.try_iter().find_map(|e| match e {
IdeEvent::Notify { level: ide_core::event::NotifyLevel::Warning, body, .. } => body,
_ => None,
});
let warning = warning.expect("the window should be told saving failed");
assert!(warning.contains("session only"));
assert!(!warning.contains("test-value"));
assert_eq!(host.ssh.password("box").as_deref(), Some("test-value"));
}
fn read_until(rx: &mpsc::Receiver<String>, needle: &str) -> String {
let mut all = String::new();
while !all.contains(needle) {
@@ -38,7 +62,8 @@ async fn host_with_ssh_box(tmp: &Path, exec: ide_ssh::testing::ExecFn) -> (Arc<H
save_secret: true,
..Default::default()
}]);
ssh.set_secret("box", Some("secret".into()), true);
ide_ssh::secrets::testing::use_memory_store();
ssh.set_secret("box", Some("secret".into()), true).unwrap();
assert!(ssh.session("box").await.is_err(), "unknown host key first");
ssh.trust_host("box").await.unwrap();
+1 -1
Переглянути файл
@@ -80,7 +80,7 @@ async fn welcome_window_browses_selected_ssh_host_without_executing_commands() {
auth: SshAuth::Password,
..Default::default()
}]);
ssh.set_secret("selected-host", Some("secret".into()), false);
ssh.set_secret("selected-host", Some("secret".into()), false).unwrap();
assert!(ssh.session("selected-host").await.is_err());
ssh.trust_host("selected-host").await.unwrap();
+15 -5
Переглянути файл
@@ -88,10 +88,18 @@ done
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
let info =
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
.await
.unwrap();
let info = ops::java::java_resolve_launch(
&host,
"main",
module,
test,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
// The build streams its command and progress while it runs.
use ide_build::compile::BuildEvent;
let events = events.lock().unwrap();
@@ -110,7 +118,9 @@ done
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
// This Maven records no build model for the IDE's Java build, so Maven builds the module.
assert!(calls.lines().next().unwrap().contains("-Dopenidea.build.model="), "{calls}");
assert!(calls.lines().nth(1).unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains(":build-classpath"), "{calls}");
}
+17
Переглянути файл
@@ -378,6 +378,23 @@ fn binary_and_huge_files_are_listed_without_symbols() {
assert_eq!(idx.status().symbols, 0);
}
#[test]
fn binary_files_are_classified_from_their_head_and_text_is_read_past_it() {
let fx = Fixture::new(&[("img/logo.rs", "")]);
let mut binary = b"fn head() {}\0".to_vec();
binary.extend(std::iter::repeat_n(b'x', 64 * 1024));
std::fs::write(fx.root.join("img/logo.rs"), &binary).unwrap();
let long = format!("{}fn past_the_sniff() {{}}\n", "// pad\n".repeat(2000));
assert!(long.len() > 8192);
fx.write("src/long.rs", &long);
let idx = fx.open();
assert_eq!(symbols(&idx, "past_the_sniff", SymbolFilter::All), vec!["past_the_sniff"]);
assert!(symbols(&idx, "head", SymbolFilter::All).is_empty());
let data = idx.shared.data.read();
let logo = data.files.iter().flatten().find(|entry| entry.rel.as_ref() == "img/logo.rs").unwrap();
assert_eq!(logo.hash, [0; 32], "a binary file is not read whole to be hashed");
}
#[test]
fn go_to_file_finds_ignored_files_but_not_their_symbols() {
let fx = Fixture::new(&[
+33 -19
Переглянути файл
@@ -29,6 +29,8 @@ static INDEX_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
/// Files larger than this are listed but not parsed for symbols.
pub const MAX_SYMBOL_FILE: u64 = 2 * 1024 * 1024;
/// Leading bytes checked for NUL to tell a binary file from text.
const BINARY_SNIFF: usize = 8192;
const CHUNK: usize = 512;
/// Insert/persist batch of the initial scan's streaming pass.
const SCAN_BATCH: usize = 2048;
@@ -180,7 +182,7 @@ impl Shared {
let snapshot_started = Instant::now();
let fast = self.try_fast_start();
let snapshot_elapsed = snapshot_started.elapsed();
if !fast {
if let Err(reason) = fast {
let snapshot_guard = SystemTime::now();
let walk_started = Instant::now();
let found = self.walk_roots(None);
@@ -192,6 +194,7 @@ impl Shared {
if !self.is_cancelled() {
tracing::info!(
mode = "fallback",
reason,
snapshot_attempt_ms = snapshot_elapsed.as_millis() as u64,
walk_ms = walk_elapsed.as_millis() as u64,
hydration_ms = hydration_elapsed.as_millis() as u64,
@@ -259,25 +262,26 @@ impl Shared {
/// Warm start: validate the snapshot's flat directory/file manifest and hydrate
/// without walking the tree. A changed scope, symlink, directory mtime, file
/// mtime or file size falls back to the full walk.
fn try_fast_start(&self) -> bool {
/// mtime or file size falls back to the full walk; the error says which, for
/// the start-up log.
fn try_fast_start(&self) -> Result<(), &'static str> {
let started = Instant::now();
let Some(store) = &self.store else { return false };
let Some(store) = &self.store else { return Err("no cache") };
let load_started = Instant::now();
let Some(snapshot) = store.load_snapshot() else { return false };
let Some(snapshot) = store.load_snapshot() else { return Err("no snapshot for this build") };
let loaded = load_started.elapsed();
let filter = self.filter();
if filter.has_extra_roots() || snapshot.filter() != filter.stamp() {
return false;
return Err("index scope changed");
}
let root = filter.root();
let validation_started = Instant::now();
for i in 0..snapshot.dirs_len() {
let rel = snapshot.dir(i);
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
let Ok(meta) = std::fs::symlink_metadata(&path) else { return false };
let Ok(meta) = std::fs::symlink_metadata(&path) else { return Err("directory changed") };
if !meta.is_dir() || mtime_of(&meta) != snapshot.dir_mtime(i) {
return false;
return Err("directory changed");
}
}
let external = crate::store::external_ignore_candidates(root);
@@ -288,19 +292,19 @@ impl Shared {
if external.len() != saved_external.len()
|| external.iter().zip(&saved_external).any(|(path, saved)| path.to_string_lossy() != **saved)
{
return false;
return Err("ignore files changed");
}
for i in 0..snapshot.ignore_len() {
let path = Path::new(snapshot.ignore_path(i));
let meta = std::fs::metadata(path).ok();
let present = meta.is_some();
if present != snapshot.ignore_present(i) {
return false;
return Err("ignore files changed");
}
if let Some(meta) = meta
&& (mtime_of(&meta) != snapshot.ignore_mtime(i) || meta.len() != snapshot.ignore_size(i))
{
return false;
return Err("ignore files changed");
}
}
let validation_elapsed = validation_started.elapsed();
@@ -320,7 +324,7 @@ impl Shared {
});
let built = build_started.elapsed();
if entries.iter().any(Option::is_none) {
return false;
return Err("file changed");
}
let validated = entries;
let mut entries = Vec::with_capacity(validated.len());
@@ -372,7 +376,7 @@ impl Shared {
}
}
r.truncate(MAX_RECENT);
true
Ok(())
}
fn load_recent(&self, store: &Store, root: &Path) {
@@ -902,22 +906,32 @@ impl Shared {
if f.size > MAX_SYMBOL_FILE {
return Extracted::New(rec, Extraction::Oversized);
}
// Sniff the head first: a binary file is classified from its first
// `BINARY_SNIFF` bytes alone, so it is never read whole or hashed.
let mut bytes = Vec::with_capacity(f.size as usize);
match std::fs::File::open(&f.path).and_then(|mut file| file.read_to_end(&mut bytes)) {
Ok(_) => {}
let read = std::fs::File::open(&f.path).and_then(|mut file| {
(&mut file).take(BINARY_SNIFF as u64).read_to_end(&mut bytes)?;
if bytes.contains(&0) {
return Ok(true);
}
file.read_to_end(&mut bytes).map(|_| false)
});
let binary = match read {
Ok(binary) => binary,
Err(e) => {
tracing::debug!("index: cannot read {}: {e}", f.path.display());
return Extracted::New(rec, Extraction::ReadFailed);
}
};
if binary {
self.parsed.fetch_add(1, Ordering::Relaxed);
return Extracted::New(rec, Extraction::Binary);
}
rec.hash = *blake3::hash(&bytes).as_bytes();
if prev_hash == Some(rec.hash) {
return Extracted::Unchanged;
}
self.parsed.fetch_add(1, Ordering::Relaxed);
if bytes[..bytes.len().min(8192)].contains(&0) {
return Extracted::New(rec, Extraction::Binary);
}
let text = String::from_utf8_lossy(&bytes);
let lang = self.languages.detect(&f.path, Some(first_line(&text)));
if self.syntax.has_symbols(&lang) {
@@ -1462,7 +1476,7 @@ mod metric_tests {
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert!(index.try_fast_start());
assert_eq!(index.try_fast_start(), Ok(()));
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
assert_eq!(index.data.read().file_count, 1);
assert_eq!(index.data.read().symbol_count, 1);
+42 -2
Переглянути файл
@@ -342,6 +342,27 @@ impl Drop for JavaExternalBuild {
}
}
/// The Gradle tooling API's own messages for a build that failed, ahead of its cause.
const GRADLE_TOOLING_FAILURES: [&str; 4] = [
"The supplied phased action failed with an exception",
"Could not run phased build action",
"Could not run build action",
"Could not fetch model of type",
];
/// A diagnostic's message on one line. Buildship marks a Gradle project whose sync failed with
/// the tooling API's message on the first line and the build's own error last ("… failed with
/// an exception.\nA problem occurred evaluating root project 'app'.\n<the error>"); that error is
/// kept as the cause.
fn launch_message(message: &str) -> String {
let mut lines = message.lines().map(str::trim).filter(|l| !l.is_empty());
let first = lines.next().unwrap_or_default();
match lines.next_back() {
Some(cause) if GRADLE_TOOLING_FAILURES.iter().any(|m| first.contains(m)) => format!("{first} Cause: {cause}"),
_ => first.to_owned(),
}
}
/// Error diagnostics sorted by file and position, capped at `limit`, and their total.
pub fn compile_errors(
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
@@ -354,7 +375,7 @@ pub fn compile_errors(
path: path.into(),
line: d.range.start.line + 1,
column: d.range.start.character + 1,
message: d.message.lines().next().unwrap_or_default().to_owned(),
message: launch_message(&d.message),
})
.collect();
errors.sort_by(|a, b| (&a.path, a.line, a.column).cmp(&(&b.path, b.line, b.column)));
@@ -535,7 +556,8 @@ fn build_file_errors(diagnostics: &[(PathBuf, lsp_types::Diagnostic)], root: &Pa
&& path.parent().is_some_and(|dir| module.starts_with(dir))
})
.map(|(path, d)| {
let message = d.message.lines().next().unwrap_or_default().trim().trim_end_matches(':');
let message = launch_message(&d.message);
let message = message.trim().trim_end_matches(':');
(path.components().count(), format!("{}: {message}", path.strip_prefix(root).unwrap_or(path).display()))
})
.collect();
@@ -1638,6 +1660,24 @@ mod tests {
assert_eq!(std::fs::read_to_string(prefs).unwrap(), format!("{}=error\n", ACCESS_OPTIONS[0]));
}
#[test]
fn a_failed_gradle_sync_keeps_its_cause_on_one_line() {
let marker = "The supplied phased action failed with an exception.\n\
A problem occurred configuring root project 'app'.\n\
A problem occurred evaluating root project 'app'.\n\
missing generated schema";
assert_eq!(
launch_message(marker),
"The supplied phased action failed with an exception. Cause: missing generated schema"
);
assert_eq!(
launch_message("The supplied phased action failed with an exception."),
"The supplied phased action failed with an exception."
);
// Other messages keep their first line only.
assert_eq!(launch_message("x cannot be resolved\nmore detail"), "x cannot be resolved");
}
#[test]
fn access_warnings_do_not_hide_real_compile_errors() {
let path = PathBuf::from("src/Main.java");
+104
Переглянути файл
@@ -1188,3 +1188,107 @@ async fn phoxite_pulls_a_member_up_end_to_end() {
assert!(!refused.message.is_empty() && !refused.message.starts_with("phoxite:"), "{refused:?}");
mgr.shutdown_all().await;
}
/// jdtls keeps building incrementally even though the IDE's Java build compiles what runs:
/// its build is what reports an API change in one Maven module in the files of the modules
/// that use it, open or not. With `java.autobuild.enabled: false` (and
/// `validateAllOpenBuffersOnChanges`), neither updates.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires jdtls on PATH (or OPENIDEA_TEST_JDTLS) and a compatible JDK"]
async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap().join("project");
let write = |rel: &str, text: &str| {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, text).unwrap();
path
};
let parent = r#"<parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent>"#;
write(
"pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>app</module></modules><properties><maven.compiler.release>11</maven.compiler.release></properties></project>"#,
);
write(
"lib/pom.xml",
&format!("<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>lib</artifactId></project>"),
);
write(
"app/pom.xml",
&format!(
"<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"
),
);
let lib_source = "package l;\npublic class L { public static String name() { return \"lib\"; } }\n";
let app_source = "package a;\npublic class A { String s = l.L.name(); }\n";
let lib = write("lib/src/main/java/l/L.java", lib_source);
let app = write("app/src/main/java/a/A.java", app_source);
let closed = write("app/src/main/java/a/B.java", "package a;\nclass B { String s = l.L.name(); }\n");
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
java.language_servers.retain(|s| s.name == "jdtls");
let server = &mut java.language_servers[0];
if let Ok(bin) = std::env::var("OPENIDEA_TEST_JDTLS") {
server.command = bin;
}
server.args.extend(["-data".into(), dir.path().join("jdtls-data").to_string_lossy().into_owned()]);
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java]));
let (lib_doc, app_doc) = (DocId::next(), DocId::next());
mgr.did_open(lib_doc, &lib, &LanguageId::new("java"), 1, lib_source);
mgr.did_open(app_doc, &app, &LanguageId::new("java"), 1, app_source);
let errors = |path: &Path| {
events.lock().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path: p, items, .. } if p.0 == path => Some(
items
.iter()
.filter(|d| d.severity == ide_core::Severity::Error)
.map(|d| d.message.clone())
.collect::<Vec<_>>(),
),
_ => None,
})
};
// The import resolves `lib` from source: the open editor of `app` has no errors.
retry("app imported", Duration::from_secs(300), || {
let status = last_status(&events, "jdtls");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, message)) = &status {
panic!("jdtls failed: {message:?}");
}
let clean = errors(&app).is_some_and(|e| e.is_empty());
let mgr = mgr.clone();
let app = app.clone();
async move {
let cp =
tokio::time::timeout(Duration::from_secs(10), mgr.java_classpath(&app, false, &Default::default()))
.await
.ok()?
.ok()?;
(clean && cp.class_paths.iter().any(|p| p.contains("/lib/"))).then_some(())
}
})
.await;
// Rename the method in the editor of `lib`, and save.
let renamed = lib_source.replace("name()", "title()");
let line = lib_source.lines().nth(1).unwrap();
mgr.did_change(
lib_doc,
2,
&[AppliedChange {
range: Range::new(Pos::new(1, 0), Pos::new(1, line.len() as u32)),
text: renamed.lines().nth(1).unwrap().to_owned(),
}],
&|| renamed.clone(),
);
std::fs::write(&lib, &renamed).unwrap();
mgr.did_save(lib_doc, &renamed);
retry("the open editor of app reports the removed method", Duration::from_secs(120), || {
let found = errors(&app).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
async move { found.then_some(()) }
})
.await;
retry("the closed file of app reports it too", Duration::from_secs(60), || {
let found = errors(&closed).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
async move { found.then_some(()) }
})
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
+1 -1
Переглянути файл
@@ -59,7 +59,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
use views_bindings::openidea::plugin::view_types as wit_vt;
/// The API version of the world above, `major.minor` of [`host_api`].
pub const API_VERSION: &str = "1.16";
pub const API_VERSION: &str = "1.17";
const EPOCH_TICK: Duration = Duration::from_millis(10);
pub(crate) const MAX_TEXT: usize = 1 << 20;
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
+9
Переглянути файл
@@ -1023,6 +1023,15 @@ pub struct Decoration {
/// Markdown rendered in the editor's hover card (API 1.16); `hover` is the
/// plain-text fallback shown when this is absent.
pub markdown_hover: Option<String>,
/// The item's own colors (API 1.17 `set-styled`), validated `#rrggbb` / `#rrggbbaa`.
#[serde(default)]
pub colors: Option<DecorationColors>,
}
/// Colors of a styled editor decoration (API 1.17).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
pub struct DecorationColors {
pub foreground: Option<String>,
pub background: Option<String>,
}
/// A tree decoration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
+23
Переглянути файл
@@ -2888,6 +2888,7 @@ impl bindings::openidea::plugin::decorations::Host for StoreData {
hover: d.hover,
after: d.after,
markdown_hover: None,
colors: None,
})
.collect();
self.replace_decorations(path, set_id, items)
@@ -2906,6 +2907,28 @@ impl bindings::openidea::plugin::decorations::Host for StoreData {
hover: d.hover,
after: d.after,
markdown_hover: d.markdown_hover,
colors: None,
})
.collect();
self.replace_decorations(path, set_id, items)
}
fn set_styled(
&mut self,
path: String,
set_id: String,
items: Vec<bindings::openidea::plugin::decorations::StyledDecoration>,
) -> Fallible<()> {
let items = items
.into_iter()
.map(|d| crate::Decoration {
range: core_range(d.range),
style: d.style,
hover: d.hover,
after: d.after,
markdown_hover: d.markdown_hover,
colors: d
.colors
.map(|c| crate::DecorationColors { foreground: c.foreground, background: c.background }),
})
.collect();
self.replace_decorations(path, set_id, items)
+5 -4
Переглянути файл
@@ -95,7 +95,7 @@ fn the_sdk_carries_the_hosts_wit() {
#[test]
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
let host = v("1.16.0");
let host = v("1.17.0");
for ok in [
"1.0.0",
"1.3.0",
@@ -112,15 +112,16 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
"1.14.0",
"1.15.0",
"1.16.0",
"1.17.0",
"1.0.0-rc.1",
] {
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
}
let newer = check_api(&v("1.17.0"), &host).unwrap_err();
assert!(newer.contains("1.17") && newer.contains("update OpenIDEA"), "{newer}");
let newer = check_api(&v("1.18.0"), &host).unwrap_err();
assert!(newer.contains("1.18") && newer.contains("update OpenIDEA"), "{newer}");
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
let older = check_api(&v("0.2.0"), &host).unwrap_err();
assert!(older.contains("rebuild it with the 1.16 SDK"), "{older}");
assert!(older.contains("rebuild it with the 1.17 SDK"), "{older}");
// 0.x: every minor is its own API.
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
68517d169bea40ca5a5426a3a05ace3389417073b9369e79157a2beb051dcfc0
98e9c2b886df177bafb68a712fc1efadc4f3a7b82e8425cd1b3f4c2355bdb785
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6edda84fad0ee7cd56a3a28b55e6c559db7b7f6b9c8c0ca645be805b545c01e7
bb77bc0963451ca4259591bf68c72ae3eb70b1c6f855fa29dfc84d2be675404c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ecc6b6c52753b11521ae033a5a66c2a289119e09e07d22742203d3a13122dd97
f381b0e20520bccf5acd46b95641f5542885184352e52ec2fed3fd53665c353b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4ec581c69a62bbf424983e241a79d0bfdb5d025a3e86d27eea745adcb1906253
f72a53e7b800b8c5408c7ac67034821f814da7b1d66f527949450431bcf52e02
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5fb89ee3d07e4275433ad9ad930ad781ef4f227af11aa5eb9dfc9174c015b1b8
3cd2f02738b07d9a6294025cbcc6e906716d3e91db50a6f39485df9b1d6a4ead
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
236db5a85d3e7e9fee01c3ff0b9f5e66fad7e3d64fa618a0c1c980d9e5883839
d77b80884163628791b292acc59324d3b9a7c2236034b88f87e8f56af5929a48
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4f89bd09b571016cbb9feb0674e668aa66996997c6b53a91d1a4ffbf161083a3
5a79d35e9fc1560a39b6459312a14c27c73739fd385f6c2568f9b1c1bf8fe4a1
+6 -2
Переглянути файл
@@ -1,10 +1,10 @@
id = "decorations"
name = "Decoration example"
version = "0.1.0"
description = "Minimal plugin API 1.16 example: line-end labels with Markdown hover cards."
description = "Minimal plugin API 1.17 example: line-end labels with Markdown hover cards and their own colors."
authors = ["OpenIDEA contributors"]
license = "Apache-2.0"
engines.openidea = "^1.16"
engines.openidea = "^1.17"
wasm = "dist/plugin.wasm"
activation = ["on-command:*"]
@@ -15,6 +15,10 @@ required = ["project.read"]
id = "publish"
title = "Decorations: Publish"
[[contributes.commands]]
id = "styled"
title = "Decorations: Publish Styled"
[[contributes.commands]]
id = "clear"
title = "Decorations: Clear"
+29 -2
Переглянути файл
@@ -1,6 +1,10 @@
//! Minimal plugin API 1.16 example: push a line-end label whose hover is Markdown.
//! Minimal plugin API 1.17 example: push a line-end label whose hover is Markdown,
//! and ranges painted in the plugin's own colors.
use openidea_plugin::{Error, Invocation, MarkdownDecoration, Plugin, Position, Range, host, register_plugin};
use openidea_plugin::{
DecorationColors, Error, Invocation, MarkdownDecoration, Plugin, Position, Range, StyledDecoration, host,
register_plugin,
};
#[derive(Default)]
struct Decorations;
@@ -23,6 +27,29 @@ impl Plugin for Decorations {
)?;
Ok(None)
}
"styled" => {
let path = arg.ok_or_else(|| Error::Invalid("a project file path is required".into()))?;
let todo = |range, foreground: Option<&str>, background: &str| StyledDecoration {
range,
style: String::new(),
hover: Some("TODO".into()),
after: None,
markdown_hover: None,
colors: Some(DecorationColors {
foreground: foreground.map(Into::into),
background: Some(background.into()),
}),
};
host::set_styled_decorations(
path,
"example",
&[
todo(Range::new(Position::new(0, 0), Position::new(0, 1)), Some("#1A1A1A"), "#FFEB3B"),
todo(Range::new(Position::new(0, 1), Position::new(0, 2)), None, "#00e5ff80"),
],
)?;
Ok(None)
}
"clear" => {
host::clear_decorations("example")?;
Ok(None)
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c5c3bac9e2b69e4957bd5049d4f560dd04faf4dfc2d7523bb7968aa29f3bdcfb
264be0e527b0cc200e2d97e982b7b297ef6181a7669506ccf09159531f91124d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a75758a44e255b7df3adf53e5f81b8f1283270d28f78ad0d8b358d9feea98a99
6230dce145f2cce3033c4797566cbbff8c98e5d8c85d41f9342693b19a10b638
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7e658a971fd58b84fcadc1f4939991d5f4506936989d4c8a7302ccebc0455e9c
3d7d853fa40ce14ae6781dbf5607153c4f38b2663a31f1ca29a753e8eba79f03
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6b7c0d8971cfd3ba1d80c5fc6428e5890c820350972597a11be4ea6f0324973f
a128c5f640b42d323059a7be1bd2e89cb9de1ea1ea635b5af4e9f69b66bfd04c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
20e43b6ac3aaa1527874f98f4b502ef88dd4676b6096b989c7bfba7a521e723d
9e00f4bcad39a99f05c35ac66962a574f7edd5713f1aa404ef72fd7ef945d1e8
Бінарний файл не відображається.
Loaded 100 of 729 files, more files were not shown because too many files have changed in this diff. Show more