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

...
Автор SHA1 Повідомлення Дата
l0ng-ai bdb383fa0b fix(java): wait for the old compiler process to exit 2026-12-06 21:31:19 +08:00
l0ng-ai 36d3ed9901 test(java): exercise build coordination through overlapping host projects 2026-12-06 21:20:57 +08:00
l0ng-ai 7df1f037e1 fix(java): coordinate builds across overlapping project windows 2026-12-06 21:10:51 +08:00
l0ng-ai 3ee1062d91 fix(markdown): take MDX preview shortcuts and links only from the user's input (#8382)
The MDX live preview runs the document's own code in the same frame as the
bridge that forwards shortcuts and link clicks to the IDE. That code can take
the bridge's port (for example by asking the host for the guest document again)
and post IDE shortcuts at any time, or open links while the pointer only hovers
over the frame.

A forwarded shortcut now counts only while the frame has the focus and the user
just pressed a key or clicked in it, the check plugin web views already make;
a link needs the same on top of the pointer being on the frame.
2026-12-06 20:44:14 +08:00
l0ng-ai 630992ca8f fix(editor): preserve contextual completion prefixes (#8323)
* fix(editor): preserve contextual completion prefixes

* fix(editor): preserve single-winner completion metadata in mergeResults
2026-12-06 20:39:23 +08:00
l0ng-ai d1b03e837a fix(tools): don't mistake supplemental servers for analyzer fallbacks (#8235)
* fix(tools): don't mistake supplemental servers for analyzer fallbacks

* fix(tools): scope language server alternative chains to the current language
2026-12-06 20:37:56 +08:00
l0ng-ai fb6d60a577 fix(python): remember added interpreters after switching (#8228) 2026-12-06 20:35:58 +08:00
l0ng-ai 58ccb9dbc9 fix(server): stop other sites from framing the web workbench (#8380)
`openidea-server --web` served the workbench and its sign-in page without
framing or content-type headers, so any site could load the IDE in a hidden
frame and trick a click into it. Both pages now send
`Content-Security-Policy: frame-ancestors 'none'; object-src 'none'; base-uri 'self'`,
`X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff` and
`Referrer-Policy: no-referrer`.
2026-12-06 20:35:51 +08:00
l0ng-ai de95beb345 fix(run): locate passed Django tests from their module names (#8241) 2026-12-06 20:35:42 +08:00
l0ng-ai 5fc201ccf4 fix(python): skip empty semantic recovery nodes (#8328) 2026-12-06 20:35:20 +08:00
l0ng-aiтаrohitdanda c4b2d24d7e fix(core): keep the IDE's temporary files in a folder only this user can open (#8378)
Several features wrote into fixed or guessable names directly under the system
temporary folder, which every user shares on Linux: the terminal's shell
integration scripts, Gradle init scripts, Java argument files, binaries and
classes of single-file runs, jdtls' temporary folder, the TypeScript watch
scratch folder, Claude and Copilot session files, the Android emulator and
Xcode build logs, CPU profiles, `devicectl` output and the throwaway Docker
config. Another local user could create those folders first and have the IDE
user run their code, or read and overwrite the files.

They now all live under `<temp>/openidea-<uid>` (`ide_core::private_temp`),
created owner-only; a name that belongs to someone else or is a symbolic link
is never used, and a folder of a random name takes its place for that run.

Co-authored-by: rohitdanda <[email protected]>
2026-12-06 20:29:20 +08:00
l0ng-ai 6b5008f02e fix(ssh): refuse hosts and users with shell metacharacters (#8377)
`ProxyCommand` and `Match exec` in `~/.ssh/config` run through `sh -c` with
`%h`, `%n` and `%r` substituted as written. A host or user name can come from
a project's files (a data source's SSH tunnel), so one holding `;` or `$(...)`
ran commands on this machine whenever the user's config had such a rule.

Connecting now refuses a host or user that OpenSSH itself refuses on its
command line: a leading `-`, whitespace, control characters or shell
metacharacters (a user may still be `DOMAIN\name`).
2026-12-06 20:14:48 +08:00
l0ng-ai 02e4cafa89 fix(editor): put inline doc tags back into the text of rendered comments only (#8376)
Rendered doc comments replace `{@link}`, `{@code}` and the other inline tags
with placeholders, sanitize the Markdown, then put the tags' HTML back by
string replacement. A placeholder inside an attribute value
(`<img alt="{@link Foo}">`) got that HTML too: its quotes ended the attribute,
and the rest of the comment's markup became attributes the sanitizer never saw.

The tags now go back on the sanitized DOM: into text nodes as their HTML, and
into attribute values as their plain text.
2026-12-06 20:12:39 +08:00
l0ng-ai 871dbd0a55 fix(remote): check trust and grants before a server reads plugin secrets (#8375)
A remote server asks the desktop for plugin secrets, secret writes and OAuth
listeners on behalf of the plugins it runs. The desktop answered for any
installed plugin, enabled or not, and returned a declared secret without a
`secrets` grant, even while the remote project was still in Restricted Mode.

- Secret, secret-write and OAuth requests and plugin events from the server
  are handled only once this machine trusts the remote project.
- They are answered only for plugins the desktop syncs to servers and that are
  enabled; reading a secret also needs the `secrets` grant, as writing one
  already did.
- A server's OAuth wait is capped at ten minutes; a disconnect still ends it.
2026-12-06 20:09:42 +08:00
l0ng-ai f10a584265 fix(vcs): keep commit diff controls outside code selections (#8324)
Revert in the unified diff moves from an inline label into the gutter, so dragging across a change selects only code. In a commit diff the block checkbox and Revert share the first displayed row of each change in fixed slots. Both viewers show a file checkbox beside Current version and report how many changes are included when part or all of the file is excluded.
2026-12-06 20:09:12 +08:00
l0ng-ai 6b0490cc01 test: make the Copilot home and Python rearrange tests pass on Windows (#8321)
The Copilot home test built an absolute path from /home/test, which has no drive on Windows; it now uses a temp directory. The rearrange test rewrote the file with same-length text inside one mtime tick, which the background scan skips; it now moves the mtime forward.
2026-12-06 10:30:17 +08:00
l0ng-ai 2ab6ba4ba9 fix(agents): ask for approval before a plugin's language servers can run (#8318)
A plugin's language server commands (.lsp.json, lsp.json, manifest lspServers) are now part of its executable capabilities and capability hash: listed in the install preview and approval dialog, and approved before they can run. Plugins without language servers keep their hash.
2026-12-06 09:49:14 +08:00
l0ng-ai c2f984720d feat(github): build the pull request comment and review fields on the editor so Vim works in them (#8314)
The pull request timeline and diff-thread comment fields and the Submit Review field use the editor-based TextField the commit message uses, so Vim attaches when Vim mode is on. Escape first leaves Insert or Visual mode, and in Normal mode or with Vim off cancels the comment as before; the @mention list keeps its keys ahead of Vim. TextField gains readOnly, onSelectionChange and onKeyDownFirst.
2026-12-06 08:15:44 +08:00
l0ng-ai 8be62cb895 fix(lsp): drop parameter info on its way when Escape comes before it shows (#8313)
The parameter info requested after accepting a call completion with unknown arguments still appeared when Escape was pressed or the editor left before the server answered, and Escape before an auto-popup showed didn't cancel it. That request now counts as automatic, and Escape cancels pending automatic requests even with no popup shown, without consuming the key.
2026-12-06 08:08:09 +08:00
audichuang 9faaae33ae fix(lsp): keep Parameter Info closed after Escape or leaving the editor (#8305)
Escape on Parameter Info right after typing an argument closed the popup and the debounced refresh of the last keystroke brought it back about 120 ms later; leaving the editor did the same, and the auto-popup still opened on an editor already left. Escape and blur now cancel the pending refresh and auto-popup timer and drop replies to automatic requests sent before that; explicit Parameter Info and typing ( or , again still open it.

Co-authored-by: audichuang <[email protected]>
2026-12-06 08:05:23 +08:00
dependabot[bot] 487ad35181 chore(deps): bump the actions group across 1 directory with 14 updates (#8143)
Bumps the GitHub Actions used by the workflows (checkout, cache, setup-node/java/go/python/dotnet, upload/download-artifact, github-script, pnpm/action-setup, gradle setup, taiki-e/install-action) to their current releases, pinned by commit.
2026-12-06 08:03:41 +08:00
aLiEz 2d11fd484f feat(java): Spring AOP advice gutter icons (#8308)
Java documents show Spring AOP gutter icons: on an advised method, to the advices applied to it; on an advice method, to the methods it advises. One target navigates directly; several open the chooser (Navigate to AOP Advices / Advised Methods), advice rows showing the advice kind and its order when statically known. The backend adds server-independent SpringAopMarker types and lsp_spring_aop_markers, asking only a server attached to the document that declares experimental java-analyzer/springAopMarkers (java-analyzer first; jdtls and older builds are not asked), refreshing on java-analyzer/springAopMarkersChanged. The Spring bean gutter's request/refresh logic moves into a shared lspMarkerGutter driver used by both. fixtures/spring-app gains aspects covering both directions, all advice kinds, named pointcuts, &&/||/! and order.

Co-authored-by: aLIEz1 <[email protected]>
2026-12-06 08:00:23 +08:00
farmer_timmm fe04de3862 fix(syntax): share the memoized outline/folding instead of cloning it (#8309)
SyntaxCache::memoized stored each result behind an Arc but deep-cloned the Vec out of it on every cache hit, which for the outline (a tree of Strings) cost milliseconds on a 2 MB file. memoized now returns the Arc, and outline() and folding() return Arc<Vec<_>>; the two IPC commands that own and extend their result take it out once with Arc::unwrap_or_clone. Results are unchanged; outline_cached_hit went from 4.68 ms to 80 ns and folding_cached_hit from 21.7 µs to 72 ns in the criterion benches.

Co-authored-by: Ttimmahlax <[email protected]>
2026-12-06 07:52:52 +08:00
l0ng-ai 0ca4c7a21b feat(vcs): show the selected file's diff in the Commit dialog (#8312)
The modal commit interface's Commit Changes dialog shows the diff of the file selected in its changes tree below the changes and the message, with the embedded diff viewer used by the Commit tool window's preview. Preview Diff in the tree toolbar hides or shows it (remembered, shown by default); the dialog is larger while it is shown.
2026-12-06 07:48:01 +08:00
l0ng-ai 6324bbb865 fix(project-trust): answer a remote open's trust prompt while the project opens (#8311)
A remote open sets the opening state before it asks Trust and Open Project?, and every action except quitting and window switching is disabled while a project opens, so the prompt's answers were refused and the open hung. Actions gain whileProjectOpens; Trust Project, Preview in Restricted Mode and Don't Open set it.
2026-12-06 07:42:52 +08:00
audichuang 6789f5abc7 test(editor): destroy every focused-cell editor after each focusedCell test (#8301)
Some focusedCell tests never destroyed their focused cell editor, and two cleaned up inside try rather than finally. Focusing a CodeMirror view schedules a 10 ms timer; when the file ended inside it, the timer called requestAnimationFrame on the torn-down jsdom window, failing the Frontend job with an unhandled error. Every cell editor is now destroyed in afterEach.

Co-authored-by: audichuang <[email protected]>
2026-12-06 06:46:34 +08:00
audichuang 6c41918675 fix(build): build WAR artifacts and update Spring Boot resources through Gradle when a build enables Isolated Projects (#8304)
The WAR build for a Tomcat deployment and the Spring Boot resource update looked the module up from the root in projectsEvaluated and registered a task on it, which Isolated Projects rejects. When the build enables it and Gradle is 8.8 or later, each script registers its task on its one target project of the main build from gradle.lifecycle.afterProject (in an afterEvaluate added there); other builds and older Gradle keep projectsEvaluated. The Isolated Projects check is shared in ide-build/src/gradle.rs.

Co-authored-by: audichuang <[email protected]>
2026-12-06 06:45:55 +08:00
audichuang b24b45c2d8 fix(run): run, test, debug and cover through Gradle when a build enables Isolated Projects (#8296)
With org.gradle.isolated-projects=true, running, debugging, testing or covering through Gradle failed: the IDE's init scripts read every project from the root (allprojects, projectsEvaluated), which Isolated Projects rejects. When the build enables it and Gradle is 8.8 or later, the scripts (application run, bootRun, test events/debug, VM options, UTF-8 charset, coverage) configure each project on its own through gradle.lifecycle.beforeProject / afterProject, reading the setting from Gradle's public BuildFeatures; other builds and older Gradle run the previous code.

Co-authored-by: audichuang <[email protected]>
2026-12-06 06:44:25 +08:00
audichuang df03de46ed test(ssh): read the command's line, not the PTY reply, in the remote-folder session test (#8306)
ssh_session_in_a_directory_starts_the_login_shell_there read only up to the first newline, which on Linux is the test server's separate pty 80x24 reply, so it failed there every time. It now reads up to the end of the command's line.

Co-authored-by: audichuang <[email protected]>
2026-12-06 06:41:40 +08:00
Michał DobaczewskiтаMDobak 7a05e2aab0 fix(agents): expand a leading ~ in agent environment values (#8299)
Sessions from other apps stayed empty when Claude Code's environment set CLAUDE_CONFIG_DIR=~/.claude-work: the value was used literally, so transcripts were looked up (and the agent launched) with a folder named ~. A leading ~ in an agent's environment value (alone or before a path separator) is now the user's home, when the agent is launched or signed in and when Claude Code's or Copilot's configuration directory is read. An empty CLAUDE_CONFIG_DIR or COPILOT_HOME counts as unset.

Co-authored-by: MDobak <[email protected]>
2026-12-06 05:30:30 +08:00
audichuang febbff46bd test(settings): wait for the .NET SDK list instead of the unpinned placeholder (#8295)
The .NET settings test waited for the SDK combo to read Not pinned, the placeholder shown before sdkDotnetStatus answers, so it read the SDK list whenever the answer happened to have rendered. It now waits for the list and checks the placeholder after.

Co-authored-by: audichuang <[email protected]>
2026-12-06 05:28:46 +08:00
l0ng-ai e811d633b9 fix(editor): keep the caret on the cut line's number after cutting a whole line (#8303)
Cut without a selection removes the caret line, but the caret was mapped into the line above, so a second Cut removed that line instead of the one that moved up. As IntelliJ's CutHandler does, the caret now goes to the start of the line that takes the cut line's place; after the last line, to the start of the line before it. Multiple carets follow the same rule.
2026-12-06 05:27:39 +08:00
l0ng-ai 7abf1d2ac7 test(vcs): close the blame popup inside act in teardown (#8300)
closeBlamePopup renders null into the popup's React root; called outside act in afterEach, React sometimes ran that work after the test environment was torn down, failing the Frontend job with an unhandled window-is-not-defined error. Both blame test files now close it inside act.
2026-12-06 05:04:48 +08:00
Vadim LazukтаInf1mum ca6efe197c fix(updates): keep the cause chain in updater errors (#8285)
The Update check failed notification showed only reqwest's top-level message (error sending request for url …), hiding what failed, such as a refused connection to a manual HTTP proxy that isn't running. ide_http::client::describe now takes any error and follows its sources, and the update check, the pre-download check and the download request/body reads use it. Endpoints, proxy routing and timeouts are unchanged.

Co-authored-by: Inf1mum <[email protected]>
2026-12-06 05:03:21 +08:00
l0ng-ai bdc4b1ef98 fix(scaffold): use a discovered Go for New Project when none is on PATH (#8298)
New Project › Go still reported go is not installed when GOROOT was on Default and go wasn't on the app's PATH (started from the Dock or Finder), although Settings › Languages › Go lists the Go installs it finds. With no GOROOT chosen and no go on PATH, the wizard now uses the first detected Go install for the requirement check and the generator steps; a go on PATH still wins. Detection runs only for generators that run go.
2026-12-06 04:57:15 +08:00
audichuang b4f4b103c6 fix(scaffold): find the Go chosen in Settings when creating a project (#8269)
New Project › Go said go is not installed and kept Create disabled whenever go wasn't on the login-shell PATH, even with Settings › Languages › Go › GOROOT pointing at a Go: the wizard searched only the host PATH, while Run and gopls use the GOROOT setting. For generators that require go, the requirement check and the generator steps now put <GOROOT>/bin ahead of PATH and set GOROOT, when that GOROOT holds a runnable go.

Co-authored-by: audichuang <[email protected]>
2026-12-06 04:48:50 +08:00
audichuang d592e5e154 fix(vcs): tell a tag from a branch of the same name in the Git Log filter (#8277)
With a tag and a local branch both named release, picking either in the Git Log Branches pane filtered by release, which git resolves to the tag, and the pane highlighted the branch row for both. The filter now takes git's own unambiguous name for the picked ref among the repository's refs (git rev-parse --abbrev-ref=strict): tags/release and heads/release, the full ref when another ref takes those, the plain name otherwise. The pane maps a filter back to the row of the ref git resolves it to; a plain name that is both selects the branch. Renaming a branch also renames a heads/ or refs/heads/ filter.

Co-authored-by: audichuang <[email protected]>
2026-12-06 04:42:59 +08:00
tongkangwangтаchiyanking ad311ce0bb feat(usages): Show Import Statements filter and an icon for Open in Find Tool Window (#8280)
Show Usages and the Find tool window gain the Show Import Statements toggle next to the read/write access filters: a usage on a line that begins an import statement (import ..., from ... import ...) is hidden when it is off. The option defaults to on and persists with read/write; saved settings without it keep showing imports. The popup's Open in Find Tool Window is an icon button with its shortcut in the tooltip. The icon is vendored from intellij-community (Apache-2.0).

Co-authored-by: chiyanking <[email protected]>
2026-12-06 04:36:14 +08:00
l0ng-ai 1806c60a7c feat(vcs): get files from the revision in the Compare tool window (#8292)
A working-tree comparison in the Compare tool window (Branches › Show Diff with Working Tree) now has Get next to Jump to Source: the selected file takes its content from the compared revision after a confirmation, and the list reloads.
2026-12-06 04:34:11 +08:00
l0ng-ai d6067dbd14 fix(scaffold): drop the previous generator's missing-tool warning when another generator is chosen (#8294)
The New Project dialog showed the last generator's requirement check until the next one returned. Check results now carry their generator and only the chosen generator's are shown.
2026-12-06 04:26:24 +08:00
Vadim LazukтаInf1mum d1afd0ae9f feat(vcs): build the commit message field on the editor so Vim works in it (#8283)
The commit message field was a textarea, outside Vim mode, and its Esc always blurred. It is now a reusable editor-based TextField (src/editor/TextField.tsx) carrying the embedded editor contributions, so Vim attaches when Vim mode is on. Margin guide, wrap at margin, subject counter, blank-line inspection, message history, Meta+Enter and the activation focus keep working. Vim claims Escape in a tool window's Vim field outside Normal mode, so Esc leaves Insert or Visual mode before the tool window's Focus Editor runs; in Normal mode Esc moves the focus as before. The field sets data-autofocus before paint and ignores the blur of a view being destroyed. The Commit dialog shares the field.

Co-authored-by: Inf1mum <[email protected]>
2026-12-06 04:25:56 +08:00
l0ng-ai 201ab6f54b fix(vim): run an <Action>(id) mapping made at the : prompt (#8291)
Typed at the : prompt, a mapping to <Action>(id) replayed its right-hand side as keys, typing into the document. The map commands now turn such a right-hand side into the action command rc mappings use.
2026-12-06 04:20:53 +08:00
l0ng-ai ecd8404e66 test(svn): pick a Last Week revision that is last week on any weekday (#8290)
The M10 test dated its revision eight days back, which is two weeks back on a Sunday, so it failed every Sunday. It now uses Wednesday noon of last week.
2026-12-06 04:17:49 +08:00
l0ng-ai e98eb5e755 fix(agents): start a new task with the agent the composer shows after its agent was removed (#8289)
After the selected agent was removed, the composer fell back to the first agent but Start still sent the removed id and failed with "unknown agent". Start and option changes now resolve the agent like the composer.
2026-12-06 04:16:43 +08:00
l0ng-ai c341799768 fix(python): point the Ruff page's both-selected note at Black's setting (#8288)
With Ruff and Black both selected, the Ruff page told users to switch this page back to Automatic, which leaves Black formatting. The note now says to switch Black's formatting provider back to Automatic.
2026-12-06 04:14:27 +08:00
l0ng-ai 69fca0aaa3 fix(diff): compare the Project view's two selected files when Compare Files runs from Find Action (#8287)
Run from Find Action, Compare Files got no argument and asked to select two files even with two selected. It now falls back to the Project view's selection like Compare Directories and rejects a selected directory.
2026-12-06 04:11:37 +08:00
l0ng-ai f8e1705dff fix(color-preview): don't read a property name after an earlier declaration as a color (#8286)
With two declarations on one line, the value check spanned the earlier declaration, so a following property name such as `background` (a deprecated WebKit system color) got a swatch. A `;`, `{` or `}` after the colon now ends the declaration.
2026-12-06 04:04:05 +08:00
audichuang a4394d3ece fix(gradle): list tasks and build when a build enables Isolated Projects (#8279)
With org.gradle.isolated-projects=true the IDE's own Gradle runs (task listing, single-file compile classpath, IDE build step) failed: they force the configuration cache off, which Gradle refuses under Isolated Projects, and their init scripts read every project from the root. When the build's or the Gradle user home's gradle.properties enables it, those runs now pass -Dorg.gradle.isolated-projects=false and the Gradle 8 name too; other builds keep their command line. Run/debug/test init scripts are left for a follow-up that reads each project on its own.

Co-authored-by: audichuang <[email protected]>
2026-12-06 03:46:52 +08:00
audichuang 4021bdd0d1 fix(plugins): ask line markers again after a save of a file their plugin covers (#8272)
A plugin's gutter markers can be built from another file (MyBatis arrows in Mapper.xml come from the Java mapper), but the editor asked line-markers only after its own document changed. A save now asks again, debounced, in the visible editors of the same project root whose language a plugin declares along with the saved file's ("*" covers all); hidden kept tabs ask once shown. plugin_line_marker_languages(path) returns those languages from the usable plugins' declarations without loading plugin code.

Co-authored-by: audichuang <[email protected]>
2026-12-06 03:45:10 +08:00
l0ng-ai 8e8a3f397b feat(deployment): start an SSH session in a Remote Host folder (#8284)
Remote Host's context menu on an SFTP server gains Start SSH Session in Directory: a terminal tab on the server's SSH configuration whose login shell starts in the chosen folder (a file's parent, or the root on empty space). ssh_open_terminal takes an optional remote folder and runs cd -- <folder>; exec "$SHELL" -l, so a missing folder reports the error and leaves the shell in home.
2026-12-06 03:37:57 +08:00
248 змінених файлів з 7284 додано та 1148 видалено

No files matched your search

+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ jobs:
cancel:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
+24 -24
Переглянути файл
@@ -117,7 +117,7 @@ jobs:
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "clippy, rustfmt" }
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
@@ -139,11 +139,11 @@ jobs:
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
with: { tool: nextest }
# ide-sdk's .NET status test and crates/ide-coverage/tests/dotnet_cli.rs run the real `dotnet`
# CLI; with CI set they fail, not skip, when it is missing.
- uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0
- uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
dotnet-version: 10.0.x
- name: Linux deps
@@ -175,7 +175,7 @@ jobs:
- name: Restore Maven artifacts for Java build tests
id: jbuild-maven-cache
if: runner.environment == 'github-hosted'
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-v2-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
@@ -209,13 +209,13 @@ jobs:
exit 1
- name: Save Maven artifacts for Java build tests
if: steps.jbuild-maven.outputs.prepared == 'true'
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
# python_yappi.rs profiles real runs. Self-hosted runners have no setup-python; without
# YAPPI_PYTHON those tests return early.
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
if: runner.environment == 'github-hosted'
id: yappi-python
with: { python-version: "3.12", update-environment: false }
@@ -231,7 +231,7 @@ jobs:
"$venv_py" -m pip install yappi==1.7.6
echo "YAPPI_PYTHON=$venv_py" >> "$GITHUB_ENV"
# python_memray.rs profiles real runs. memray has no Windows build.
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
if: runner.os != 'Windows' && runner.environment == 'github-hosted'
id: memray-python
with: { python-version: "3.12", update-environment: false }
@@ -287,7 +287,7 @@ jobs:
timeout-minutes: 40
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: x86_64-unknown-linux-musl }
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
@@ -318,7 +318,7 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
- if: runner.environment != 'self-hosted'
@@ -354,9 +354,9 @@ jobs:
cargo test --locked --manifest-path "$dir/Cargo.toml"
echo "::endgroup::"
done
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with: { node-version: 22, package-manager-cache: false }
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
- name: Web pages typecheck and test
@@ -383,9 +383,9 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
with: { tool: cargo-deny }
- run: cargo deny check
@@ -396,19 +396,19 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: runner.environment == 'self-hosted'
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
# src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing.
- uses: actions/setup-dotnet@v5
- uses: actions/setup-dotnet@v6
with:
dotnet-version: |
10.0.x
@@ -429,10 +429,10 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -451,10 +451,10 @@ jobs:
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -462,7 +462,7 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm e2e --shard=${{ matrix.shard }}/4
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: failure()
with:
name: playwright-report-${{ matrix.shard }}
+2 -2
Переглянути файл
@@ -36,10 +36,10 @@ jobs:
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.token.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.token.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download release
+3 -3
Переглянути файл
@@ -42,16 +42,16 @@ jobs:
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
path: tap
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
+10 -10
Переглянути файл
@@ -176,7 +176,7 @@ jobs:
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
CARGO_PROFILE_DEV_DEBUG: line-tables-only
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
@@ -205,7 +205,7 @@ jobs:
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
# A tar keeps the executable bits, which artifacts drop.
tar -cf smoke-bin.tar smoke-bin
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
@@ -224,21 +224,21 @@ jobs:
env:
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Tool versions, shared with the evals (pnpm eval).
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- if: contains(matrix.group.languages, 'rust')
uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "rust-analyzer, rustfmt" }
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -264,19 +264,19 @@ jobs:
fi
- if: contains(matrix.group.languages, 'python')
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with: { python-version: "3.12" }
- if: contains(matrix.group.languages, 'python')
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
- if: contains(matrix.group.languages, 'go')
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with: { go-version: "1.27", cache: false }
- if: contains(matrix.group.languages, 'go')
run: go install "golang.org/x/tools/gopls@$GOPLS"
- if: contains(matrix.group.languages, 'java') || contains(matrix.group.languages, 'kotlin')
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: contains(matrix.group.languages, 'java')
run: |
@@ -288,7 +288,7 @@ jobs:
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
- if: contains(matrix.group.languages, 'kotlin')
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
with:
gradle-version: "${{ env.GRADLE }}"
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
+2 -2
Переглянути файл
@@ -30,7 +30,7 @@ jobs:
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: { ref: main, fetch-depth: 0 }
- id: changed
env:
@@ -41,7 +41,7 @@ jobs:
echo "::notice::main has not changed since $last"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.changed.outputs.skip != 'true'
with: { node-version: 22 }
- name: Version commit and tag
+1 -1
Переглянути файл
@@ -18,7 +18,7 @@ jobs:
if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
const pr = context.payload.pull_request;
+8 -8
Переглянути файл
@@ -72,11 +72,11 @@ jobs:
target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
with: { node-version: 22, cache: pnpm }
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
@@ -198,7 +198,7 @@ jobs:
- { runner: macos-latest, target: x86_64-apple-darwin, os: macos, arch: x86_64 }
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
@@ -238,13 +238,13 @@ jobs:
env:
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
run: echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.signing.outputs.updater == 'true'
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
if: steps.signing.outputs.updater == 'true'
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.signing.outputs.updater == 'true'
with: { node-version: 22, cache: pnpm }
- if: steps.signing.outputs.updater == 'true'
@@ -270,7 +270,7 @@ jobs:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
RELEASE_ID: ${{ inputs.release_id }}
with:
+6 -6
Переглянути файл
@@ -37,7 +37,7 @@ jobs:
outputs:
release_id: ${{ steps.release.outputs.id }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: { ref: "${{ env.TAG }}" }
- name: Tag matches app version
run: |
@@ -57,7 +57,7 @@ jobs:
exit 1
fi
- id: release
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
NIGHTLY: ${{ inputs.nightly == true }}
with:
@@ -126,7 +126,7 @@ jobs:
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.key.outputs.skip != 'true'
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
@@ -135,10 +135,10 @@ jobs:
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: steps.key.outputs.skip != 'true'
with: { key: release-plugins }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
if: steps.key.outputs.skip != 'true'
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0
if: steps.key.outputs.skip != 'true'
with: { node-version: 22 }
# Builds the web pages; fails when a checked-in component isn't built from these sources.
@@ -183,7 +183,7 @@ jobs:
needs: [create-release, binaries, plugins]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
with:
+5
Переглянути файл
@@ -75,6 +75,11 @@ The read/write usage filter assets (`actions/showReadAccess{,_dark}.svg` and
[`e992ff4750b4c36afe2caadfa8b191a8f36fb7a2`](https://github.com/JetBrains/intellij-community/tree/e992ff4750b4c36afe2caadfa8b191a8f36fb7a2/platform/icons/src/expui/actions).
Their original copyright headers and Apache-2.0 licensing are retained.
The `actions/showImportStatements{,_dark}.svg` asset is copied unmodified from
`platform/icons/src/expui/actions/` at intellij-community commit
[`71290c3174`](https://github.com/JetBrains/intellij-community/tree/71290c3174/platform/icons/src).
Its original copyright headers and Apache-2.0 licensing are retained.
- [intellij-rust](https://github.com/intellij-rust/intellij-rust) (MIT):
`src/main/resources/icons/expui/rustFile{,_dark}.svg` →
`src/ui/expui/fileTypes/rust{,_dark}.svg`;
+4 -1
Переглянути файл
@@ -1574,6 +1574,9 @@ pub struct AgentPluginCapabilities {
pub hook_files: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stdio_commands: Vec<String>,
/// Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub lsp_commands: Vec<String>,
#[serde(default)]
pub has_lsp: bool,
#[serde(default)]
@@ -1581,7 +1584,7 @@ pub struct AgentPluginCapabilities {
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub native_harnesses: Vec<String>,
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands`, `lsp_commands` and `hook_files` contents).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub capability_hash: Option<String>,
+20 -4
Переглянути файл
@@ -134,13 +134,14 @@ impl Cli for Process {
}
}
/// Claude Code's configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`).
/// Claude Code's configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`); an empty value counts as
/// unset, and a leading `~` is the user's home.
pub(crate) fn config_dir(env: &[(String, String)]) -> Option<PathBuf> {
let set = env
.iter()
.find(|(k, _)| k == "CLAUDE_CONFIG_DIR")
.map(|(_, v)| PathBuf::from(v))
.or_else(|| std::env::var_os("CLAUDE_CONFIG_DIR").map(PathBuf::from));
.find(|(k, v)| k == "CLAUDE_CONFIG_DIR" && !v.is_empty())
.map(|(_, v)| PathBuf::from(crate::provider::expand_home(v)))
.or_else(|| std::env::var_os("CLAUDE_CONFIG_DIR").filter(|v| !v.is_empty()).map(PathBuf::from));
set.or_else(|| {
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(|h| Path::new(&h).join(".claude"))
})
@@ -160,4 +161,19 @@ mod tests {
"--resume a --fork-session --session-id b"
);
}
#[test]
fn an_empty_config_dir_is_unset() {
let dir = config_dir(&[("CLAUDE_CONFIG_DIR".into(), String::new())]);
assert!(dir.is_some_and(|d| d.is_absolute()));
let set = config_dir(&[("CLAUDE_CONFIG_DIR".into(), "/home/me/.claude-work".into())]);
assert_eq!(set, Some(PathBuf::from("/home/me/.claude-work")));
}
#[test]
fn a_config_dir_under_the_home_folder_can_start_with_a_tilde() {
let home = crate::home_dir().unwrap();
let dir = config_dir(&[("CLAUDE_CONFIG_DIR".into(), "~/.claude-work".into())]);
assert_eq!(dir, Some(home.join(".claude-work")));
}
}
+4 -4
Переглянути файл
@@ -3,9 +3,9 @@
//!
//! Each ACP session runs its own `claude` process, whose session id is the ACP one.
//! The CLI writes a session's transcript only once it has a message, so a fork or an
//! undo that has not been prompted yet is kept as a pending start (`<temp>/openidea-claude/
//! <id>.json`): loading that session, from this connection or a fresh one, starts it that
//! way.
//! undo that has not been prompted yet is kept as a pending start (`claude/<id>.json` in this
//! user's temporary folder, `ide_core::private_temp`): loading that session, from this
//! connection or a fresh one, starts it that way.
pub(crate) mod cli;
pub(crate) mod history;
@@ -62,7 +62,7 @@ pub(crate) fn connect(
args: spec.args.clone(),
env: spec.env.clone(),
config_dir: cli::config_dir(&spec.env),
pending_dir: std::env::temp_dir().join("openidea-claude"),
pending_dir: ide_core::private_temp::dir("claude")?,
cwd: cwd.to_path_buf(),
};
let shim = Shim::new(config, Arc::new(cli::Process), Arc::from(on_stderr));
+6 -6
Переглянути файл
@@ -37,12 +37,13 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
const EARLY_CANCEL: Duration = Duration::from_secs(2);
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`); an empty value counts as
/// unset, and a leading `~` is the user's home.
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
env.iter()
.find(|(key, _)| key == "COPILOT_HOME")
.map(|(_, value)| PathBuf::from(value))
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
.find(|(key, value)| key == "COPILOT_HOME" && !value.is_empty())
.map(|(_, value)| PathBuf::from(crate::provider::expand_home(value)))
.or_else(|| std::env::var_os("COPILOT_HOME").filter(|v| !v.is_empty()).map(PathBuf::from))
.or_else(|| home.map(|home| home.join(".copilot")))
}
@@ -1403,8 +1404,7 @@ fn write_temp_image(session_id: &str, mime: &str, base64_data: &str) -> Option<P
if bytes.is_empty() {
return None;
}
let dir = std::env::temp_dir().join("openidea-copilot");
std::fs::create_dir_all(&dir).ok()?;
let dir = ide_core::private_temp::dir("copilot").ok()?;
let safe_sid: String = session_id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
let file = dir.join(format!("{safe_sid}-{}.{ext}", uuid::Uuid::new_v4().simple()));
std::fs::write(&file, &bytes).ok()?;
+13 -1
Переглянути файл
@@ -117,14 +117,26 @@ fn sample_price_units() -> Value {
#[test]
fn resolves_copilot_home_from_agent_env_or_user_home() {
let home = std::path::Path::new("/home/test");
// Absolute on every platform: `/home/test` has no drive on Windows.
let home_dir = std::env::temp_dir().join("copilot-home-test");
let home = home_dir.as_path();
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
Some(std::path::Path::new("/custom/copilot"))
);
if std::env::var_os("COPILOT_HOME").is_none() {
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), String::new())], Some(home)),
Some(home.join(".copilot"))
);
}
assert!(super::config_dir(&[("COPILOT_HOME".into(), String::new())], Some(home)).is_some_and(|d| d.is_absolute()));
let user_home = crate::home_dir().unwrap();
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), "~/.copilot-work".into())], Some(home)),
Some(user_home.join(".copilot-work"))
);
}
#[test]
+145 -4
Переглянути файл
@@ -2203,13 +2203,15 @@ fn inspect_fetched_subtree(
}
skill_names.sort();
skill_names.dedup();
let ExecutableCapabilities { mcp_names, stdio_commands, hook_files, capability_hash, .. } = executable;
let ExecutableCapabilities { mcp_names, stdio_commands, lsp_commands, hook_files, capability_hash, .. } =
executable;
if formats.is_empty()
&& skill_names.is_empty()
&& mcp_names.is_empty()
&& rule_count == 0
&& hook_files.is_empty()
&& lsp_commands.is_empty()
&& subagent_count == 0
&& command_count == 0
{
@@ -2241,6 +2243,7 @@ fn inspect_fetched_subtree(
command_count,
hook_files,
stdio_commands,
lsp_commands,
has_lsp,
has_canvas_or_app,
native_harnesses: native_harnesses.into_iter().collect(),
@@ -2337,6 +2340,7 @@ impl PluginFiles for DiskPluginFiles<'_> {
struct ExecutableCapabilities {
mcp_names: BTreeSet<String>,
stdio_commands: Vec<String>,
lsp_commands: Vec<String>,
hook_files: Vec<String>,
hook_harnesses: BTreeSet<String>,
capability_hash: Option<String>,
@@ -2345,6 +2349,7 @@ struct ExecutableCapabilities {
fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabilities {
let mut mcp_names = BTreeSet::new();
let mut stdio_commands = BTreeSet::new();
let mut lsp_commands = BTreeSet::new();
let mut hook_files = BTreeSet::new();
let mut hook_harnesses = BTreeSet::new();
let mut hook_contents: BTreeMap<String, Vec<u8>> = BTreeMap::new();
@@ -2369,6 +2374,9 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil
if let Some(mcp) = manifest.get("mcpServers") {
collect_in_memory_mcp_summary(mcp, files, &mut mcp_names, &mut stdio_commands);
}
if let Some(lsp) = manifest.get("lspServers") {
collect_lsp_commands(lsp, files, &mut lsp_commands, &mut HashSet::new());
}
let (paths, objects) = manifest_hook_declarations(rel, &manifest);
for path in paths {
add_hook_file(path, &mut hook_contents);
@@ -2382,6 +2390,13 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil
collect_in_memory_mcp_summary(&value, files, &mut mcp_names, &mut stdio_commands);
}
}
for rel in [".lsp.json", "lsp.json"] {
if let Some(bytes) = files.read(rel)
&& let Ok(value) = parse_jsonc(&String::from_utf8_lossy(&bytes))
{
collect_lsp_commands(&value, files, &mut lsp_commands, &mut HashSet::new());
}
}
for (label, bytes) in inline_hooks {
hook_files.insert(label.clone());
hook_contents.insert(label, bytes);
@@ -2400,12 +2415,14 @@ fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabil
}
}
let stdio_commands: Vec<String> = stdio_commands.into_iter().collect();
let lsp_commands: Vec<String> = lsp_commands.into_iter().collect();
let digests: Vec<(&str, &[u8])> =
hook_contents.iter().map(|(rel, bytes)| (rel.as_str(), bytes.as_slice())).collect();
let capability_hash = compute_capability_hash(&stdio_commands, &digests);
let capability_hash = compute_capability_hash(&stdio_commands, &lsp_commands, &digests);
ExecutableCapabilities {
mcp_names,
stdio_commands,
lsp_commands,
hook_files: hook_files.into_iter().collect(),
hook_harnesses,
capability_hash,
@@ -2478,6 +2495,59 @@ fn collect_in_memory_mcp_summary_inner(
}
}
/// `name: command args env:K=V` for each language server a `.lsp.json` file, a manifest's
/// `lspServers` value (an object, a path to such a file, or a list of either) declares.
fn collect_lsp_commands(
val: &Value,
files: &dyn PluginFiles,
out: &mut BTreeSet<String>,
visited_files: &mut HashSet<String>,
) {
match val {
Value::String(rel) => {
let clean = rel.trim().trim_start_matches("./").trim_start_matches('/');
if visited_files.insert(clean.to_owned())
&& let Some(bytes) = files.read(clean)
&& let Ok(parsed) = parse_jsonc(&String::from_utf8_lossy(&bytes))
{
collect_lsp_commands(&parsed, files, out, visited_files);
}
}
Value::Array(items) => {
for item in items {
collect_lsp_commands(item, files, out, visited_files);
}
}
Value::Object(obj) => {
if let Some(nested) = obj.get("lspServers") {
collect_lsp_commands(nested, files, out, visited_files);
return;
}
for (name, entry) in obj {
let Some(cmd) = entry.get("command").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
else {
continue;
};
let mut parts = vec![cmd.to_owned()];
parts.extend(extract_string_array(entry.get("args")));
let env = entry
.get("env")
.and_then(Value::as_object)
.into_iter()
.flatten()
.map(|(key, value)| format!("{}={}", key, scalar_capability_value(value)))
.collect::<Vec<_>>()
.join(" ");
if !env.is_empty() {
parts.push(format!("env:{env}"));
}
out.insert(format!("{name}: {}", parts.join(" ")));
}
}
_ => {}
}
}
fn scalar_capability_value(value: &Value) -> String {
match value {
Value::String(value) => value.clone(),
@@ -2746,6 +2816,7 @@ pub fn inspect_plugin_dir(
&& mcp_names.is_empty()
&& rule_files.is_empty()
&& hook_rel_names.is_empty()
&& executable.lsp_commands.is_empty()
&& subagent_count == 0
&& command_count == 0)
{
@@ -2803,6 +2874,7 @@ pub fn inspect_plugin_dir(
command_count,
hook_files: hook_rel_names,
stdio_commands: executable.stdio_commands,
lsp_commands: executable.lsp_commands,
has_lsp,
has_canvas_or_app,
native_harnesses: native_harnesses.into_iter().collect(),
@@ -2815,8 +2887,12 @@ pub fn inspect_plugin_dir(
})
}
fn compute_capability_hash(stdio_commands: &[String], hooks: &[(&str, &[u8])]) -> Option<String> {
if stdio_commands.is_empty() && hooks.is_empty() {
fn compute_capability_hash(
stdio_commands: &[String],
lsp_commands: &[String],
hooks: &[(&str, &[u8])],
) -> Option<String> {
if stdio_commands.is_empty() && lsp_commands.is_empty() && hooks.is_empty() {
return None;
}
let mut hasher = blake3::Hasher::new();
@@ -2828,6 +2904,14 @@ fn compute_capability_hash(stdio_commands: &[String], hooks: &[(&str, &[u8])]) -
hasher.update(cmd.as_bytes());
hasher.update(b"\0");
}
// Only added when present, so the hash of a plugin without language servers stays as approved before.
let mut sorted_lsp = lsp_commands.to_vec();
sorted_lsp.sort();
for cmd in sorted_lsp {
hasher.update(b"lsp:");
hasher.update(cmd.as_bytes());
hasher.update(b"\0");
}
for (rel, bytes) in hooks {
hasher.update(b"hook:");
hasher.update(rel.as_bytes());
@@ -5682,6 +5766,63 @@ mod tests {
assert!(codex_text.contains("https://github.com/acme/plugins.git"));
}
#[test]
fn language_servers_a_plugin_ships_need_execution_consent() {
let tmp = tempfile::tempdir().unwrap();
// A `.lsp.json` file, an inline `lspServers` object and a path to one in the manifest.
let file = tmp.path().join("lsp-file");
write(&file.join(".claude-plugin/plugin.json"), r#"{"name":"lsp-file","version":"1.0.0"}"#);
write(&file.join(".lsp.json"), r#"{"go":{"command":"/bin/sh","args":["-c","touch /tmp/x"]}}"#);
let inline = tmp.path().join("lsp-inline");
write(
&inline.join(".claude-plugin/plugin.json"),
r#"{"name":"lsp-inline","lspServers":{"py":{"command":"pyright-langserver","args":["--stdio"],"env":{"A":"1"}}}}"#,
);
let linked = tmp.path().join("lsp-linked");
write(&linked.join(".claude-plugin/plugin.json"), r#"{"name":"lsp-linked","lspServers":"./servers.json"}"#);
write(&linked.join("servers.json"), r#"{"rs":{"command":"rust-analyzer"}}"#);
let cases = [
(&file, "go: /bin/sh -c touch /tmp/x"),
(&inline, "py: pyright-langserver --stdio env:A=1"),
(&linked, "rs: rust-analyzer"),
];
for (dir, command) in cases {
let installed = inspect_plugin_dir(dir, AgentPluginSource::ClaudeUser, McpScope::User, None, true)
.unwrap()
.capabilities;
let scanned = scan_local_subtree(dir, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin").unwrap();
let preview = inspect_fetched_subtree(&scanned, "plugin", None).unwrap().capabilities;
for caps in [&installed, &preview] {
assert_eq!(caps.lsp_commands, vec![command.to_owned()], "{}", dir.display());
assert!(caps.requires_consent, "{}", dir.display());
assert!(caps.capability_hash.is_some());
}
// The install dialog's approval matches the hash of the installed folder.
assert_eq!(installed.capability_hash, preview.capability_hash);
}
// Changing the server command invalidates an earlier approval.
let before = inspect_plugin_dir(&file, AgentPluginSource::ClaudeUser, McpScope::User, None, true).unwrap();
write(&file.join(".lsp.json"), r#"{"go":{"command":"gopls"}}"#);
let after = inspect_plugin_dir(&file, AgentPluginSource::ClaudeUser, McpScope::User, None, true).unwrap();
assert_ne!(before.capabilities.capability_hash, after.capabilities.capability_hash);
// A plugin without language servers keeps its hash: approvals given before stay valid.
let mut v1 = blake3::Hasher::new();
v1.update(b"openidea-agent-plugin-caps-v1\0mcp:k8s: npx -y k8s-mcp\0");
assert_eq!(
compute_capability_hash(&["k8s: npx -y k8s-mcp".to_owned()], &[], &[]),
Some(v1.finalize().to_hex().to_string())
);
let skills_only = tmp.path().join("skills-only");
write(&skills_only.join(".claude-plugin/plugin.json"), r#"{"name":"skills-only"}"#);
write(&skills_only.join("skills/a/SKILL.md"), "---\nname: a\ndescription: A\n---\n");
let caps = inspect_plugin_dir(&skills_only, AgentPluginSource::ClaudeUser, McpScope::User, None, true)
.unwrap()
.capabilities;
assert!(caps.lsp_commands.is_empty() && !caps.requires_consent && caps.capability_hash.is_none());
}
#[test]
fn marketplace_browse_preview_and_pinned_native_install_roundtrip() {
let tmp = tempfile::tempdir().unwrap();
+33 -1
Переглянути файл
@@ -194,6 +194,9 @@ impl ProviderSpec {
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
for (_, value) in &mut self.env {
*value = expand_home(value);
}
if let Some(program) = self.managed_cli.take() {
self.command = program;
} else if self.driver != Driver::Acp {
@@ -235,7 +238,7 @@ impl ProviderSpec {
return Some(LoginLaunch {
program,
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
env: self.env.iter().cloned().collect(),
env: self.env.iter().map(|(name, value)| (name.clone(), expand_home(value))).collect(),
});
}
@@ -1201,6 +1204,21 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
specs
}
/// `value` with a leading `~` (alone or before a path separator) replaced by the user's home,
/// as a shell does for `NAME=~/path`.
pub(crate) fn expand_home(value: &str) -> String {
let rest = match value.strip_prefix('~') {
Some("") => "",
Some(rest) if rest.starts_with('/') || rest.starts_with('\\') => &rest[1..],
_ => return value.to_owned(),
};
match crate::home_dir() {
Some(home) if rest.is_empty() => home.to_string_lossy().into_owned(),
Some(home) => home.join(rest).to_string_lossy().into_owned(),
None => value.to_owned(),
}
}
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
#[cfg(test)]
pub(crate) fn installed(command: &str) -> bool {
@@ -1647,6 +1665,20 @@ mod tests {
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
#[test]
fn a_leading_tilde_in_the_environment_is_the_home_folder() {
let home = crate::home_dir().unwrap();
let mut spec = builtin_spec("claude").unwrap();
for (name, value) in [("A", "~/.claude-work"), ("B", "~"), ("C", "a~/b"), ("D", "~user/x"), ("E", "/abs")] {
spec.env.push((name.into(), value.into()));
}
let resolved = spec.resolve_for_launch(Path::new("."));
let value = |name: &str| resolved.env.iter().find(|(n, _)| n == name).map(|(_, v)| v.clone()).unwrap();
assert_eq!(value("A"), home.join(".claude-work").to_string_lossy());
assert_eq!(value("B"), home.to_string_lossy());
assert_eq!((value("C"), value("D"), value("E")), ("a~/b".into(), "~user/x".into(), "/abs".into()));
}
#[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -116,7 +116,7 @@ pub fn launch_emulator(avd: &str) -> IdeResult<()> {
fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
let log_path = ide_core::private_temp::dir("android")?.join(format!("emulator-{name}.log"));
let log = std::fs::File::create(&log_path)?;
let mut cmd = Command::new(emulator);
cmd.arg("-avd").arg(avd);
+45 -5
Переглянути файл
@@ -49,9 +49,8 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
&script,
format!(
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
{}
def register = {{ p ->
def update = {{ t ->
t.dependsOn 'processResources'
// Resolved here so the action holds no task or project (configuration cache).
@@ -63,9 +62,14 @@ gradle.projectsEvaluated {{
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update)
else p.tasks.create('openideaUpdateResources', update)
}}
// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`; init scripts also
// run in included builds, which may have a project at the same path.
if (isolated) gradle.lifecycle.afterProject {{ p -> if (p.path == {path} && p.gradle.parent == null) p.afterEvaluate {{ register(p) }} }}
else gradle.projectsEvaluated {{ register(gradle.rootProject.project({path})) }}
"#,
literal(&p.path),
literal(&manifest.to_string_lossy())
crate::gradle::ISOLATED_PROJECTS_SCRIPT,
literal(&manifest.to_string_lossy()),
path = literal(&p.path),
),
)?;
return Ok(ResourceBuild {
@@ -204,6 +208,42 @@ mod tests {
assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
}
/// The resource-update task's init script on a real Gradle, with and without Isolated Projects (#8261).
#[test]
fn gradle_resources_update_with_and_without_isolated_projects() {
let Some((gradle, version)) = crate::gradle::test_gradle() else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let builds = crate::gradle::write_test_builds(
&base,
// The build realizes tasks early and moves the resources in `afterEvaluate`.
"plugins { id 'java' }\ntasks.all {}\nafterEvaluate { sourceSets.main.output.resourcesDir = file('build/custom') }\n",
"plugins { java }\ntasks.all {}\nafterEvaluate { sourceSets[\"main\"].output.setResourcesDir(file(\"build/custom\")) }\n",
&[("src/main/resources/static/index.html", "after")],
);
for (root, isolated) in builds {
// Before Gradle 8.8 the script keeps reading the project from the root, as before.
if isolated && version < (8, 8) {
continue;
}
let cache = root.join("cache");
let mut model = crate::load(&root, &cache, None);
model.gradle[0].command = gradle.to_string_lossy().into_owned();
for pass in if isolated { &["miss", "hit"][..] } else { &["run"][..] } {
let plan = plan(&root, &model, Path::new("app"), &cache).unwrap();
let out = crate::gradle::run_test_gradle(&root, &plan.cwd, &plan.command, &plan.args)
.unwrap_or_else(|e| panic!("{pass}:\n{e}"));
assert_eq!(out.contains("Reusing configuration cache."), *pass == "hit", "{out}");
let dir = fs::read_to_string(cache.join("resource-output.txt")).unwrap();
assert_eq!(Path::new(&dir), root.join("app/build/custom"));
assert_eq!(fs::read_to_string(Path::new(&dir).join("static/index.html")).unwrap(), "after");
}
}
}
#[test]
fn publishes_maven_and_gradle_resource_outputs_to_the_runtime_classpath() {
for layout in ["target/classes", "build/resources/main", "custom resource output"] {
+5 -6
Переглянути файл
@@ -603,17 +603,16 @@ pub fn gradle_compile_file_plan(
fs::create_dir_all(cache)?;
let init_script = cache.join("gradle-compile-cp.init.gradle");
fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
let args = vec![
"--console=plain".into(),
"-q".into(),
"-Dorg.gradle.configuration-cache=false".into(),
let gradle_dir = subdir(root, &gradle.dir);
let mut args = vec!["--console=plain".into(), "-q".into(), "-Dorg.gradle.configuration-cache=false".into()];
args.extend(crate::gradle::no_isolated_projects(&gradle_dir, &gradle.env));
args.extend([
"--init-script".into(),
init_script.to_string_lossy().into_owned(),
format!("-Popenidea.target={}", project.path),
format!("-Popenidea.scope={scope}"),
"help".into(),
];
let gradle_dir = subdir(root, &gradle.dir);
]);
let mut reported: Option<String> = None;
let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
+2 -5
Переглянути файл
@@ -213,11 +213,8 @@ impl Scratch {
use std::hash::{Hash, Hasher};
let mut hash = std::collections::hash_map::DefaultHasher::new();
config.hash(&mut hash);
let dir = std::env::temp_dir().join("openidea-tsc-watch").join(format!(
"{}-{:016x}",
std::process::id(),
hash.finish()
));
let dir =
ide_core::private_temp::dir("tsc-watch")?.join(format!("{}-{:016x}", std::process::id(), hash.finish()));
// Fresh: a `.tsbuildinfo` left by an earlier run would make tsc skip unchanged projects.
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir)?;
+170
Переглянути файл
@@ -12,6 +12,65 @@ use std::time::{Duration, Instant};
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
const ISOLATED_PROJECTS: [&str; 2] = ["org.gradle.isolated-projects", "org.gradle.unsafe.isolated-projects"];
/// Arguments turning Isolated Projects off for the IDE's own model reads of the build at `dir`, when
/// the build enables it: Gradle refuses them without the configuration cache, and their init scripts
/// read projects across the build. Other builds keep their command line. Gradle 9 still reads the
/// Gradle 8 name.
pub(crate) fn no_isolated_projects(dir: &Path, env: &BTreeMap<String, String>) -> Vec<String> {
// The variable as the Gradle process gets it: the project's and the login shell's environment too.
let inherited = ide_core::process::host_vars_in(dir)
.chain(ide_core::process::shell_env_in(dir))
.find(|(key, _)| key == "GRADLE_USER_HOME")
.map(|(_, value)| value);
let home = user_home(dir, env, inherited, dirs::home_dir());
if !isolated_projects(dir, home.as_deref()) {
return Vec::new();
}
ISOLATED_PROJECTS.iter().map(|key| format!("-D{key}=false")).collect()
}
fn user_home(
dir: &Path,
env: &BTreeMap<String, String>,
inherited: Option<std::ffi::OsString>,
home: Option<PathBuf>,
) -> Option<PathBuf> {
let set = env.get("GRADLE_USER_HOME").map(PathBuf::from).or_else(|| inherited.map(PathBuf::from));
set.map(|path| dir.join(path)).or_else(|| Some(home?.join(".gradle")))
}
/// The user home's `gradle.properties` overrides the build's; when the two names disagree, Gradle
/// keeps Isolated Projects off.
fn isolated_projects(dir: &Path, user_home: Option<&Path>) -> bool {
let user = user_home.map(file_properties).unwrap_or_default();
let build = file_properties(dir);
let values: Vec<bool> = ISOLATED_PROJECTS
.iter()
.filter_map(|key| user.get(*key).or_else(|| build.get(*key)))
.map(|value| value.eq_ignore_ascii_case("true"))
.collect();
values.contains(&true) && !values.contains(&false)
}
/// Groovy for init scripts that add a task to one project (needs `GradleVersion` imported): `isolated`
/// is whether the build enables Isolated Projects on Gradle 8.8+, where such a script must register
/// it from `gradle.lifecycle` instead of reading the project from the root. `BuildFeatures` (8.5+) is
/// only injected, so a class compiled at run time reads it.
pub(crate) const ISOLATED_PROJECTS_SCRIPT: &str = r#"def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
"#;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -1125,6 +1184,70 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
script.split(|c: char| !c.is_alphanumeric() && c != '_').any(|word| word == "war")
}
/// A real Gradle for tests (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path) and its
/// version as (major, minor); `None` without it or without `JAVA_HOME`.
#[cfg(test)]
pub(crate) fn test_gradle() -> Option<(PathBuf, (u32, u32))> {
std::env::var_os("JAVA_HOME")?;
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 out = std::process::Command::new(&gradle).arg("--version").output().ok()?;
let text = String::from_utf8_lossy(&out.stdout).into_owned();
let version = text.lines().find_map(|l| l.strip_prefix("Gradle "))?.trim().to_owned();
let mut parts = version.split('.').map(|p| p.parse::<u32>().unwrap_or(0));
Some((gradle.clone(), (parts.next()?, parts.next().unwrap_or(0))))
}
/// Runs a planned Gradle command in `root`; its output, or the failure with it.
#[cfg(test)]
pub(crate) fn run_test_gradle(root: &Path, cwd: &str, command: &str, args: &[String]) -> Result<String, String> {
let out = std::process::Command::new(command).args(args).current_dir(root.join(cwd)).output().unwrap();
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
if out.status.success() { Ok(text) } else { Err(text) }
}
/// Two builds for init-script tests, each with `files` under `app`: one in the Groovy DSL without
/// Isolated Projects, one in the Kotlin DSL with it (and so the configuration cache).
#[cfg(test)]
pub(crate) fn write_test_builds(
base: &Path,
groovy: &str,
kotlin: &str,
files: &[(&str, &str)],
) -> [(PathBuf, bool); 2] {
let plain = base.join("plain");
let isolated = base.join("isolated");
let mut all = vec![
(plain.join("gradle.properties"), "org.gradle.daemon=false\n".to_owned()),
(plain.join("settings.gradle"), "rootProject.name = 'plain'\ninclude 'app'\n".to_owned()),
(plain.join("app/build.gradle"), groovy.to_owned()),
(
isolated.join("gradle.properties"),
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\n\
org.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n"
.to_owned(),
),
(
isolated.join("settings.gradle.kts"),
"rootProject.name = \"isolated\"\ninclude(\"app\")\nincludeBuild(\"inc\")\n".to_owned(),
),
// An included build with a project at the same path, whose tasks are realized early.
(isolated.join("inc/settings.gradle.kts"), "rootProject.name = \"inc\"\ninclude(\"app\")\n".to_owned()),
(isolated.join("inc/app/build.gradle.kts"), "plugins { java }\ntasks.all {}\n".to_owned()),
(isolated.join("app/build.gradle.kts"), kotlin.to_owned()),
];
for (rel, text) in files {
all.push((plain.join("app").join(rel), text.to_string()));
all.push((isolated.join("app").join(rel), text.to_string()));
}
for (path, text) in all {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
[(plain, false), (isolated, true)]
}
#[cfg(test)]
mod tests {
#[test]
@@ -1578,6 +1701,53 @@ dependencies {
use super::*;
#[test]
fn isolated_projects_are_read_from_the_build_and_the_user_home() {
let temp = tempfile::tempdir().unwrap();
let (build, home) = (temp.path().join("build"), temp.path().join("home"));
std::fs::create_dir_all(&build).unwrap();
std::fs::create_dir_all(&home).unwrap();
let enabled = |user_home: Option<&Path>| isolated_projects(&build, user_home);
assert!(!enabled(Some(&home)), "no gradle.properties");
std::fs::write(build.join("gradle.properties"), "org.gradle.jvmargs=-Xmx2g\n").unwrap();
assert!(!enabled(Some(&home)), "not enabled");
std::fs::write(build.join("gradle.properties"), "org.gradle.isolated-projects=true\n").unwrap();
assert!(enabled(Some(&home)), "the build's gradle.properties");
assert!(enabled(None));
std::fs::write(home.join("gradle.properties"), "org.gradle.isolated-projects=false\n").unwrap();
assert!(!enabled(Some(&home)), "the user home overrides the build");
std::fs::write(build.join("gradle.properties"), "").unwrap();
std::fs::write(home.join("gradle.properties"), "org.gradle.unsafe.isolated-projects = true\n").unwrap();
assert!(enabled(Some(&home)), "the user home's gradle.properties, Gradle 8 name");
std::fs::write(build.join("gradle.properties"), "org.gradle.isolated-projects=false\n").unwrap();
assert!(!enabled(Some(&home)), "disabled under either name wins");
}
#[test]
fn the_gradle_user_home_is_the_builds_setting_then_the_environment_then_dot_gradle() {
let dir = Path::new("/build");
let env = BTreeMap::from([("GRADLE_USER_HOME".to_owned(), "/setting".to_owned())]);
let inherited = || Some(std::ffi::OsString::from("/inherited"));
let home = || Some(PathBuf::from("/home/u"));
assert_eq!(user_home(dir, &env, inherited(), home()), Some(PathBuf::from("/setting")));
assert_eq!(user_home(dir, &BTreeMap::new(), inherited(), home()), Some(PathBuf::from("/inherited")));
assert_eq!(user_home(dir, &BTreeMap::new(), None, home()), Some(PathBuf::from("/home/u/.gradle")));
let relative = Some(std::ffi::OsString::from("gradle-home"));
assert_eq!(user_home(dir, &BTreeMap::new(), relative, home()), Some(PathBuf::from("/build/gradle-home")));
}
#[test]
fn builds_without_isolated_projects_keep_their_command_line() {
let temp = tempfile::tempdir().unwrap();
let env = BTreeMap::from([("GRADLE_USER_HOME".to_owned(), temp.path().join("home").display().to_string())]);
assert!(no_isolated_projects(temp.path(), &env).is_empty());
std::fs::write(temp.path().join("gradle.properties"), "org.gradle.isolated-projects=true\n").unwrap();
assert_eq!(
no_isolated_projects(temp.path(), &env),
["-Dorg.gradle.isolated-projects=false", "-Dorg.gradle.unsafe.isolated-projects=false"]
);
}
#[test]
fn settings_scripts() {
let kts = r#"
+1
Переглянути файл
@@ -300,6 +300,7 @@ pub(super) fn gradle_step(
&["--console=plain", "--no-configuration-cache"],
&subdir(root, &g.dir),
);
step.args.extend(crate::gradle::no_isolated_projects(&step.cwd, &g.env));
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 {
+16
Переглянути файл
@@ -792,6 +792,22 @@ fn builds_gradle_projects_with_javac_and_only_what_changed() {
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
}
#[test]
fn builds_gradle_projects_that_enable_isolated_projects() {
let Some(f) = Fixture::gradle(&[
(
"gradle.properties",
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
),
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
]) else {
return;
};
let built = f.launch(false);
assert_eq!(built.failure, None, "{:?}\n{}", built.messages, build_output_tail(&f.events.lock().unwrap()));
assert!(f.out("t.app/classes/a/A.class").is_file());
}
#[test]
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
let Some(f) = Fixture::gradle(&[
+40 -4
Переглянути файл
@@ -499,11 +499,9 @@ pub fn sync_gradle_model(
"-q".into(),
// The init script reports the evaluated projects, even when a build enables the configuration cache.
"-Dorg.gradle.configuration-cache=false".into(),
"--init-script".into(),
init_script.to_string_lossy().into_owned(),
"tasks".into(),
"--all".into(),
];
args.extend(gradle::no_isolated_projects(&root.join(&model.dir), &options.env));
args.extend(["--init-script".into(), init_script.to_string_lossy().into_owned(), "tasks".into(), "--all".into()]);
if options.offline {
args.push("--offline".into());
}
@@ -1208,4 +1206,42 @@ mod tests {
assert!(args.contains("-T1"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
}
/// Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path).
#[test]
fn gradle_sync_lists_tasks_of_builds_that_enable_isolated_projects() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some();
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(std::path::PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
let Some(gradle) = gradle.filter(|_| has_jdk) else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let temp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(temp.path()).unwrap();
let files = [
(
"gradle.properties",
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
),
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib'\n"),
("build.gradle", ""),
("lib/build.gradle", "plugins { id 'java' }\n"),
];
for (rel, text) in files {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
let mut model = gradle::load(&root).unwrap();
model.command = gradle.to_string_lossy().into_owned();
let cache = root.join(".cache");
sync_gradle_model(&root, &cache, &model, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
let loaded = crate::load(&root, &cache, None);
let build = &loaded.gradle[0];
assert_eq!(build.sync_error, None);
let lib = build.projects.iter().find(|p| p.path == ":lib").expect("the reported :lib project");
assert!(lib.tasks.iter().any(|t| t.name == "compileJava"), "{:?}", lib.tasks);
}
}
+45 -5
Переглянути файл
@@ -161,9 +161,8 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
&script,
format!(
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
{}
def register = {{ p ->
def artifact = {{ t ->
t.dependsOn 'war'
// Resolved here so the action holds no task or project (configuration cache).
@@ -180,9 +179,14 @@ gradle.projectsEvaluated {{
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact)
else p.tasks.create('openideaTomcatArtifact', artifact)
}}
// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`; init scripts also
// run in included builds, which may have a project at the same path.
if (isolated) gradle.lifecycle.afterProject {{ p -> if (p.path == {path} && p.gradle.parent == null) p.afterEvaluate {{ register(p) }} }}
else gradle.projectsEvaluated {{ register(gradle.rootProject.project({path})) }}
"#,
groovy_literal(path),
groovy_literal(&manifest.to_string_lossy())
crate::gradle::ISOLATED_PROJECTS_SCRIPT,
groovy_literal(&manifest.to_string_lossy()),
path = groovy_literal(path),
),
)?;
let task = format!("{}:openideaTomcatArtifact", path.trim_end_matches(':'));
@@ -274,6 +278,42 @@ mod tests {
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
}
/// The WAR task's init script on a real Gradle, with and without Isolated Projects (#8261).
#[test]
fn gradle_war_artifact_builds_with_and_without_isolated_projects() {
let Some((gradle, version)) = crate::gradle::test_gradle() else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let builds = crate::gradle::write_test_builds(
&base,
// The build realizes tasks early and applies the WAR plugin in `afterEvaluate`.
"plugins { id 'java' }\ntasks.all {}\nafterEvaluate { apply plugin: 'war' }\n",
"plugins { java }\ntasks.all {}\nafterEvaluate { apply(plugin = \"war\") }\n",
&[("src/main/webapp/index.html", "war")],
);
for (root, isolated) in builds {
// Before Gradle 8.8 the script keeps reading the project from the root, as before.
if isolated && version < (8, 8) {
continue;
}
let cache = root.join("cache");
let mut model = crate::load(&root, &cache, None);
model.gradle[0].command = gradle.to_string_lossy().into_owned();
let id = artifacts(&root, &model).into_iter().find(|a| a.id.contains(":app")).expect("the app WAR").id;
for pass in if isolated { &["miss", "hit"][..] } else { &["run"][..] } {
let plan = build(&root, &model, &id, &cache).unwrap();
let out = crate::gradle::run_test_gradle(&root, &plan.cwd, &plan.command, &plan.args)
.unwrap_or_else(|e| panic!("{pass}:\n{e}"));
assert_eq!(out.contains("Reusing configuration cache."), *pass == "hit", "{out}");
let war = fs::read_to_string(cache.join("artifact-path.txt")).unwrap();
assert!(Path::new(&war).is_file() && war.ends_with(".war"), "{war}");
}
}
}
#[test]
fn gradle_manifest_paths_preserve_windows_characters() {
for path in [r"C:\工作 区\Tomcat's cache\artifact-path.txt", r"\\server\share\artifact-path.txt"] {
+2
Переглянути файл
@@ -467,6 +467,8 @@ pub enum LspRefreshKind {
FlutterOutline,
/// Spring bean markers of open documents may have changed.
SpringBeanMarkers,
/// Spring AOP markers of open documents may have changed.
SpringAopMarkers,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+1
Переглянути файл
@@ -24,6 +24,7 @@ pub mod network_path;
pub mod output_encoding;
pub mod output_rate;
pub mod platform;
pub mod private_temp;
pub mod process;
pub mod project_dir;
pub mod project_env;
+19 -3
Переглянути файл
@@ -170,8 +170,24 @@ pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects {
each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
eachProject { p ->
each(p.tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
}
";
@@ -622,7 +638,7 @@ mod tests {
#[test]
fn gradle_script_respects_the_builds_own_file_encoding() {
let s = GRADLE_FILE_ENCODING_SCRIPT;
assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("each(p.tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}");
assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}");
+97
Переглянути файл
@@ -0,0 +1,97 @@
//! Folders of this user in the system temporary folder.
//!
//! `/tmp` is shared by every user on Linux, so a fixed name there (`/tmp/openidea-gradle`) can be
//! created first by another user, who then controls the scripts, argument files and binaries
//! written into it. Everything goes under `<temp>/openidea-<uid>`, created owner-only; when that
//! name belongs to someone else or is a symbolic link, under a folder of a random name instead.
use std::io;
use std::path::PathBuf;
/// `<temp>/openidea-<uid>/<name>`, created when missing. `name` is a plain folder name.
pub fn dir(name: &str) -> io::Result<PathBuf> {
debug_assert!(!name.is_empty() && !name.contains(['/', '\\']), "{name}");
let dir = root()?.join(name);
std::fs::create_dir_all(&dir)?;
Ok(dir)
}
#[cfg(unix)]
fn root() -> io::Result<PathBuf> {
use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
static TAKEN: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
if let Some(own) = TAKEN.get() {
return Ok(own.clone());
}
// SAFETY: `geteuid` has no preconditions and cannot fail.
let uid = unsafe { libc::geteuid() };
let root = std::env::temp_dir().join(format!("openidea-{uid}"));
match std::fs::DirBuilder::new().mode(0o700).create(&root) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e),
}
let meta = std::fs::symlink_metadata(&root)?;
if !meta.is_dir() || meta.uid() != uid {
// Someone else took the name: a fresh folder of a random name for the rest of this run,
// rather than no temporary files at all.
let own = unique(&root)?;
return Ok(TAKEN.get_or_init(|| own).clone());
}
if meta.mode() & 0o077 != 0 {
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700))?;
}
Ok(root)
}
/// `<root>-XXXXXX`, created owner-only by `mkdtemp`.
#[cfg(unix)]
fn unique(root: &std::path::Path) -> io::Result<PathBuf> {
use std::os::unix::ffi::{OsStrExt, OsStringExt};
let mut template = root.as_os_str().as_bytes().to_vec();
template.extend_from_slice(b"-XXXXXX\0");
// SAFETY: `template` is a writable, NUL-terminated buffer that outlives the call.
if unsafe { libc::mkdtemp(template.as_mut_ptr().cast()) }.is_null() {
return Err(io::Error::last_os_error());
}
template.pop();
Ok(PathBuf::from(std::ffi::OsString::from_vec(template)))
}
/// The temporary folder is the user's own (`%LOCALAPPDATA%\Temp`).
#[cfg(not(unix))]
fn root() -> io::Result<PathBuf> {
Ok(std::env::temp_dir().join("openidea"))
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
#[test]
fn folders_are_under_an_owner_only_root() {
let made = dir("private-temp-test").unwrap();
let root = made.parent().unwrap();
let meta = std::fs::symlink_metadata(root).unwrap();
assert_eq!(meta.mode() & 0o777, 0o700);
assert_eq!(meta.uid(), unsafe { libc::geteuid() });
assert!(root.starts_with(std::env::temp_dir()));
assert!(made.is_dir());
// A root left group- or world-accessible is narrowed again.
std::fs::set_permissions(root, std::fs::Permissions::from_mode(0o755)).unwrap();
dir("private-temp-test").unwrap();
assert_eq!(std::fs::symlink_metadata(root).unwrap().mode() & 0o777, 0o700);
let _ = std::fs::remove_dir(&made);
}
#[test]
fn a_taken_name_falls_back_to_a_fresh_owner_only_folder() {
let tmp = tempfile::tempdir().unwrap();
let a = unique(&tmp.path().join("openidea-1")).unwrap();
let b = unique(&tmp.path().join("openidea-1")).unwrap();
assert_ne!(a, b);
assert!(a.file_name().unwrap().to_string_lossy().starts_with("openidea-1-"));
assert_eq!(std::fs::symlink_metadata(&a).unwrap().mode() & 0o777, 0o700);
}
}
+110 -1
Переглянути файл
@@ -9,7 +9,23 @@ const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects { p ->
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
eachProject { p ->
p.plugins.withId('java') {
p.apply plugin: 'jacoco'
each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') }
@@ -582,4 +598,97 @@ mod tests {
CoveragePrepared::Unsupported { .. }
));
}
/// The coverage init script on a real Gradle, with and without Isolated Projects (#8261).
/// Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path).
#[test]
fn gradle_init_script_configures_each_project() {
let gradle = std::env::var_os("JAVA_HOME").and_then(|_| {
std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(std::path::PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()))
});
let Some(gradle) = gradle else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let version = std::process::Command::new(&gradle).arg("--version").output().unwrap();
let version =
String::from_utf8_lossy(&version.stdout).lines().find_map(|l| l.strip_prefix("Gradle ").map(str::to_owned));
let mut parts = version
.expect("a `Gradle x.y` line")
.trim()
.split('.')
.map(|p| p.parse::<u32>().unwrap_or(0))
.collect::<Vec<_>>();
parts.resize(2, 0);
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let script = base.join("coverage.init.gradle");
std::fs::write(&script, GRADLE_INIT).unwrap();
for (name, props) in [
("plain", ""),
(
"isolated",
"org.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
),
] {
if name == "isolated" && (parts[0], parts[1]) < (8, 8) {
// Before Gradle 8.8 the script keeps reading every project, as the plain build checked.
continue;
}
let root = base.join(name);
for (rel, text) in [
("gradle.properties", format!("org.gradle.daemon=false\n{props}")),
("settings.gradle", "include 'lib'\n".to_owned()),
("build.gradle", String::new()),
(
"lib/build.gradle",
"plugins { id 'java' }\nrepositories { mavenCentral() }\n\
dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'; \
testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }\n\
test { useJUnitPlatform() }\n"
.to_owned(),
),
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static int one() { return 1; } }\n".to_owned(),
),
(
"lib/src/test/java/l/LTest.java",
"package l;\nclass LTest { @org.junit.jupiter.api.Test void one() { L.one(); } }\n".to_owned(),
),
] {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
let report = root.join("lib/build/reports/jacoco/test/jacocoTestReport.xml");
// With Isolated Projects the configuration cache is on: a miss, then a hit.
for pass in if name == "isolated" { &["miss", "hit"][..] } else { &["run"][..] } {
// Fresh test results and execution data, so each pass runs the tests under the agent.
for dir in ["lib/build/jacoco", "lib/build/test-results", "lib/build/reports"] {
let _ = std::fs::remove_dir_all(root.join(dir));
}
let out = std::process::Command::new(&gradle)
.args(["--console=plain", "--init-script"])
.arg(&script)
.arg(":lib:test")
.current_dir(&root)
.output()
.unwrap();
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
assert!(out.status.success(), "{name} {pass}:\n{text}");
let xml =
std::fs::read_to_string(&report).unwrap_or_else(|_| panic!("{name} {pass}: no report\n{text}"));
assert_eq!(text.contains("Reusing configuration cache."), *pass == "hit", "{name} {pass}:\n{text}");
let method =
xml.split(r#"<method name="one" desc="()I""#).nth(1).and_then(|m| m.split("</method>").next());
assert!(
method.is_some_and(|m| m.contains(r#"<counter type="LINE" missed="0" covered="1"/>"#)),
"{name} {pass}: {xml}"
);
}
}
}
}
+2 -2
Переглянути файл
@@ -78,8 +78,8 @@ impl DebugManager {
};
self.js_page_request(s, "stopProfile", json!({})).await?;
static HANDED_OVER: AtomicU32 = AtomicU32::new(0);
let dir = std::env::temp_dir().join(format!(
"openidea-js-profile-{}-{}-{}",
let dir = ide_core::private_temp::dir("js-profile")?.join(format!(
"{}-{}-{}",
std::process::id(),
s.0,
HANDED_OVER.fetch_add(1, Ordering::Relaxed)
+2 -2
Переглянути файл
@@ -1373,7 +1373,7 @@ fn json_args_len(args: &Value, key: &str) -> usize {
pub(crate) fn shorten_java_analyzer_classpath(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
let cwd = args.get("cwd").and_then(Value::as_str).map(PathBuf::from).unwrap_or_else(|| s.spec.cwd.clone());
if let Some(jar) =
shorten_java_analyzer_classpath_with(args, &cwd, cfg!(windows), &ide_run::java_cmdline::default_temp_dir())?
shorten_java_analyzer_classpath_with(args, &cwd, cfg!(windows), &ide_run::java_cmdline::default_temp_dir()?)?
{
s.temp_files.lock().push(TempFile(jar));
}
@@ -1444,7 +1444,7 @@ pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) ->
&java_args,
&s.spec.cwd,
cfg!(windows),
&ide_run::java_cmdline::default_temp_dir(),
&ide_run::java_cmdline::default_temp_dir()?,
)? {
java_args = shortened.args;
s.temp_files.lock().push(TempFile(shortened.file));
+1 -6
Переглянути файл
@@ -304,13 +304,8 @@ impl TempConfig {
pub fn new() -> IdeResult<Self> {
let nanos =
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
let dir = std::env::temp_dir().join(format!("openidea-docker-{}-{nanos}", std::process::id()));
let dir = ide_core::private_temp::dir("docker")?.join(format!("{}-{nanos}", std::process::id()));
std::fs::create_dir_all(&dir)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
}
if let Some(contexts) = user_config_dir().map(|d| d.join("contexts")).filter(|d| d.is_dir()) {
let _ = copy_dir(&contexts, &dir.join("contexts"));
}
+2
Переглянути файл
@@ -144,6 +144,7 @@ pub struct Host {
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>,
pub(crate) java_build_coordinator: Arc<ide_lsp::JavaBuildCoordinator>,
pub(crate) metrics_sampler: Mutex<ops::host_metrics::HostMetricsSampler>,
/// SSH connections of Settings › SSH Configurations.
pub ssh: Arc<ide_ssh::SshManager>,
@@ -315,6 +316,7 @@ impl Host {
heap_requests: Default::default(),
rebase_editors: Default::default(),
java_build: Default::default(),
java_build_coordinator: Arc::default(),
metrics_sampler: Default::default(),
languages,
syntax,
+1 -25
Переглянути файл
@@ -117,31 +117,7 @@ fn remove_old_logs(dir: &Path, max_age: std::time::Duration) {
/// A directory only this user can read: output may hold secrets, and `/tmp` is shared on Linux.
fn output_dir() -> IdeResult<PathBuf> {
#[cfg(unix)]
{
use std::os::unix::fs::{DirBuilderExt, MetadataExt};
let uid = rustix::process::getuid().as_raw();
let dir = std::env::temp_dir().join(format!("openidea-mcp-{uid}"));
match std::fs::DirBuilder::new().mode(0o700).create(&dir) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e.into()),
}
let meta = std::fs::symlink_metadata(&dir)?;
if !meta.is_dir() || meta.uid() != uid || meta.mode() & 0o077 != 0 {
return Err(ide_core::IdeError::new(
ide_core::error::ErrorKind::PermissionDenied,
format!("{} is not a private directory of this user", dir.display()),
));
}
Ok(dir)
}
#[cfg(not(unix))]
{
let dir = std::env::temp_dir().join("openidea-mcp");
std::fs::create_dir_all(&dir)?;
Ok(dir)
}
Ok(ide_core::private_temp::dir("mcp")?)
}
#[cfg(test)]
+3 -2
Переглянути файл
@@ -8,6 +8,7 @@ use ide_text::LineEnding;
use ide_workspace::settings::SettingsScope;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
/// editor buffer, so syntax features and language-server requests work in it.
@@ -165,7 +166,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
items
}
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
None => syntax(),
None => Arc::unwrap_or_clone(syntax()),
})
})
.await
@@ -186,7 +187,7 @@ pub async fn doc_folding(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
if snap.large {
return Ok(Vec::new());
}
let mut folds = project.syntax.folding(doc, &snap.language, snap.version, &snap.text);
let mut folds = Arc::unwrap_or_clone(project.syntax.folding(doc, &snap.language, snap.version, &snap.text));
if let Some(plugins) = crate::plugins::editor_providers_for(crate::plugins::ProviderKind::Folding) {
let d = ide_plugin::ProviderDocument {
path: project.documents.identity(doc)?.0,
+9 -2
Переглянути файл
@@ -338,10 +338,17 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
"class Board:\n def __init__(self):\n self.名前 = 1 # 初始化\n\n def 移动(self):\n return '→'\n"
);
// Already in order, or broken: nothing to do.
std::fs::write(&path, rearranged.text()).unwrap();
// The reordered text has the original's length: move the mtime, or a scan that lands in the
// same timestamp tick (common on Windows) keeps the old buffer.
let write_later = |text: &str, secs: u64| {
std::fs::write(&path, text).unwrap();
let file = std::fs::File::options().write(true).open(&path).unwrap();
file.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(secs)).unwrap();
};
write_later(&rearranged.text(), 2);
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
std::fs::write(&path, "class A:\n def b(self\n def __init__(self): ...\n").unwrap();
write_later("class A:\n def b(self\n def __init__(self): ...\n", 4);
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
}
+39
Переглянути файл
@@ -715,6 +715,23 @@ pub async fn plugin_line_markers(host: &Host, window: &str, doc: DocId) -> IdeRe
Ok(crate::plugins::LineMarkers { markers, late })
}
/// The languages whose plugin line markers a save of `path` can change: those a plugin declares for
/// `line-markers` along with the file's language (`"*"` for every language). Does not load plugin
/// code. By path, not document: closing a tab saves it and then closes its document.
#[command(trust = trusted)]
pub async fn plugin_line_marker_languages(
host: &Host,
window: &str,
path: std::path::PathBuf,
) -> IdeResult<Vec<String>> {
let Some(plugins) = editor_providers(ProviderKind::LineMarkers) else {
return Ok(Vec::new());
};
let project = host.project(window)?;
let language = blocking(move || Ok(project.documents.language_of(&path, None).language.0)).await?;
Ok(plugins.line_marker_languages_with(&language))
}
/// Where other files import the document's file (Find Usages on a file, a Vue component's
/// usages). Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
@@ -773,6 +790,26 @@ pub async fn lsp_spring_bean_markers(
result
}
/// The document's Spring AOP markers (advised methods with their advices, advice methods with
/// the methods they advise); `None` when no server attached to it provides them. Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_spring_aop_markers(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
) -> IdeResult<Option<Vec<SpringAopMarker>>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.spring_aop_markers(doc, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
result
}
/// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
/// instead of its `.d.ts`. Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
@@ -3797,6 +3834,7 @@ ide_command::domain!(
lsp_implementation_locations,
lsp_file_references,
lsp_spring_bean_markers,
lsp_spring_aop_markers,
lsp_switch_source_header,
lsp_source_definition,
lsp_open_typescript_file,
@@ -3832,6 +3870,7 @@ ide_command::domain!(
plugin_color_presentations,
plugin_formatters,
plugin_language_visuals,
plugin_line_marker_languages,
plugin_line_markers,
prepare_workspace_edit,
redo_workspace_edit,
+4 -4
Переглянути файл
@@ -736,10 +736,10 @@ fn split_build_log(
let name: String =
config.id.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).collect();
let project_key = project.cache_dir.file_name().unwrap_or_default();
let path = std::env::temp_dir().join("openidea-xcode-build").join(project_key).join(format!("{name}.log"));
let file = std::fs::create_dir_all(path.parent().unwrap_or(&path))
.and_then(|()| std::fs::File::create(&path))
.map(std::io::BufWriter::new);
let dir = ide_core::private_temp::dir("xcode-build").map(|d| d.join(project_key));
let path = dir.as_ref().map(|d| d.join(format!("{name}.log"))).unwrap_or_default();
let file =
dir.and_then(std::fs::create_dir_all).and_then(|()| std::fs::File::create(&path)).map(std::io::BufWriter::new);
let file = match file {
Ok(file) => Some(file),
Err(e) => {
+4 -2
Переглянути файл
@@ -173,7 +173,8 @@ pub async fn run_env_files(files: Vec<std::path::PathBuf>) -> IdeResult<std::col
pub async fn run_gradle_jvm_args_script(jvm_args: Vec<String>) -> IdeResult<String> {
// The forked JVMs: `bootRun`, `run`, tests; the path is for `--init-script`.
tokio::task::spawn_blocking(move || {
ide_run::gradle_jvm::write_init_script(&ide_run::gradle_jvm::default_dir(), &jvm_args)
ide_run::gradle_jvm::default_dir()
.and_then(|dir| ide_run::gradle_jvm::write_init_script(&dir, &jvm_args))
.map(|p| p.to_string_lossy().into_owned())
.map_err(|e| IdeError::internal(format!("cannot write the Gradle init script: {e}")))
})
@@ -189,7 +190,8 @@ pub async fn run_gradle_init_script(name: String, text: String) -> IdeResult<Str
return Err(IdeError::invalid(format!("invalid init script name {name:?}")));
}
tokio::task::spawn_blocking(move || {
ide_run::gradle_jvm::write_script(&ide_run::gradle_jvm::default_dir(), &name, &text)
ide_run::gradle_jvm::default_dir()
.and_then(|dir| ide_run::gradle_jvm::write_script(&dir, &name, &text))
.map(|p| p.to_string_lossy().into_owned())
.map_err(|e| IdeError::internal(format!("cannot write the Gradle init script: {e}")))
})
+3 -3
Переглянути файл
@@ -191,7 +191,7 @@ fn package_name(file: &Path) -> Option<String> {
}
/// A stable directory per source file, so a rebuild reuses classes of unchanged files.
fn compile_dir(file: &Path) -> PathBuf {
fn compile_dir(file: &Path) -> std::io::Result<PathBuf> {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
file.hash(&mut hasher);
let stem: String = file
@@ -201,7 +201,7 @@ fn compile_dir(file: &Path) -> PathBuf {
.chars()
.map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' })
.collect();
std::env::temp_dir().join("openidea-run").join(format!("java-{stem}-{:x}", hasher.finish()))
Ok(ide_core::private_temp::dir("run")?.join(format!("java-{stem}-{:x}", hasher.finish())))
}
/// Replaces `config` with `java -cp <project> <class>` after compiling the file with the
@@ -274,7 +274,7 @@ pub(super) async fn prepare(
}
let sources = module.as_ref().map(|m| m.sources.as_slice()).unwrap_or_default();
let libraries = module.as_ref().map(|m| m.libraries.as_slice()).unwrap_or_default();
let out = compile_dir(&file);
let out = compile_dir(&file).map_err(|e| IdeError::internal(format!("Cannot create the output folder ({e})")))?;
std::fs::create_dir_all(&out).map_err(|e| IdeError::internal(format!("Cannot create {} ({e})", out.display())))?;
let mut args: Vec<String> = vec!["-g".into(), "-d".into(), out.to_string_lossy().into_owned()];
if !libraries.is_empty() {
+32 -3
Переглянути файл
@@ -33,8 +33,35 @@ pub async fn scaffold_options(
/// The programs a generator needs for `values`, and whether they are installed.
#[command(trust = always)]
pub async fn scaffold_requirements(generator: String, values: Values) -> IdeResult<Vec<Requirement>> {
blocking(move || ide_scaffold::requirements(&generator, &values)).await
pub async fn scaffold_requirements(host: &Host, generator: String, values: Values) -> IdeResult<Vec<Requirement>> {
let configured = configured_goroot(host);
blocking(move || {
let goroot = goroot(configured, &generator, &values);
ide_scaffold::requirements(&generator, &values, goroot.as_deref())
})
.await
}
/// The GOROOT chosen in the global settings (those of new projects).
fn configured_goroot(host: &Host) -> Option<PathBuf> {
host.global_settings.read_effective(|s| ide_sdk::apply::absolute_setting_path(&s.languages.go.goroot))
}
/// The Go a generator that needs `go` runs: the GOROOT chosen in Settings; else `go` from `PATH`,
/// where a version manager picks it for the target folder; else, with no `go` on `PATH` (an app
/// started from the Dock or Finder), the first Go install found on this machine, as listed in
/// Settings › Languages › Go. Blocking: detection runs `go version`.
fn goroot(configured: Option<PathBuf>, generator: &str, values: &Values) -> Option<PathBuf> {
configured.or_else(|| {
if !ide_scaffold::needs_program(generator, values, "go") {
return None;
}
let path = ide_core::process::host_var_os("PATH").unwrap_or_default();
if ide_core::process::find_executable("go", &path).is_some() {
return None;
}
ide_sdk::detect(ide_sdk::SdkKind::Go, None).into_iter().find_map(|sdk| sdk.home.map(IpcPath::into_path_buf))
})
}
/// Whether a project named `name` cannot be created in `location`: something other than an
@@ -61,8 +88,10 @@ pub async fn scaffold_create(
) -> IdeResult<IpcPath> {
// Trusted because the user just created it; a failed or cancelled run leaves no files behind.
let cancel = host.begin_request(request);
let configured = configured_goroot(host);
let result = blocking(move || {
ide_scaffold::create(&req, &cancel, &|e| {
let goroot = goroot(configured, &req.generator, &req.values);
ide_scaffold::create(&req, goroot.as_deref(), &cancel, &|e| {
let _ = on_event.send(e);
})
})
+60 -9
Переглянути файл
@@ -50,13 +50,23 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
(Some(p), SdkKind::Python) => ide_sdk::apply::python_interpreter(&p.root, &p.settings.effective()),
_ => None,
};
// Explicitly added interpreters belong to the user, not to the project being opened.
// Include them in discovery for every selector, even after a different interpreter is chosen.
let registered = if kind == SdkKind::Python {
host.global_settings.effective().languages.python.interpreters
} else {
Vec::new()
};
blocking_value(move || {
let mut sdks = ide_sdk::detect(kind, root.as_deref());
if let Some(path) = current
&& !sdks.iter().any(|s| *s.path == *path)
&& let Some(sdk) = ide_sdk::python_interpreter_sdk(&path, root.as_deref())
{
sdks.push(sdk);
let registered = registered.into_iter().map(PathBuf::from).filter(|path| path.is_absolute());
for path in current.into_iter().chain(registered) {
if !sdks.iter().any(|s| *s.path == *path)
&& let Some(sdk) = ide_sdk::python_interpreter_sdk(&path, root.as_deref())
&& !sdks.iter().any(|s| s.path == sdk.path)
{
sdks.push(sdk);
}
}
sdks
})
@@ -408,10 +418,12 @@ pub async fn sdk_locate_tools(
near: Option<PathBuf>,
) -> IdeResult<LocatedTools> {
host.require_trust_if_project(window)?;
blocking_value(move || LocatedTools {
tools: ide_sdk::locate::locate_tools(&names, near.as_deref()),
compile_dir: ide_sdk::locate::compile_dir().into(),
macos_sysroot: ide_sdk::locate::macos_sysroot().map(Into::into),
blocking(move || {
Ok(LocatedTools {
tools: ide_sdk::locate::locate_tools(&names, near.as_deref()),
compile_dir: ide_sdk::locate::compile_dir()?.into(),
macos_sysroot: ide_sdk::locate::macos_sysroot().map(Into::into),
})
})
.await
}
@@ -672,6 +684,45 @@ mod tests {
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn registered_python_interpreters_remain_detectable_after_switch_and_reopen() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
let a = fake_venv(&root, ".venv");
let b = fake_venv(&root, ".venv-alt");
let missing = root.join("missing/bin/python");
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.trust.decide(&root, true, false).unwrap();
host.global_settings
.set(
ide_workspace::SettingsScope::Global,
"languages.python.interpreters",
serde_json::json!([a, b, b, missing]),
)
.unwrap();
host.open_project("main", &root).unwrap();
let project = host.project("main").unwrap();
for python in [&b, &a] {
project
.settings
.set(
ide_workspace::SettingsScope::Project,
"languages.python.interpreter",
serde_json::to_value(python).unwrap(),
)
.unwrap();
}
host.close_project("main");
host.open_project("main", &root).unwrap();
let detected = sdk_detect(&host, "main", SdkKind::Python).await.unwrap();
assert_eq!(detected.iter().filter(|s| *s.path == a).count(), 1);
assert_eq!(detected.iter().filter(|s| *s.path == b).count(), 1);
assert!(!detected.iter().any(|s| *s.path == missing));
assert_eq!(sdk_python_effective(&host, "main", None).await.unwrap(), Some(a.into()));
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn another_projects_interpreter_is_listed_with_its_project() {
let temp = tempfile::tempdir().unwrap();
+14 -2
Переглянути файл
@@ -74,11 +74,13 @@ pub(crate) fn apply_output_rate(host: &Host, window: &str) {
}
/// 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.
/// built-in client with the configuration's saved password, key or agent. With `cwd` (Remote
/// Host › Start SSH Session in Directory) the shell starts in that remote folder.
pub async fn spawn_ssh(
host: &Host,
window: &str,
id: &str,
cwd: Option<&str>,
cols: u16,
rows: u16,
on_output: Emit<String>,
@@ -93,7 +95,7 @@ pub async fn spawn_ssh(
let out = feed.clone();
let process = session
.spawn(
"",
&ssh_shell_command(cwd),
Some(size),
Box::new(move |chunk| match chunk {
ide_ssh::Output::Stdout(data) | ide_ssh::Output::Stderr(data) => out.output(data),
@@ -134,6 +136,16 @@ pub async fn spawn_ssh(
)
}
/// The exec command of an SSH terminal: empty for the account's shell, or a `cd` into `cwd` that
/// then replaces itself with the login shell. A `cd` that fails prints its error and leaves the
/// shell in the home folder.
fn ssh_shell_command(cwd: Option<&str>) -> String {
match cwd.map(str::trim).filter(|d| !d.is_empty()) {
None => String::new(),
Some(dir) => format!("cd -- {}; exec \"${{SHELL:-/bin/sh}}\" -l", ide_ssh::shell::tilde_quote(dir)),
}
}
enum SshInput {
Data(Vec<u8>),
Resize(u16, u16),
+48 -4
Переглянути файл
@@ -128,6 +128,29 @@ impl Providers {
out
}
/// Each plugin's languages declared for `kind`, in declaration order.
fn languages_by_plugin(&self, kind: ProviderKind) -> Vec<(String, Vec<String>)> {
let mut out: Vec<(String, Vec<String>)> = Vec::new();
for (_, plugin, kinds, languages) in self.items.read().iter() {
if !kinds.contains(&kind) {
continue;
}
let at = match out.iter().position(|(id, _)| id == plugin) {
Some(at) => at,
None => {
out.push((plugin.clone(), Vec::new()));
out.len() - 1
}
};
for language in languages {
if !out[at].1.contains(language) {
out[at].1.push(language.clone());
}
}
}
out
}
/// One coherent declaration snapshot, preserving the first match per plugin.
fn matching<T: FromIterator<(String, u64)>>(&self, kind: ProviderKind, language: &str) -> T {
let items = self.items.read();
@@ -301,6 +324,11 @@ use std::collections::BTreeSet;
use std::sync::Weak;
use std::time::{Duration, Instant};
fn usable_provider(p: &LoadedPlugin) -> bool {
let m = p.meta.lock();
matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty()
}
/// What the plugins answered for completion in the editor.
#[derive(Debug, Default)]
pub(crate) struct EditorCompletion {
@@ -342,13 +370,29 @@ impl PluginHost {
.plugins_for(kind, language)
.into_iter()
.filter_map(|id| self.get(&id).ok())
.filter(|p| {
let m = p.meta.lock();
matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty()
})
.filter(|p| usable_provider(p))
.collect()
}
/// The languages a usable plugin declares for `line-markers` along with `language` (`"*"` for
/// every language), without loading any plugin: a saved file of `language` can change the
/// markers of the files of these languages.
pub fn line_marker_languages_with(&self, language: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for (id, languages) in self.providers.languages_by_plugin(ProviderKind::LineMarkers) {
let covers = languages.iter().any(|l| l == "*" || l == language);
if !covers || !self.get(&id).is_ok_and(|p| usable_provider(&p)) {
continue;
}
for l in languages {
if !out.contains(&l) {
out.push(l);
}
}
}
out
}
/// Edit-path calls (soft / hard deadline) to every usable plugin that
/// declares `kind` for `language`, in plugin order, leaving out those that
/// failed or were late. Each plugin runs on its own thread, so the calls
+28 -6
Переглянути файл
@@ -69,6 +69,9 @@ pub enum AuthOperation {
pub const PLUGINS_DIR: &str = "remote-plugins";
const INCOMING_DIR: &str = "remote-plugins.incoming";
const SECRET_TIMEOUT: Duration = Duration::from_secs(10);
/// The longest a server may hold a desktop OAuth listener open in one request; a disconnect
/// abandons it earlier ([`PluginHost::forget_remote_loopbacks`]).
const REMOTE_AUTH_WAIT_MAX: Duration = Duration::from_secs(10 * 60);
const EVENT_FLUSH: Duration = Duration::from_millis(250);
const TICKS_PER_SUPERVISION: u32 = 20;
@@ -188,6 +191,11 @@ fn plugin_command(id: &str) -> bool {
// ---- desktop side -----------------------------------------------------------
/// Whether a plugin is one the desktop sends to remote servers.
fn synced(plugin: &super::LoadedPlugin) -> bool {
plugin.dev_root.is_none() && !plugin.invalid && plugin.manifest().wasm.is_some()
}
impl PluginHost {
fn package_files(&self, plugin: &super::LoadedPlugin) -> IdeResult<Vec<PathBuf>> {
let set = self.prepare(&plugin.pkg).map_err(IdeError::invalid)?;
@@ -199,7 +207,7 @@ impl PluginHost {
let plugins: Vec<_> = self.plugins.read().values().cloned().collect();
plugins
.iter()
.filter(|p| p.dev_root.is_none() && !p.invalid && p.manifest().wasm.is_some())
.filter(|p| synced(p))
.filter_map(|p| {
let files = self.package_files(p).ok()?;
let digest = package_digest(p.dir(), &files).ok()?;
@@ -228,9 +236,23 @@ impl PluginHost {
.collect()
}
/// A secret a plugin declares, for its remote instance (`plugin_secret`).
/// A plugin a server may act for: one [`remote_packages`](Self::remote_packages) sends, and
/// enabled. A server may name any plugin, so this is checked on every request it makes.
fn remote_plugin(&self, id: &str) -> Result<Arc<super::LoadedPlugin>, String> {
let plugin = self.get(id).map_err(|e| e.message)?;
if !synced(&plugin) || !matches!(plugin.status(), super::PluginStatus::Active | super::PluginStatus::Inactive) {
return Err("plugin not available remotely".into());
}
Ok(plugin)
}
/// A secret a plugin declares, for its remote instance (`plugin_secret`): only with a current
/// `secrets` grant, as a request header on this machine needs.
pub fn declared_secret(&self, id: &str, name: &str) -> Option<String> {
let plugin = self.get(id).ok()?;
let plugin = self.remote_plugin(id).ok()?;
if !plugin.meta.lock().granted.iter().any(|g| g.covers(&ide_extension::Capability::Secrets)) {
return None;
}
if !self.ui.items(super::providers::SECRETS_POINT, Some(plugin.id())).iter().any(|s| s.key == name) {
return None;
}
@@ -558,7 +580,7 @@ impl super::auth::Service for ClientLoopbacks {
impl PluginHost {
/// A remote instance may mutate only declared secrets with a current grant.
pub fn remote_secret_write(&self, request: SecretWrite) -> Result<(), String> {
let plugin = self.get(&request.plugin).map_err(|e| e.message)?;
let plugin = self.remote_plugin(&request.plugin)?;
if !plugin.meta.lock().granted.iter().any(|g| g.covers(&ide_extension::Capability::Secrets)) {
return Err("secrets capability not granted".into());
}
@@ -573,7 +595,7 @@ impl PluginHost {
/// Serves a connected remote instance using this connection's actual window.
pub fn remote_auth(&self, window: &str, request: AuthRequest) -> Result<serde_json::Value, ide_plugin::HostError> {
if matches!(&request.operation, AuthOperation::Begin { .. } | AuthOperation::Wait { .. }) {
self.get(&request.plugin).map_err(|e| ide_plugin::HostError::NotFound(e.message))?;
self.remote_plugin(&request.plugin).map_err(ide_plugin::HostError::NotFound)?;
}
let owner = format!("remote:{window}:{}", request.plugin);
let service = self.shared.loopbacks.read().clone();
@@ -587,7 +609,7 @@ impl PluginHost {
AuthOperation::Wait { id, timeout_ms } => serde_json::to_value(service.wait(
&owner,
id,
Duration::from_millis(u64::from(timeout_ms)),
Duration::from_millis(u64::from(timeout_ms)).min(REMOTE_AUTH_WAIT_MAX),
&ide_core::CancellationToken::new(),
)?),
AuthOperation::Close { id } => {
+31
Переглянути файл
@@ -272,6 +272,7 @@ impl Host {
)?;
mark("index");
let lsp = LspManager::new(root.clone(), languages.clone(), sink.clone());
lsp.set_java_build_coordinator(self.java_build_coordinator.clone());
crate::plugins::injections::configure_lsp(&lsp);
lsp.set_execution_allowed(trusted.load(Ordering::Acquire));
lsp.set_content_roots(language_server_roots(&root, extra_roots.clone()));
@@ -416,6 +417,7 @@ impl Host {
&effective.inspections,
lang_level,
);
let generated_workspace = !cfg.args.iter().any(|arg| arg == "-data");
ide_sdk::java::configure_jdtls(
cfg,
server_root,
@@ -427,6 +429,12 @@ impl Host {
&bundles,
lombok.jar(),
);
if generated_workspace && server_root != window_root {
// The same build can be selected from a containing window and from a
// window opened directly on it. They must not lock the same Eclipse
// metadata directory while keeping independent editor buffers.
scope_java_workspace(cfg, window_root);
}
ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective);
let gradle_dirs: Vec<_> = std::iter::once(data_dir.join("gradle"))
.chain(dirs::cache_dir().map(|dir| dir.join("openidea").join("gradle")))
@@ -3033,6 +3041,15 @@ fn exclude_globs(
globs
}
fn scope_java_workspace(cfg: &mut ide_language::LanguageServerConfig, window_root: &Path) {
if let Some(index) = cfg.args.iter().position(|arg| arg == "-data")
&& let Some(data) = cfg.args.get_mut(index + 1)
{
data.push_str("-window-");
data.push_str(&project_key(window_root));
}
}
pub(crate) fn project_key(root: &Path) -> String {
// Stable FNV-1a directory name per project for caches.
let s = root.to_string_lossy();
@@ -3271,6 +3288,20 @@ mod vue_release_tests {
#[cfg(test)]
mod maven_linkage_tests {
#[test]
fn nested_java_workspaces_have_distinct_metadata_paths() {
let mut cfg: ide_language::LanguageServerConfig = serde_json::from_value(serde_json::json!({
"name": "jdtls", "command": "jdtls", "args": ["-data", "workspace"]
}))
.unwrap();
let original = cfg.clone();
super::scope_java_workspace(&mut cfg, std::path::Path::new("/parent"));
assert_ne!(cfg.args, original.args);
let mut other = original;
super::scope_java_workspace(&mut other, std::path::Path::new("/other"));
assert_ne!(cfg.args, other.args);
}
#[test]
fn explicit_gradle_links_preserve_independent_eclipse_projects() {
let tmp = tempfile::tempdir().unwrap();
+24 -2
Переглянути файл
@@ -781,7 +781,7 @@ document.getElementById("f").addEventListener("submit", async (e) => {
</script>
</body>
</html>"#;
Response::builder()
page_headers(Response::builder())
.status(StatusCode::UNAUTHORIZED)
.header(header::CONTENT_TYPE, "text/html; charset=utf-8")
.header(header::CACHE_CONTROL, "no-store")
@@ -789,6 +789,17 @@ document.getElementById("f").addEventListener("submit", async (e) => {
.unwrap()
}
/// Headers of the pages the browser shows (the workbench and the sign-in page): no other site
/// may frame them, which would let it trick a click into the IDE, and nothing is guessed from
/// content or leaked through `Referer`.
fn page_headers(builder: hyper::http::response::Builder) -> hyper::http::response::Builder {
builder
.header(header::CONTENT_SECURITY_POLICY, "frame-ancestors 'none'; object-src 'none'; base-uri 'self'")
.header(header::X_FRAME_OPTIONS, "DENY")
.header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
.header(header::REFERRER_POLICY, "no-referrer")
}
fn handle_ws_upgrade(req: Request<Incoming>, state: Arc<ServerState>) -> Response<Full<Bytes>> {
let Some(key) = req.headers().get(header::SEC_WEBSOCKET_KEY).and_then(|v| v.to_str().ok()).map(str::to_owned)
else {
@@ -1228,7 +1239,7 @@ async fn serve_index_html(web_dir: &Path, head_only: bool, gzip: bool) -> Respon
};
let len = payload.len();
let body = if head_only { Bytes::new() } else { payload };
let mut builder = Response::builder()
let mut builder = page_headers(Response::builder())
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "text/html; charset=utf-8")
.header(header::CONTENT_LENGTH, len.to_string())
@@ -1244,6 +1255,17 @@ async fn serve_index_html(web_dir: &Path, head_only: bool, gzip: bool) -> Respon
mod tests {
use super::*;
#[tokio::test]
async fn pages_cannot_be_framed_by_other_sites() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("index.html"), "<html><head></head><body></body></html>").unwrap();
let response = serve_index_html(dir.path(), false, false).await;
let headers = response.headers();
assert_eq!(headers[header::X_FRAME_OPTIONS], "DENY");
assert!(headers[header::CONTENT_SECURITY_POLICY].to_str().unwrap().contains("frame-ancestors 'none'"));
assert_eq!(headers[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
}
#[test]
fn resolves_direct_and_reverse_proxy_prefixed_assets_safely() {
let dir = tempfile::tempdir().unwrap();
+27 -1
Переглянути файл
@@ -91,6 +91,7 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() {
&host,
"main",
"box",
None,
100,
30,
Arc::new(move |s| {
@@ -116,7 +117,7 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() {
assert!(!host.terminals.contains(info.id));
// Closing the tab hangs up a running shell.
let info = ide_host::ops::term::spawn_ssh(&host, "main", "box", 80, 24, Arc::new(|_| {})).await.unwrap();
let info = ide_host::ops::term::spawn_ssh(&host, "main", "box", None, 80, 24, Arc::new(|_| {})).await.unwrap();
host.terminals.kill(info.id).unwrap();
let code = loop {
match events.recv_timeout(Duration::from_secs(10)).expect("exit event") {
@@ -128,6 +129,31 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() {
host.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ssh_session_in_a_directory_starts_the_login_shell_there() {
let tmp = tempfile::tempdir().unwrap();
let (host, _events) = host_with_ssh_box(tmp.path(), Arc::new(|cmd| (format!("ran: {cmd}\n"), 0))).await;
let (tx, output) = mpsc::channel();
let tx = Mutex::new(tx);
ide_host::ops::term::spawn_ssh(
&host,
"main",
"box",
Some("~/my app's"),
80,
24,
Arc::new(move |s| {
let _ = tx.lock().unwrap().send(s);
}),
)
.await
.unwrap();
// The server answers the PTY request ("pty 80x24") first, in its own packet on Linux.
let out = read_until(&output, "-l\n");
assert!(out.contains(r#"ran: cd -- ~/'my app'\''s'; exec "${SHELL:-/bin/sh}" -l"#), "{out:?}");
host.shutdown().await;
}
/// Reads what a connection to the local end of a Docker tunnel gets back.
async fn dial(port: u16) -> std::io::Result<String> {
use tokio::io::AsyncReadExt;
+44
Переглянути файл
@@ -1578,6 +1578,50 @@ async fn java_multimodule() {
multimodule("java", JAVA_MODULES, "java_multimodule").await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "language smoke: needs jdtls, JDK 21 and Maven"]
async fn java_overlapping_windows() {
const CHILD: &str = "child";
let smoke =
Smoke::open("java", "java-multimodule", &[], Duration::from_secs(300)).await.named("java_overlapping_windows");
let core = smoke.root.join("core");
let file = core.join("src/main/java/com/example/core/Greeter.java");
let class = core.join("target/classes/com/example/core/Greeter.class");
let cancel = ide_core::CancellationToken::new();
ops::doc::doc_open(&smoke.host, WINDOW, file.clone()).await.unwrap();
let parent = smoke.host.project(WINDOW).unwrap();
parent.lsp.wait_jdtls_imported(&file, tokio::time::Instant::now() + smoke.warm_up, &cancel).await.unwrap();
assert_eq!(
ops::java::java_build_workspace(&smoke.host, WINDOW, core.clone(), None).await.unwrap(),
ide_lsp::jdtls::JavaBuildStatus::Succeeded
);
let written = std::fs::metadata(&class).unwrap().modified().unwrap();
tokio::time::sleep(Duration::from_secs(1)).await;
smoke.host.trust.decide(&core, true, false).unwrap();
smoke.host.open_project(CHILD, &core).unwrap();
ops::doc::doc_open(&smoke.host, CHILD, file.clone()).await.unwrap();
let child = smoke.host.project(CHILD).unwrap();
child.lsp.wait_jdtls_imported(&file, tokio::time::Instant::now() + smoke.warm_up, &cancel).await.unwrap();
child.lsp.java_classpath(&core, false, &cancel).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
assert_eq!(
std::fs::metadata(&class).unwrap().modified().unwrap(),
written,
"the child window rebuilt the same output"
);
eprintln!("Maven parent and child windows imported; no second automatic write to Greeter.class");
let (a, b) = tokio::join!(
ops::java::java_build_workspace(&smoke.host, WINDOW, core.clone(), None),
ops::java::java_build_workspace(&smoke.host, CHILD, core.clone(), None),
);
assert_eq!(a.unwrap(), ide_lsp::jdtls::JavaBuildStatus::Succeeded);
assert_eq!(b.unwrap(), ide_lsp::jdtls::JavaBuildStatus::Succeeded);
eprintln!("both explicit builds succeeded without competing automatic writers");
smoke.host.close_project(CHILD);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "language smoke: needs kotlin-lsp, a JDK and Gradle"]
async fn kotlin_restart() {
+81
Переглянути файл
@@ -3465,7 +3465,13 @@ fn official_license_header_reports_fixes_and_scans() {
#[test]
fn official_mybatis_navigates_between_interface_and_xml() {
let f = fixture(Limits::default());
assert!(f.host.line_marker_languages_with("java").is_empty());
f.install(&official("mybatis"));
// One plugin's two declarations: a saved Kotlin file can change the XML's markers too.
let mut languages = f.host.line_marker_languages_with("kotlin");
languages.sort();
assert_eq!(languages, ["java", "kotlin", "xml"]);
assert!(f.host.line_marker_languages_with("markdown").is_empty());
let java_path = f.project.join("src/main/java/com/acme/UserMapper.java");
let xml_path = f.project.join("src/main/resources/mapper/UserMapper.xml");
std::fs::create_dir_all(java_path.parent().unwrap()).unwrap();
@@ -6882,6 +6888,38 @@ fn api14_denies_new_privileges_and_requires_an_invoking_window() {
assert_eq!(f.host.declared_secret("api14", "token"), None);
}
#[test]
fn remote_secret_requests_need_an_enabled_plugin_with_the_secrets_grant() {
use ide_host::plugins::remote_host::{AuthOperation, AuthRequest, SecretWrite};
let f = fixture(Limits::default());
f.host.install_from_dir(&sample("api14"), &Consent::default()).unwrap();
f.host.set_capability("api14", "secrets", true).unwrap();
f.run("api14", "secret", Some("stored")).unwrap();
let write = |value: &str| {
f.host.remote_secret_write(SecretWrite {
plugin: "api14".into(),
name: "token".into(),
value: Some(value.into()),
})
};
assert_eq!(f.host.declared_secret("api14", "token").as_deref(), Some("stored"));
f.host.set_capability("api14", "secrets", false).unwrap();
assert_eq!(f.host.declared_secret("api14", "token"), None);
assert!(write("other").is_err());
f.host.set_capability("api14", "secrets", true).unwrap();
f.host.set_enabled("api14", false).unwrap();
assert_eq!(f.host.declared_secret("api14", "token"), None);
assert!(write("other").is_err());
let begin = AuthRequest { plugin: "api14".into(), operation: AuthOperation::Begin { path: "/cb".into() } };
assert!(f.host.remote_auth("main", begin).is_err());
f.host.set_enabled("api14", true).unwrap();
assert_eq!(f.host.declared_secret("api14", "token").as_deref(), Some("stored"));
assert_eq!(f.host.declared_secret("missing", "token"), None);
}
/// `net.fetch-stream`: the body is read as it arrives, so a plugin gets the
/// first server-sent event while the server is still sending (here it never
/// finishes), and a short body ends with `done`. The same grants as `fetch`.
@@ -8903,3 +8941,46 @@ fn line_markers_too_late_from_one_provider_keep_the_others() {
assert!(markers.iter().all(|(id, _)| id == "on-time"));
});
}
/// A disabled plugin's languages don't make a save ask for line markers again.
#[test]
fn line_marker_languages_leave_out_disabled_plugins() {
let f = fixture(Limits::default());
f.install(&official("mybatis"));
assert_eq!(f.host.line_marker_languages_with("xml").len(), 3);
f.host.set_enabled("openidea.mybatis", false).unwrap();
assert!(f.host.line_marker_languages_with("xml").is_empty());
}
/// Another plugin's languages don't count: only one plugin declaring both links two files.
#[test]
fn line_marker_languages_come_from_the_plugins_covering_the_saved_language() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let install = |id: &str, languages: &str| {
let pkg = tmp.path().join(id);
copy_dir(&misbehave_pkg(), &pkg);
std::fs::write(
pkg.join("plugin.toml"),
format!(
"id = \"{id}\"\nname = \"{id}\"\nversion = \"0.0.1\"\nengines.openidea = \"^1.0\"\n\
wasm = \"dist/plugin.wasm\"\nactivation = [\"on-language:text\"]\n\
[[contributes.providers]]\nkinds = [\"line-markers\"]\nlanguages = {languages}\n"
),
)
.unwrap();
f.install(&pkg);
};
install("text-markers", r#"["text"]"#);
install("md-markers", r#"["markdown"]"#);
// Another plugin's languages don't come along.
assert_eq!(f.host.line_marker_languages_with("text"), ["text"]);
assert_eq!(f.host.line_marker_languages_with("markdown"), ["markdown"]);
assert!(f.host.line_marker_languages_with("java").is_empty());
install("any-markers", r#"["*"]"#);
// `any-markers` covers every language, so every save reaches its editors.
let mut languages = f.host.line_marker_languages_with("text");
languages.sort();
assert_eq!(languages, ["*", "text"]);
assert_eq!(f.host.line_marker_languages_with("java"), ["*"]);
}
+48 -3
Переглянути файл
@@ -174,9 +174,9 @@ pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &Cancell
Ok(format!("{} {}", status.as_u16(), status.canonical_reason().unwrap_or("")).trim_end().to_owned())
}
/// reqwest errors with their causes ("error sending request: … connection refused").
pub fn describe(e: &reqwest::Error) -> String {
use std::error::Error;
/// An error with its causes ("error sending request: … connection refused"), so
/// messages surfaced to the user keep the step that actually failed.
pub fn describe(e: &(dyn std::error::Error + 'static)) -> String {
let mut msg = e.to_string();
let mut source = e.source();
while let Some(s) = source {
@@ -194,6 +194,51 @@ pub fn describe(e: &reqwest::Error) -> String {
mod tests {
use super::*;
/// The updater wraps reqwest in its own error type (`tauri-plugin-updater`'s
/// `#[error(transparent)]` variant), so `describe` must follow `source` through
/// any error, not just `reqwest::Error`.
#[derive(Debug)]
struct ConnectRefused;
impl std::fmt::Display for ConnectRefused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "tcp connect error: connection refused 127.0.0.1:55134")
}
}
impl std::error::Error for ConnectRefused {}
#[derive(Debug)]
struct WrappedRequest {
source: ConnectRefused,
}
impl std::fmt::Display for WrappedRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"error sending request for url (https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json)"
)
}
}
impl std::error::Error for WrappedRequest {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
#[test]
fn describe_keeps_the_causes_behind_a_wrapped_error() {
let error = WrappedRequest { source: ConnectRefused };
assert_eq!(
describe(&error),
"error sending request for url (https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json): \
tcp connect error: connection refused 127.0.0.1:55134"
);
}
#[test]
fn describe_of_an_error_without_causes_is_unchanged() {
assert_eq!(describe(&ConnectRefused), "tcp connect error: connection refused 127.0.0.1:55134");
}
#[test]
fn auto_mode_rebuilds_the_shared_client_when_the_system_proxy_changes() {
static SYSTEM: Mutex<String> = Mutex::new(String::new());
+27 -14
Переглянути файл
@@ -186,7 +186,8 @@ impl SyntaxCache {
stats
}
pub fn outline(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Vec<OutlineItem> {
/// The memoized outline, shared: a cache hit clones none of its `String`s.
pub fn outline(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Arc<Vec<OutlineItem>> {
self.memoized(
doc,
lang,
@@ -211,7 +212,8 @@ impl SyntaxCache {
)
}
pub fn folding(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Vec<FoldRange> {
/// The memoized folding ranges, shared like [`Self::outline`].
pub fn folding(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Arc<Vec<FoldRange>> {
self.memoized(
doc,
lang,
@@ -230,7 +232,7 @@ impl SyntaxCache {
/// Highlighting from the grammar's own query; empty without one.
pub fn highlights(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> SyntaxHighlights {
SyntaxHighlights::new(self.memoized(
SyntaxHighlights::new(Arc::unwrap_or_clone(self.memoized(
doc,
lang,
version,
@@ -241,10 +243,12 @@ impl SyntaxCache {
})
.or_else(|| super::external::highlights(lang, text))
},
))
)))
}
/// `compute()` once per document version; `None` (no grammar / query) is not memoized.
/// Returns the `Arc` the memo holds; a caller that must own the result uses
/// `Arc::unwrap_or_clone`.
fn memoized<T: Clone>(
&self,
doc: DocId,
@@ -252,7 +256,7 @@ impl SyntaxCache {
version: u32,
slot: impl Fn(&mut Memo) -> &mut Option<Arc<Vec<T>>>,
compute: impl FnOnce() -> Option<Vec<T>>,
) -> Vec<T> {
) -> Arc<Vec<T>> {
let entry = self.entries.lock().get(&doc).cloned();
if let Some(e) = &entry {
let mut e = e.lock();
@@ -260,10 +264,11 @@ impl SyntaxCache {
&& let Some(hit) = slot(&mut e.memo).clone()
{
self.hits.fetch_add(1, Ordering::Relaxed);
return (*hit).clone();
return hit;
}
}
let Some(result) = compute() else { return Vec::new() };
let Some(result) = compute() else { return Arc::new(Vec::new()) };
let result = Arc::new(result);
if let Some(e) = &entry {
let mut e = e.lock();
// Containers without their own grammar memoize their web outline too.
@@ -271,7 +276,7 @@ impl SyntaxCache {
if e.version == version
&& (e.tree.is_some() || (e.lang == *lang && self.syntax.web_grammar_name(lang) == Some("html")))
{
*slot(e.memo.at(version, lang)) = Some(Arc::new(result.clone()));
*slot(e.memo.at(version, lang)) = Some(result.clone());
}
}
result
@@ -426,7 +431,7 @@ mod tests {
let mut doc = Document::new(SRC);
cache.open(id, &rust(), doc.version());
let first = cache.outline(id, &rust(), 0, &doc.text());
assert_eq!(first, cache.syntax().outline(&rust(), SRC));
assert_eq!(first.as_ref(), &cache.syntax().outline(&rust(), SRC));
assert_eq!(cache.stats().full_parses, 1);
cache.folding(id, &rust(), 0, &doc.text());
assert_eq!(cache.stats().hits, 1);
@@ -444,8 +449,16 @@ mod tests {
cache.edit(id, doc.version(), &edits);
let text = doc.text();
let v = doc.version();
assert_eq!(cache.outline(id, &rust(), v, &text), cache.syntax().outline(&rust(), &text), "round {round}");
assert_eq!(cache.folding(id, &rust(), v, &text), cache.syntax().folding(&rust(), &text), "round {round}");
assert_eq!(
cache.outline(id, &rust(), v, &text).as_ref(),
&cache.syntax().outline(&rust(), &text),
"round {round}"
);
assert_eq!(
cache.folding(id, &rust(), v, &text).as_ref(),
&cache.syntax().folding(&rust(), &text),
"round {round}"
);
let off = seed % (doc.len_utf16() + 1);
assert_eq!(
cache.selection_ranges(id, &rust(), v, &text, off),
@@ -481,7 +494,7 @@ mod tests {
cache.edit(id, doc.version(), &edits);
let text = doc.text();
let edited = cache.outline(id, &rust(), 1, &text);
assert_eq!(edited, cache.syntax().outline(&rust(), &text));
assert_eq!(edited.as_ref(), &cache.syntax().outline(&rust(), &text));
assert_ne!(edited, outline);
// Another language at the same version is not answered from the memo.
assert!(cache.outline(id, &LanguageId::new("plaintext"), 1, &text).is_empty());
@@ -504,7 +517,7 @@ mod tests {
cache.edit(id, doc.version(), &edits);
let second = cache.outline(id, &lang, doc.version(), &doc.text());
assert_ne!(second, first);
assert_eq!(second, cache.syntax().outline(&lang, &doc.text()));
assert_eq!(second.as_ref(), &cache.syntax().outline(&lang, &doc.text()));
// An older query must not replace the current version's memo.
cache.outline(id, &lang, 0, "<script>const old = 0;</script>");
let hits = cache.stats().hits;
@@ -528,7 +541,7 @@ mod tests {
let edits = edit(&mut doc, 0, 0, "// y\n");
cache.edit(id, doc.version(), &edits);
let text = doc.text();
assert_eq!(cache.outline(id, &rust(), 2, &text), cache.syntax().outline(&rust(), &text));
assert_eq!(cache.outline(id, &rust(), 2, &text).as_ref(), &cache.syntax().outline(&rust(), &text));
assert_eq!(cache.stats().full_parses, 2, "dropped tree re-parses from scratch");
// A query for a version the cache has not reached is answered but not stored.
+4 -4
Переглянути файл
@@ -2033,9 +2033,9 @@ fn cached_outline_matches_syntax_outline_for_web_documents() {
let id = DocId::next();
let src = "<template><div/></template>\n<script lang=\"ts\">\nconst app = 1;\n</script>\n";
cache.open(id, &lang("vue"), 0);
assert_eq!(cache.outline(id, &lang("vue"), 0, src), syntax().outline(&lang("vue"), src));
assert_eq!(cache.outline(id, &lang("vue"), 0, src).as_ref(), &syntax().outline(&lang("vue"), src));
cache.open(id, &lang("html"), 0);
assert_eq!(cache.outline(id, &lang("html"), 0, src), syntax().outline(&lang("html"), src));
assert_eq!(cache.outline(id, &lang("html"), 0, src).as_ref(), &syntax().outline(&lang("html"), src));
}
#[test]
@@ -2137,7 +2137,7 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() {
let cache = SyntaxCache::new(Arc::new(Syntax::new()));
cache.open(id, &language, 0);
let items = cache.outline(id, &language, 0, src);
assert_eq!(items, syntax().outline(&language, src));
assert_eq!(items.as_ref(), &syntax().outline(&language, src));
assert_eq!(items[0].name, "中文😀");
assert_eq!(items[0].selection_range, Range::new(Pos::new(1, 1), Pos::new(1, 5)));
assert_eq!(items[0].children[0].name, "子章节");
@@ -2146,7 +2146,7 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() {
assert_eq!(items[0].children[1].name, "Other");
let edited = src.replace("子章节", "新章节😀");
let updated = cache.outline(id, &language, 1, &edited);
assert_eq!(updated, syntax().outline(&language, &edited));
assert_eq!(updated.as_ref(), &syntax().outline(&language, &edited));
assert_eq!(updated[0].children[0].selection_range.end, Pos::new(4, 5));
assert_ne!(items, updated);
}
+7 -2
Переглянути файл
@@ -168,8 +168,13 @@ pub fn client_capabilities() -> Value {
"typeHierarchy": { "dynamicRegistration": false }
},
// rust-analyzer: report when the project has loaded (`quiescent`).
// java-analyzer: Spring bean markers of open documents may have changed (`spring_beans.rs`).
"experimental": { "serverStatusNotification": true, "java-analyzer/springBeanMarkersChanged": true },
// java-analyzer: Spring bean and AOP markers of open documents may have changed
// (`spring_beans.rs`, `spring_aop.rs`).
"experimental": {
"serverStatusNotification": true,
"java-analyzer/springBeanMarkersChanged": true,
"java-analyzer/springAopMarkersChanged": true
},
// Jupyter notebooks: code cells are synced with `notebookDocument/*` (see `notebook.rs`).
"notebookDocument": { "synchronization": { "dynamicRegistration": false, "executionSummarySupport": false } }
})
+3
Переглянути файл
@@ -783,6 +783,9 @@ impl Handler for ClientHandler {
crate::spring_beans::CHANGED if self.server.is_live(self.generation) => {
mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::SpringBeanMarkers })
}
crate::spring_aop::CHANGED if self.server.is_live(self.generation) => {
mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::SpringAopMarkers })
}
"window/showMessage" => self.show_message(&mgr, &params),
"window/logMessage" => {
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
+382
Переглянути файл
@@ -0,0 +1,382 @@
//! One background JDT builder per overlapping physical workspace on a host.
//! Windows keep their own documents and language-service settings. An explicit
//! build borrows the output directories from the background builder instead of
//! letting two Eclipse workspaces write them at the same time.
use crate::server::{Running, Server};
use ide_core::{CancellationToken, IdeError, IdeResult, ServerId};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::sync::Notify;
#[derive(Default)]
pub struct JavaBuildCoordinator {
state: Mutex<State>,
changed: Notify,
}
type Instance = (ServerId, u64);
#[derive(Default)]
struct State {
entries: Vec<Entry>,
builds: Vec<Build>,
}
struct Entry {
instance: Instance,
server: Weak<Server>,
roots: Vec<PathBuf>,
}
struct Build {
instance: Instance,
roots: Vec<PathBuf>,
}
fn intersections<'a>(a: &'a [PathBuf], b: &'a [PathBuf]) -> impl Iterator<Item = &'a Path> {
a.iter().flat_map(move |a| {
b.iter().filter_map(move |b| {
if a.starts_with(b) {
Some(a.as_path())
} else if b.starts_with(a) {
Some(b.as_path())
} else {
None
}
})
})
}
impl State {
/// Keep the first live writer. A broader, later workspace is still useful for
/// analysis; an explicit build in it can borrow the overlapping writer's turn.
fn update_owners(&self) -> Vec<(Arc<Server>, u64, Vec<PathBuf>)> {
let mut writers: Vec<&Entry> = Vec::new();
let mut paused = Vec::new();
for entry in &self.entries {
let Some(server) = entry.server.upgrade() else { continue };
let shadowed = writers.iter().any(|writer| intersections(&writer.roots, &entry.roots).next().is_some());
if !shadowed {
writers.push(entry);
}
let borrowed = self.builds.iter().find(|build| {
build.instance != entry.instance && intersections(&build.roots, &entry.roots).next().is_some()
});
let suspended = shadowed || borrowed.is_some();
let previous = server.java_coordinated_autobuild_suspended.swap(suspended, Ordering::SeqCst);
if previous != suspended {
if let Some(run) = server.initialized_gen(entry.instance.1) {
let settings = crate::handler::all_settings(&server.effective_config());
if let Err(error) =
run.peer.notify("workspace/didChangeConfiguration", json!({ "settings": settings }))
{
tracing::debug!(%error, "jdtls: updating coordinated autobuild");
}
}
if suspended && let Some(build) = borrowed {
let roots = intersections(&build.roots, &entry.roots).map(Path::to_path_buf).collect();
paused.push((server, entry.instance.1, roots));
}
}
}
paused
}
}
impl JavaBuildCoordinator {
pub(crate) async fn register(
self: &Arc<Self>,
server: &Arc<Server>,
generation: u64,
roots: Vec<PathBuf>,
cancel: &CancellationToken,
) -> IdeResult<Registration> {
let roots = roots.into_iter().map(|p| dunce::canonicalize(&p).unwrap_or(p)).collect::<Vec<_>>();
let instance = (server.id, generation);
loop {
let changed = self.changed.notified();
tokio::pin!(changed);
changed.as_mut().enable();
{
let mut state = self.state.lock();
if !state.builds.iter().any(|build| intersections(&build.roots, &roots).next().is_some()) {
state.entries.retain(|entry| entry.instance.0 != server.id && entry.server.strong_count() != 0);
state.entries.push(Entry { instance, server: Arc::downgrade(server), roots });
state.update_owners();
return Ok(Registration { coordinator: self.clone(), instance });
}
}
crate::jdtls::cancellable_wait(cancel, changed).await?;
}
}
pub(crate) async fn acquire(
self: &Arc<Self>,
server: &Server,
generation: u64,
cancel: &CancellationToken,
) -> IdeResult<BuildPermit> {
let instance = (server.id, generation);
let (permit, paused) = loop {
let changed = self.changed.notified();
tokio::pin!(changed);
changed.as_mut().enable();
{
let mut state = self.state.lock();
let roots = state
.entries
.iter()
.find(|entry| entry.instance == instance)
.ok_or_else(|| IdeError::unavailable("Java workspace stopped before building"))?
.roots
.clone();
if !state.builds.iter().any(|build| intersections(&build.roots, &roots).next().is_some()) {
state.builds.push(Build { instance, roots: roots.clone() });
let permit = BuildPermit { coordinator: self.clone(), instance, roots, outstanding: None };
break (permit, state.update_owners());
}
}
crate::jdtls::cancellable_wait(cancel, changed).await?;
};
// Configuration stops scheduling new automatic builds. The classpath
// request takes the Eclipse project scheduling rule, draining a build
// already in progress before the borrower touches the same outputs.
for (writer, generation, roots) in paused {
let run = tokio::select! {
ready = crate::jdtls::cancellable_wait(cancel, writer.wait_ready(Duration::from_secs(240))) => ready?,
retired = self.wait_retired((writer.id, generation), cancel) => {
retired?;
continue;
}
};
let Some(run) = run.filter(|run| run.generation == generation) else {
if !writer.is_live(generation) {
self.wait_retired((writer.id, generation), cancel).await?;
continue;
}
return Err(IdeError::unavailable("Overlapping Java workspace is still starting; retry the build"));
};
if crate::java_project::reports_import(&writer) {
let ready = crate::jdtls::cancellable_wait(
cancel,
tokio::time::timeout(Duration::from_secs(240), writer.wait_java_ready(generation)),
)
.await?;
if !matches!(ready, Ok(true)) {
if !writer.is_live(generation) {
self.wait_retired((writer.id, generation), cancel).await?;
continue;
}
return Err(IdeError::unavailable(
"Overlapping Java workspace is still importing; retry the build",
));
}
}
let result = crate::jdtls::cancellable_wait(cancel, drain(&run, &roots, Some(cancel.clone()))).await?;
if let Err(error) = result {
if writer.is_live(generation) {
return Err(error);
}
self.wait_retired((writer.id, generation), cancel).await?;
}
}
Ok(permit)
}
/// Stopping changes the server status before its JVM has released the
/// output files. Wait for reaping, not merely for the transport to close.
async fn wait_retired(&self, instance: Instance, cancel: &CancellationToken) -> IdeResult<()> {
let wait = async {
loop {
let changed = self.changed.notified();
tokio::pin!(changed);
changed.as_mut().enable();
if !self.state.lock().entries.iter().any(|entry| entry.instance == instance) {
return;
}
changed.await;
}
};
crate::jdtls::cancellable_wait(cancel, tokio::time::timeout(Duration::from_secs(240), wait))
.await?
.map_err(|_| IdeError::unavailable("Overlapping Java workspace has not stopped; retry the build"))
}
}
/// Query the project's classpaths under its Eclipse scheduling rule. An
/// ancestor can contain multiple Maven projects, and need not itself be a Java
/// project. Check the actual imported projects rather than the directory alone.
async fn drain(run: &Running, roots: &[PathBuf], cancel: Option<CancellationToken>) -> IdeResult<()> {
let command = |name: &str, args: Value| {
let cancel = cancel.clone();
let peer = run.peer.clone();
let params = json!({"command": name, "arguments": args});
async move {
tokio::time::timeout(
Duration::from_secs(240),
peer.request::<_, Value>("workspace/executeCommand", params, cancel),
)
.await
.map_err(|_| IdeError::unavailable("Overlapping Java workspace is still building; retry the build"))?
.map_err(|e| crate::rpc_err("jdtls", "workspace/executeCommand", e))
}
};
let projects = command("java.project.getAll", json!([])).await?;
let paths = match projects.as_array() {
Some(projects) => projects
.iter()
.filter_map(Value::as_str)
.filter_map(crate::jdtls::project_path)
.map(|p| dunce::canonicalize(&p).unwrap_or(p))
.filter(|p| roots.iter().any(|root| p.starts_with(root)))
.collect::<Vec<_>>(),
None => roots.to_vec(),
};
for project in paths {
command("java.project.getClasspaths", json!([crate::path_to_uri_string(&project), "{\"scope\":\"runtime\"}"]))
.await?;
}
Ok(())
}
/// Owned by the actual server instance until its JVM exits, not by the window.
/// Closing the first window promotes the next compatible background writer.
pub(crate) struct Registration {
coordinator: Arc<JavaBuildCoordinator>,
instance: Instance,
}
impl Drop for Registration {
fn drop(&mut self) {
self.coordinator.retire(self.instance.0, self.instance.1);
}
}
pub(crate) struct BuildPermit {
coordinator: Arc<JavaBuildCoordinator>,
instance: Instance,
roots: Vec<PathBuf>,
outstanding: Option<Running>,
}
impl BuildPermit {
pub(crate) fn started(&mut self, run: &Running) {
self.outstanding = Some(run.clone());
}
pub(crate) fn finished(&mut self) {
self.outstanding = None;
}
}
impl JavaBuildCoordinator {
pub(crate) fn retire(&self, server: ServerId, generation: u64) {
let mut state = self.state.lock();
state.entries.retain(|entry| entry.instance != (server, generation));
state.update_owners();
self.changed.notify_waiters();
}
fn release(&self, instance: Instance) {
let mut state = self.state.lock();
state.builds.retain(|build| build.instance != instance);
state.update_owners();
self.changed.notify_waiters();
}
}
impl Drop for BuildPermit {
fn drop(&mut self) {
let overlapping = {
let state = self.coordinator.state.lock();
state.builds.iter().find(|build| build.instance == self.instance).is_some_and(|build| {
state.entries.iter().any(|entry| {
entry.instance != self.instance && intersections(&build.roots, &entry.roots).next().is_some()
})
})
};
if let Some(run) = self.outstanding.take().filter(|_| overlapping) {
// A cancelled JSON-RPC request can return before Eclipse stops the
// compiler. Don't re-enable another writer until its scheduling
// rule is free, even if the outer future was dropped.
let coordinator = self.coordinator.clone();
let instance = self.instance;
let roots = std::mem::take(&mut self.roots);
tokio::spawn(async move {
if drain(&run, &roots, None).await.is_err() {
run.peer.kill();
run.peer.exited().await;
}
coordinator.release(instance);
});
} else {
self.coordinator.release(self.instance);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::LanguageId;
use ide_language::LanguageServerConfig;
fn server(root: &Path) -> Arc<Server> {
let cfg: LanguageServerConfig = serde_json::from_value(json!({"name": "jdtls", "command": "jdtls"})).unwrap();
Arc::new(Server::new(cfg, root.to_path_buf(), LanguageId::new("java")))
}
fn suspended(server: &Server) -> bool {
server.java_coordinated_autobuild_suspended.load(Ordering::SeqCst)
}
#[tokio::test]
async fn overlapping_windows_have_one_background_writer_and_promote_on_close() {
let tmp = tempfile::tempdir().unwrap();
let parent = tmp.path().join("parent");
let child = parent.join("child");
let independent = tmp.path().join("independent");
std::fs::create_dir_all(&child).unwrap();
std::fs::create_dir_all(&independent).unwrap();
let (a, b, c) = (server(&parent), server(&child), server(&independent));
let coordinator = Arc::new(JavaBuildCoordinator::default());
let cancel = CancellationToken::new();
let a_reg = coordinator.register(&a, 1, vec![parent], &cancel).await.unwrap();
let _b_reg = coordinator.register(&b, 1, vec![child], &cancel).await.unwrap();
let _c_reg = coordinator.register(&c, 1, vec![independent], &cancel).await.unwrap();
assert!(!suspended(&a));
assert!(suspended(&b));
assert!(!suspended(&c));
drop(a_reg);
assert!(!suspended(&b));
}
#[tokio::test]
async fn explicit_builds_of_overlapping_workspaces_wait_but_disjoint_builds_do_not() {
let tmp = tempfile::tempdir().unwrap();
let parent = tmp.path().join("parent");
let child = parent.join("child");
let independent = tmp.path().join("independent");
std::fs::create_dir_all(&child).unwrap();
std::fs::create_dir_all(&independent).unwrap();
let (a, b, c) = (server(&parent), server(&child), server(&independent));
let coordinator = Arc::new(JavaBuildCoordinator::default());
let cancel = CancellationToken::new();
let _a_reg = coordinator.register(&a, 1, vec![parent], &cancel).await.unwrap();
let _b_reg = coordinator.register(&b, 1, vec![child], &cancel).await.unwrap();
let _c_reg = coordinator.register(&c, 1, vec![independent], &cancel).await.unwrap();
let _a_build = coordinator.acquire(&a, 1, &cancel).await.unwrap();
let _c_build = coordinator.acquire(&c, 1, &cancel).await.unwrap();
assert!(tokio::time::timeout(Duration::from_millis(20), coordinator.acquire(&b, 1, &cancel)).await.is_err());
assert!(suspended(&b));
let stopped = CancellationToken::new();
stopped.cancel();
assert!(coordinator.acquire(&b, 1, &stopped).await.is_err());
}
}
+37 -9
Переглянути файл
@@ -267,7 +267,7 @@ fn cache_owned_maven_settings(root: &Path) -> bool {
root.join("pom.xml").is_file() && matches!(root.join(".settings").try_exists(), Ok(false))
}
fn project_path(uri: &str) -> Option<PathBuf> {
pub(crate) fn project_path(uri: &str) -> Option<PathBuf> {
// jdtls commands use Java's `file:/p` as well as LSP's `file:///p`.
let normalized = match uri.strip_prefix("file:") {
Some(rest) if !rest.starts_with("//") => format!("file://{rest}"),
@@ -350,6 +350,7 @@ pub struct JavaExternalBuild {
server: Arc<Server>,
run: Running,
_lock: tokio::sync::OwnedMutexGuard<()>,
_permit: crate::java_build_coordinator::BuildPermit,
}
impl Drop for JavaExternalBuild {
@@ -939,6 +940,19 @@ impl LspManager {
let started = Instant::now();
let (server, run) = self.jdtls(path, cancel).await?;
let ready_ms = started.elapsed().as_millis();
Self::jdtls_instance_request(&server, &run, method, params, timeout, cancel, ready_ms).await
}
async fn jdtls_instance_request(
server: &Server,
run: &Running,
method: &str,
params: Value,
timeout: Duration,
cancel: &CancellationToken,
ready_ms: u128,
) -> IdeResult<Value> {
let started = Instant::now();
let phase = params.get("command").and_then(Value::as_str).unwrap_or(method).to_owned();
let fut = run.peer.request::<Value, Value>(method, params, Some(cancel.clone()));
let result = match tokio::time::timeout(timeout, fut).await {
@@ -954,7 +968,7 @@ impl LspManager {
tracing::info!(
phase,
ready_ms,
request_ms = started.elapsed().as_millis() - ready_ms,
request_ms = started.elapsed().as_millis(),
success = result.is_ok(),
"Java launch request"
);
@@ -1131,9 +1145,14 @@ impl LspManager {
/// Keep this guard until Maven outputs have been copied out of JDT's reach.
pub async fn java_external_build(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<JavaExternalBuild> {
let (server, run) = self.jdtls(path, cancel).await?;
let coordinator = self.java_build_coordinator.read().clone();
let permit = coordinator.acquire(&server, run.generation, cancel).await?;
let lock = cancellable_wait(cancel, server.java_build_lock.clone().lock_owned()).await?;
if !server.is_live(run.generation) {
return Err(IdeError::unavailable("Java workspace stopped before building"));
}
server.java_autobuild_suspended.store(true, std::sync::atomic::Ordering::SeqCst);
let guard = JavaExternalBuild { server, run, _lock: lock };
let guard = JavaExternalBuild { server, run, _lock: lock, _permit: permit };
let settings = crate::handler::all_settings(&guard.server.effective_config());
guard
.run
@@ -1147,19 +1166,28 @@ impl LspManager {
/// class files are up to date before a launch.
/// `full` asks jdtls for a clean build (`java/buildWorkspace(true)`, IDEA's Rebuild).
pub async fn java_build(&self, path: &Path, full: bool, cancel: &CancellationToken) -> IdeResult<JavaBuildStatus> {
let (server, _) = self.jdtls(path, cancel).await?;
let _lock = cancellable_wait(cancel, server.java_build_lock.lock()).await?;
let mut v = self.jdtls_request(path, "java/buildWorkspace", json!(full), BUILD_TIMEOUT, cancel).await?;
// The first build can finish the Maven import before ServiceReady is handled.
let (server, run) = self.jdtls(path, cancel).await?;
let coordinator = self.java_build_coordinator.read().clone();
let mut permit = coordinator.acquire(&server, run.generation, cancel).await?;
let _lock = cancellable_wait(cancel, server.java_build_lock.lock()).await?;
permit.started(&run);
let request = || {
Self::jdtls_instance_request(&server, &run, "java/buildWorkspace", json!(full), BUILD_TIMEOUT, cancel, 0)
};
let mut v = request().await?;
// The first build can finish the Maven import before ServiceReady is handled.
let changed = cancellable_wait(cancel, self.java_configure_compiler(&server, &run)).await??;
// ServiceReady can update the options concurrently with that first build.
let recheck = v.as_i64() == Some(2)
&& compiler_defaults(&server.effective_config()).as_object().is_some_and(|o| !o.is_empty());
if changed || recheck {
v = self.jdtls_request(path, "java/buildWorkspace", json!(full), BUILD_TIMEOUT, cancel).await?;
v = request().await?;
}
Ok(JavaBuildStatus::from_code(v.as_i64().unwrap_or(0)))
let status = JavaBuildStatus::from_code(v.as_i64().unwrap_or(0));
if status != JavaBuildStatus::Cancelled {
permit.finished();
}
Ok(status)
}
/// Runtime (`test == false`) or test classpath of the project containing `path`.
+35 -4
Переглянути файл
@@ -23,6 +23,7 @@ mod go_scope;
mod handler;
mod injections;
mod inspect;
mod java_build_coordinator;
pub mod java_project;
pub mod jdtls;
mod kotlin_lsp;
@@ -40,6 +41,7 @@ mod roslyn;
mod scope;
mod server;
mod source_actions;
mod spring_aop;
mod spring_beans;
mod switch_source_header;
mod tcp;
@@ -57,6 +59,7 @@ mod xml_comment;
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions};
pub use java_build_coordinator::JavaBuildCoordinator;
pub use jdtls::exception_breakpoints::JdtExceptionBreakpoints;
pub use jdtls::jvm_inspect::JdtJvmInspector;
pub use jdtls::stream_trace::JdtStreamTracer;
@@ -337,6 +340,7 @@ pub struct LspManager {
jdtls_shared_hook: RwLock<Option<Arc<JdtlsSharedFn>>>,
locale_hook: RwLock<Option<Arc<LocaleFn>>>,
jdtls_workspace: Mutex<JdtlsWorkspace>,
java_build_coordinator: RwLock<Arc<JavaBuildCoordinator>>,
reconfigure_lock: tokio::sync::Mutex<()>,
shutting_down: AtomicBool,
execution_allowed: AtomicBool,
@@ -668,6 +672,7 @@ impl LspManager {
jdtls_shared_hook: RwLock::new(None),
locale_hook: RwLock::new(None),
jdtls_workspace: Mutex::new(Default::default()),
java_build_coordinator: RwLock::new(Arc::default()),
reconfigure_lock: tokio::sync::Mutex::new(()),
shutting_down: AtomicBool::new(false),
execution_allowed: AtomicBool::new(true),
@@ -728,6 +733,11 @@ impl LspManager {
self.jdtls_import_roots.read().clone()
}
/// Coordinates Java builders across all project windows of the host.
pub fn set_java_build_coordinator(&self, coordinator: Arc<JavaBuildCoordinator>) {
*self.java_build_coordinator.write() = coordinator;
}
/// Shares JDT LS within this manager; callers reconfigure after the hook's value changes.
pub fn set_jdtls_shared_hook(&self, hook: Box<JdtlsSharedFn>) {
*self.jdtls_shared_hook.write() = Some(Arc::from(hook));
@@ -1081,6 +1091,15 @@ impl LspManager {
async fn run_instance(self: Arc<Self>, server: Arc<Server>, generation: u64) {
let Some(cancel) = server.starting_status(generation, &self.sink) else { return };
let registration = if is_local_jdtls(&server.config) {
let coordinator = self.java_build_coordinator.read().clone();
match coordinator.register(&server, generation, self.server_workspace_roots(&server), &cancel).await {
Ok(registration) => Some(registration),
Err(_) => return,
}
} else {
None
};
// Includes settings/prepare, blocking-pool queueing, launch and initialize.
let started = std::time::Instant::now();
tracing::info!(server = ?server.id, generation, name = %server.name, "starting language server");
@@ -1241,7 +1260,7 @@ impl LspManager {
}
Self::kill_peer(&server, &peer).await;
// Treated like a crash so transient failures retry with backoff.
self.spawn_supervisor(server, generation, peer);
self.spawn_supervisor(server, generation, peer, registration);
return;
}
};
@@ -1308,13 +1327,24 @@ impl LspManager {
self.check_vue_navigation(&server).await;
server.refresh_busy_status(&self.sink);
server.announce_ready(generation);
self.spawn_supervisor(server, generation, peer);
self.spawn_supervisor(server, generation, peer, registration);
}
fn spawn_supervisor(&self, server: Arc<Server>, generation: u64, peer: ide_jsonrpc::Peer) {
fn spawn_supervisor(
&self,
server: Arc<Server>,
generation: u64,
peer: ide_jsonrpc::Peer,
registration: Option<java_build_coordinator::Registration>,
) {
let weak = self.me.clone();
self.runtime.spawn(async move {
let code = peer.closed().await;
if registration.is_some() && peer.pid().is_some() {
peer.kill();
peer.exited().await;
}
drop(registration);
if let Some(me) = weak.upgrade() {
me.on_instance_closed(server, generation, code).await;
}
@@ -4722,7 +4752,7 @@ impl LspManager {
continue;
}
};
let current = s.effective_config();
let current = s.instance_config();
let locale_changed = s.effective_locale().is_some_and(|l| l != next_locale);
if next == current && !locale_changed {
continue;
@@ -5034,6 +5064,7 @@ impl LspManager {
Self::kill_peer(server, &peer).await;
if is_local_jdtls(&server.config) {
let _startup = server.startup_lock.lock().await;
self.java_build_coordinator.read().retire(server.id, run.generation);
}
server.end_stop(run.generation, &self.sink);
self.file_watch_roots_changed();
+11 -2
Переглянути файл
@@ -207,6 +207,7 @@ pub struct Server {
/// JDT retirement waits for launch and initialization cleanup, even before `Ready`.
pub startup_lock: Arc<tokio::sync::Mutex<()>>,
pub java_autobuild_suspended: std::sync::atomic::AtomicBool,
pub java_coordinated_autobuild_suspended: std::sync::atomic::AtomicBool,
pub external_project: tokio::sync::Mutex<crate::external_project::State>,
pub external_diagnostics: std::sync::atomic::AtomicBool,
pub external_refresh_queued: std::sync::atomic::AtomicBool,
@@ -262,6 +263,7 @@ impl Server {
java_absent_outputs: Mutex::new(Default::default()),
startup_lock: Arc::new(tokio::sync::Mutex::new(())),
java_autobuild_suspended: std::sync::atomic::AtomicBool::new(false),
java_coordinated_autobuild_suspended: std::sync::atomic::AtomicBool::new(false),
external_project: tokio::sync::Mutex::new(Default::default()),
external_diagnostics: std::sync::atomic::AtomicBool::new(false),
external_refresh_queued: std::sync::atomic::AtomicBool::new(false),
@@ -273,8 +275,10 @@ impl Server {
/// Configuration of the current (or last) instance; the base config before the first launch.
pub fn effective_config(&self) -> LanguageServerConfig {
let mut config = self.effective.lock().clone().unwrap_or_else(|| self.config.clone());
if self.java_autobuild_suspended.load(std::sync::atomic::Ordering::SeqCst) {
let mut config = self.instance_config();
if self.java_autobuild_suspended.load(std::sync::atomic::Ordering::SeqCst)
|| self.java_coordinated_autobuild_suspended.load(std::sync::atomic::Ordering::SeqCst)
{
let mut settings = crate::handler::all_settings(&config);
settings["java"]["autobuild"]["enabled"] = serde_json::json!(false);
config.settings = Some(settings);
@@ -282,6 +286,11 @@ impl Server {
config
}
/// Settings used to launch the instance, before temporary builder suspension.
pub fn instance_config(&self) -> LanguageServerConfig {
self.effective.lock().clone().unwrap_or_else(|| self.config.clone())
}
/// The configured server's display name for the current (or last) instance.
pub fn display_name(&self) -> Option<String> {
self.effective.lock().as_ref().and_then(|c| c.display_name.clone())
+103
Переглянути файл
@@ -0,0 +1,103 @@
//! Spring AOP markers of a Java document: advised methods with the advices applied to them, and
//! advice methods with the methods they advise. The first source is java-analyzer's
//! `java-analyzer/springAopMarkers`, one request per document; its answer is turned into the
//! server-independent [`SpringAopMarker`]s the gutter shows.
use crate::types::{SpringAopAdviceKind, SpringAopDirection, SpringAopMarker, SpringAopTarget};
use crate::{LspManager, Target, lsp};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Range};
use serde::Deserialize;
use serde_json::json;
use std::time::Duration;
/// `{ textDocument: { uri } }` → `{ markers: [{ range, name, direction, targets: [{ location, label, adviceKind, order }] }] }`.
pub(crate) const METHOD: &str = "java-analyzer/springAopMarkers";
/// Sent by the server, to clients that declare it, when markers of open documents may have changed.
pub(crate) const CHANGED: &str = "java-analyzer/springAopMarkersChanged";
/// The first answer of a large workspace pairs every advised method with its advices.
const TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Deserialize)]
struct Answer {
markers: Vec<WireMarker>,
}
#[derive(Deserialize)]
struct WireMarker {
range: lsp::Range,
name: String,
direction: SpringAopDirection,
targets: Vec<WireTarget>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireTarget {
location: lsp::Location,
label: String,
#[serde(default)]
advice_kind: Option<SpringAopAdviceKind>,
#[serde(default)]
order: Option<i32>,
}
impl LspManager {
/// The document's Spring AOP markers; `None` when no server attached to it provides them
/// (jdtls, an older java-analyzer, a server not running yet), without asking any server.
pub async fn spring_aop_markers(
&self,
doc: DocId,
cancel: CancellationToken,
) -> IdeResult<Option<Vec<SpringAopMarker>>> {
let snap = self.snapshot(doc)?;
// Only an instance the document is open on: waiting for servers to start would hold
// every Java file of a jdtls project for a background feature.
let source = self.docs.lock().get(&doc).and_then(|d| {
d.servers.iter().find_map(|a| {
let run = a.server.running()?;
let provides = {
let caps = run.caps.read();
// AOP markers are implementation navigation: `features` without it leave it out.
caps.restriction.implementation() && caps.raw["experimental"][METHOD] == true
};
(provides && a.opened_gen == Some(run.generation)).then(|| Target::new(a.server.clone(), run))
})
});
let Some(target) = source else { return Ok(None) };
let answer: Option<Answer> =
self.call(&target, METHOD, json!({ "textDocument": snap.ident() }), Some(&cancel), TIMEOUT).await?;
// Ranges are read against the text the request was made for.
if self.snapshot(doc)?.version != snap.version {
return Err(IdeError::cancelled());
}
let enc = target.enc();
let conv = self.conv(enc);
let pos = |p| snap.text.lsp_to_ide(enc, p);
let markers = answer.map_or_else(Vec::new, |a| a.markers);
Ok(Some(
markers
.into_iter()
.filter_map(|m| {
let targets: Vec<_> = m
.targets
.into_iter()
.filter_map(|t| {
Some(SpringAopTarget {
location: conv.location(&t.location)?,
label: t.label,
advice_kind: t.advice_kind,
order: t.order,
})
})
.collect();
(!targets.is_empty()).then(|| SpringAopMarker {
range: Range::new(pos(m.range.start), pos(m.range.end)),
name: m.name,
direction: m.direction,
targets,
})
})
.collect(),
))
}
}
+43
Переглянути файл
@@ -840,3 +840,46 @@ pub enum SpringBeanResolution {
Resolved,
Candidate,
}
/// A Spring AOP marker on a Java method: an advised method (`ToAdvice`) or an advice
/// method (`ToAdvised`), whichever server found it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SpringAopMarker {
/// The method's name range.
pub range: Range,
pub name: String,
pub direction: SpringAopDirection,
/// Never empty.
pub targets: Vec<SpringAopTarget>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SpringAopDirection {
/// On an advised method: its targets are the advices applied to it.
ToAdvice,
/// On an advice method: its targets are the methods it advises.
ToAdvised,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SpringAopTarget {
pub location: Location,
pub label: String,
/// Set on an advice target; `None` on an advised method.
pub advice_kind: Option<SpringAopAdviceKind>,
/// The advice's Spring `order`; `None` when it has none.
pub order: Option<i32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SpringAopAdviceKind {
Before,
After,
AfterReturning,
AfterThrowing,
Around,
}
+177 -1
Переглянути файл
@@ -315,7 +315,14 @@ type MockLanguage<'a> = (&'a str, &'a str, &'a [(&'a str, Value)]);
/// Several languages; documents open as the first.
fn harness_languages(languages: &[MockLanguage<'_>], adjust: impl Fn(&mut LanguageServerConfig)) -> Harness {
let dir = tempfile::tempdir().unwrap();
harness_languages_in(tempfile::tempdir().unwrap(), languages, adjust)
}
fn harness_languages_in(
dir: tempfile::TempDir,
languages: &[MockLanguage<'_>],
adjust: impl Fn(&mut LanguageServerConfig),
) -> Harness {
// Edits and references report canonical paths.
let root = dunce::canonicalize(dir.path()).unwrap();
let configs = languages
@@ -3320,6 +3327,91 @@ async fn java_build_waits_for_a_reconfigured_server_to_restart() {
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_overlapping_windows_coordinate_autobuild_and_explicit_builds() {
let configure = |cfg: &mut LanguageServerConfig| {
cfg.settings = Some(json!({"java": {"autobuild": {"enabled": true}}}));
};
let parent = harness_configured("java", "java", &[("jdtls", incremental_caps())], configure);
let child = harness_languages_in(
tempfile::tempdir_in(&parent.root).unwrap(),
&[("java", "java", &[("jdtls", incremental_caps())])],
configure,
);
let coordinator = Arc::new(ide_lsp::JavaBuildCoordinator::default());
parent.mgr.set_java_build_coordinator(coordinator.clone());
child.mgr.set_java_build_coordinator(coordinator);
parent.open("Parent.java", "class Parent {}");
parent.wait_status("jdtls", ServerStatus::Ready).await;
child.open("Child.java", "class Child {}");
child.wait_status("jdtls", ServerStatus::Ready).await;
let (primary, secondary) = (parent.launcher.state("jdtls"), child.launcher.state("jdtls"));
assert_eq!(
primary.requested("initialize")[0]["initializationOptions"]["settings"]["java"]["autobuild"]["enabled"],
true
);
assert_eq!(
secondary.requested("initialize")[0]["initializationOptions"]["settings"]["java"]["autobuild"]["enabled"],
false
);
child.mgr.reconfigure().await;
assert_eq!(secondary.launches.load(Ordering::SeqCst), 1);
primary.respond("workspace/executeCommand", json!({}));
primary.peer().notify("language/status", json!({"type": "ServiceReady", "message": "ServiceReady"})).unwrap();
secondary.respond("java/buildWorkspace", json!(1));
assert_eq!(
child.mgr.java_build(&child.root, false, &Default::default()).await.unwrap(),
ide_lsp::jdtls::JavaBuildStatus::Succeeded
);
assert!(primary.requested("workspace/executeCommand").iter().any(|p| p["command"] == "java.project.getClasspaths"));
eventually(|| {
primary
.notified("workspace/didChangeConfiguration")
.last()
.is_some_and(|p| p["settings"]["java"]["autobuild"]["enabled"] == true)
})
.await;
assert!(
primary
.notified("workspace/didChangeConfiguration")
.iter()
.any(|p| p["settings"]["java"]["autobuild"]["enabled"] == false)
);
assert!(
secondary
.notified("workspace/didChangeConfiguration")
.iter()
.all(|p| p["settings"]["java"]["autobuild"]["enabled"] == false)
);
// Down is published before the JVM has exited. A child build must wait
// for the old writer to release the workspace, not just for that status.
let exit = Arc::new(Gate::default());
*primary.held.lock() = Some(("exit".into(), exit.clone()));
let shutdown = tokio::spawn({
let mgr = parent.mgr.clone();
async move { mgr.shutdown_all().await }
});
eventually(|| exit.entered()).await;
let mut build = tokio::spawn({
let (mgr, root) = (child.mgr.clone(), child.root.clone());
async move { mgr.java_build(&root, false, &Default::default()).await }
});
let early = tokio::time::timeout(Duration::from_millis(100), &mut build).await;
exit.open();
shutdown.await.unwrap();
assert!(early.is_err(), "the child must wait for the first writer to exit: {early:?}");
assert_eq!(build.await.unwrap().unwrap(), ide_lsp::jdtls::JavaBuildStatus::Succeeded);
eventually(|| {
secondary
.notified("workspace/didChangeConfiguration")
.last()
.is_some_and(|p| p["settings"]["java"]["autobuild"]["enabled"] == true)
})
.await;
child.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_build_asks_for_a_full_build_when_rebuilding() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
@@ -11014,3 +11106,87 @@ async fn move_without_the_pair_on_java_analyzer_says_so() {
assert!(err.message.starts_with("java-analyzer doesn't support Move"), "{}", err.message);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn spring_aop_markers_come_from_the_server_that_declares_them() {
let mut caps = incremental_caps();
caps["positionEncoding"] = json!("utf-8");
caps["experimental"] = json!({ "java-analyzer/springAopMarkers": true });
let h = harness(&[("aop", caps), ("plain", incremental_caps())]);
// "é😀" is 3 UTF-16 units and 6 bytes before `clock`.
let (doc, path) = h.open("a.mk", "é😀clock;\nclass App {}\n");
for name in ["aop", "plain"] {
h.wait_status(name, ServerStatus::Ready).await;
}
let (aop, plain) = (h.launcher.state("aop"), h.launcher.state("plain"));
eventually(|| !aop.notified("textDocument/didOpen").is_empty()).await;
let init = &aop.requested("initialize")[0];
assert_eq!(init["capabilities"]["experimental"]["java-analyzer/springAopMarkersChanged"], true);
let at = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}});
aop.respond(
"java-analyzer/springAopMarkers",
json!({ "markers": [
{ "range": at(0, 6, 11), "name": "clock", "direction": "toAdvice", "targets": [
{ "location": { "uri": uri_of(&path), "range": at(1, 6, 9) }, "label": "logBefore", "adviceKind": "before", "order": 1 },
{ "location": { "uri": uri_of(&path), "range": at(0, 0, 2) }, "label": "é", "adviceKind": "around", "order": null },
] },
{ "range": at(1, 6, 9), "name": "App", "direction": "toAdvised", "targets": [
{ "location": { "uri": uri_of(&path), "range": at(0, 3, 8) }, "label": "clock", "adviceKind": null, "order": null },
] },
{ "range": at(1, 0, 3), "name": "App", "direction": "toAdvised", "targets": [] },
] }),
);
let markers = h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap().unwrap();
assert_eq!(aop.requested("java-analyzer/springAopMarkers")[0], json!({ "textDocument": { "uri": uri_of(&path) } }));
assert!(plain.requested("java-analyzer/springAopMarkers").is_empty());
// The marker without targets is dropped; positions are UTF-16 in every file.
assert_eq!(markers.len(), 2);
assert_eq!(markers[0].range, rng(0, 3, 0, 8));
assert_eq!(markers[0].direction, SpringAopDirection::ToAdvice);
assert_eq!(markers[0].targets[0].location.range, rng(1, 6, 1, 9));
assert_eq!(markers[0].targets[0].advice_kind, Some(SpringAopAdviceKind::Before));
assert_eq!(markers[0].targets[0].order, Some(1));
assert_eq!(markers[0].targets[1].location.range, rng(0, 0, 0, 1));
assert_eq!(markers[0].targets[1].advice_kind, Some(SpringAopAdviceKind::Around));
assert_eq!(markers[0].targets[1].order, None);
assert_eq!(markers[1].direction, SpringAopDirection::ToAdvised);
assert_eq!(markers[1].targets[0].advice_kind, None);
assert_eq!(markers[1].targets[0].order, None);
let refreshes = || {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SpringAopMarkers, .. }))
.count()
};
aop.peer().notify("java-analyzer/springAopMarkersChanged", json!({})).unwrap();
eventually(|| refreshes() == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn spring_aop_markers_ask_no_server_without_the_capability() {
let h = harness(&[("plain", incremental_caps())]);
let (doc, _) = h.open("a.mk", "class App {}\n");
// Not ready yet: no wait for it to start.
assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None);
h.wait_status("plain", ServerStatus::Ready).await;
let plain = h.launcher.state("plain");
eventually(|| !plain.notified("textDocument/didOpen").is_empty()).await;
assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None);
assert!(plain.requested("java-analyzer/springAopMarkers").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn spring_aop_markers_follow_the_servers_features() {
let mut caps = incremental_caps();
caps["experimental"] = json!({ "java-analyzer/springAopMarkers": true });
// Used for diagnostics only: no navigation from it, AOP markers included.
let h = harness_configured("mock", "mk", &[("aop", caps)], |cfg| cfg.features = vec!["diagnostics".into()]);
let (doc, _) = h.open("a.mk", "class App {}\n");
h.wait_status("aop", ServerStatus::Ready).await;
let aop = h.launcher.state("aop");
eventually(|| !aop.notified("textDocument/didOpen").is_empty()).await;
assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None);
assert!(aop.requested("java-analyzer/springAopMarkers").is_empty());
}
+81
Переглянути файл
@@ -2152,3 +2152,84 @@ async fn some_sass_indented_end_to_end() {
assert!(errors.iter().any(|d| d.range.start.line >= 5), "{errors:?}");
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// #7733: opening a reactor and its child in independent windows must not
/// run a second automatic compiler over the existing Maven output directories.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires jdtls on PATH (or OPENIDEA_TEST_JDTLS), a compatible JDK and Maven"]
async fn jdtls_overlapping_windows_do_not_rebuild_the_same_maven_outputs() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap().join("reactor");
let child = root.join("core");
let source = child.join("src/main/java/demo/Greeter.java");
std::fs::create_dir_all(source.parent().unwrap()).unwrap();
std::fs::write(root.join("pom.xml"), r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>reactor</artifactId><version>1</version><packaging>pom</packaging><modules><module>core</module></modules><properties><maven.compiler.release>21</maven.compiler.release></properties></project>"#).unwrap();
std::fs::write(child.join("pom.xml"), r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>reactor</artifactId><version>1</version></parent><artifactId>core</artifactId></project>"#).unwrap();
let text = "package demo;\npublic class Greeter { public int value() { return 1; } }\n";
std::fs::write(&source, text).unwrap();
let coordinator = Arc::new(ide_lsp::JavaBuildCoordinator::default());
let create = |root: &Path, workspace: &str| {
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(workspace).to_string_lossy().into_owned()]);
let (mgr, events) = manager(root, LanguageRegistry::from_configs(vec![java]));
mgr.set_java_build_coordinator(coordinator.clone());
(mgr, events)
};
let (parent, _) = create(&root, "parent-data");
let (secondary, _) = create(&child, "child-data");
let parent_doc = DocId::next();
parent.did_open(parent_doc, &source, &LanguageId::new("java"), 1, text);
assert_eq!(
parent.java_build(&child, false, &Default::default()).await.unwrap(),
ide_lsp::jdtls::JavaBuildStatus::Succeeded
);
let output = child.join("target/classes/demo/Greeter.class");
let before = std::fs::metadata(&output).unwrap().modified().unwrap();
tokio::time::sleep(Duration::from_secs(1)).await;
let child_doc = DocId::next();
secondary.did_open(child_doc, &source, &LanguageId::new("java"), 1, text);
secondary
.wait_jdtls_imported(&source, tokio::time::Instant::now() + Duration::from_secs(120), &Default::default())
.await
.unwrap();
let cp = secondary.java_classpath(&child, false, &Default::default()).await.unwrap();
assert!(cp.class_paths.iter().any(|p| p.ends_with("target/classes") || p.ends_with("target\\classes")));
tokio::time::sleep(Duration::from_secs(2)).await;
assert_eq!(
std::fs::metadata(&output).unwrap().modified().unwrap(),
before,
"the secondary workspace automatically rebuilt the shared class"
);
eprintln!("secondary imported the Maven project without rewriting Greeter.class");
assert_eq!(
secondary.java_build(&child, false, &Default::default()).await.unwrap(),
ide_lsp::jdtls::JavaBuildStatus::Succeeded
);
parent.shutdown_all().await;
let changed = text.replace("return 1;", "return 2;");
let line = text.lines().nth(1).unwrap();
secondary.did_change(
child_doc,
2,
&[AppliedChange {
range: Range::new(Pos::new(1, 0), Pos::new(1, line.len() as u32)),
text: changed.lines().nth(1).unwrap().to_owned(),
}],
&|| changed.clone(),
);
std::fs::write(&source, &changed).unwrap();
secondary.did_save(child_doc, &changed);
let previous = std::fs::read(&output).unwrap();
retry("promoted secondary automatically compiles the saved change", Duration::from_secs(60), || async {
std::fs::read(&output).ok().filter(|bytes| bytes != &previous).map(|_| ())
})
.await;
secondary.shutdown_all().await;
}
+30 -13
Переглянути файл
@@ -21,25 +21,42 @@ fn groovy_string(s: &str) -> String {
out
}
const HEADER: &str = r#"// Written by OpenIDEA: VM options of the run configuration.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
"#;
/// The init script adding `jvm_args` (one argument each) to the forked JVMs.
pub fn init_script(jvm_args: &[String]) -> String {
let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", ");
format!(
"// Written by OpenIDEA: VM options of the run configuration.\n\
import org.gradle.util.GradleVersion\n\
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.\n\
def each = {{ tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? \
tasks.configureEach(action) : tasks.all(action) }}\n\
allprojects {{\n \
each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
"{HEADER}eachProject {{ p ->\n \
each(p.tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
each(p.tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
}}\n"
)
}
/// Where the scripts are written.
pub fn default_dir() -> PathBuf {
std::env::temp_dir().join("openidea-gradle")
/// Where the scripts are written: a folder of this user, as Gradle runs what it finds there.
pub fn default_dir() -> std::io::Result<PathBuf> {
ide_core::private_temp::dir("gradle")
}
/// Writes the script for `jvm_args` under `dir` (named by its content, so launches share
@@ -79,8 +96,8 @@ mod tests {
fn adds_each_argument_to_java_exec_and_test_tasks() {
let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]));
let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']";
assert!(script.contains(&format!("each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(p.tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(p.tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(script.contains("? tasks.configureEach(action) : tasks.all(action)"), "{script}");
}
+2 -2
Переглянути файл
@@ -238,8 +238,8 @@ pub fn shorten_classpath_to_jar(
}
/// Where launches put their pathing jars / argfiles.
pub fn default_temp_dir() -> PathBuf {
std::env::temp_dir().join("openidea-classpath")
pub fn default_temp_dir() -> std::io::Result<PathBuf> {
ide_core::private_temp::dir("classpath")
}
fn temp_file(dir: &Path, ext: &str) -> PathBuf {
+5 -6
Переглянути файл
@@ -271,7 +271,8 @@ fn shorten_java(inv: &mut Invocation, config: &RunConfig, cwd: &Path) -> IdeResu
} else {
inv.program.clone()
};
let dir = crate::java_cmdline::default_temp_dir();
let dir = crate::java_cmdline::default_temp_dir()
.map_err(|e| IdeError::internal(format!("cannot shorten the command line: {e}")))?;
let shortened = crate::java_cmdline::shorten(&java, &inv.args, cwd, cfg!(windows), &dir)
.map_err(|e| IdeError::internal(format!("cannot shorten the command line: {e}")))?;
let Some(s) = shortened else { return Ok(TempFile(None)) };
@@ -307,11 +308,9 @@ fn match_console_encoding(
env.vars.extend(fix.env);
let mut prepend = fix.java_args;
if fix.gradle_init_script {
match crate::gradle_jvm::write_script(
&crate::gradle_jvm::default_dir(),
"file-encoding",
output_encoding::GRADLE_FILE_ENCODING_SCRIPT,
) {
match crate::gradle_jvm::default_dir().and_then(|dir| {
crate::gradle_jvm::write_script(&dir, "file-encoding", output_encoding::GRADLE_FILE_ENCODING_SCRIPT)
}) {
Ok(script) => prepend.extend(["--init-script".to_owned(), script.to_string_lossy().into_owned()]),
Err(e) => tracing::warn!("cannot write the Gradle file.encoding init script: {e}"),
}
+2 -1
Переглянути файл
@@ -128,7 +128,8 @@ pub fn parse_devices(json: &str) -> IdeResult<Vec<IosSimulator>> {
/// `devicectl` (Xcode 15 and later) is missing or fails. `dir` picks the project's Xcode.
pub fn devices(dir: &Path) -> Vec<IosSimulator> {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos();
let file = std::env::temp_dir().join(format!("openidea-devicectl-{}-{stamp}.json", std::process::id()));
let Ok(out) = ide_core::private_temp::dir("devicectl") else { return Vec::new() };
let file = out.join(format!("{}-{stamp}.json", std::process::id()));
let path = file.to_string_lossy().into_owned();
let listed = run_in(Some(dir), "xcrun", &["devicectl", "list", "devices", "--quiet", "--json-output", &path]);
let json = std::fs::read_to_string(&file);
+201
Переглянути файл
@@ -0,0 +1,201 @@
//! The init scripts of Gradle run, debug and test launches on a real Gradle, with and without
//! Isolated Projects (#8261). Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else
//! `gradle` on the search path); skipped without them, like ide-build's Gradle tests.
use std::path::{Path, PathBuf};
use std::process::Command;
const RUN: &str = include_str!("../../../../src/features/run/gradleRun.gradle");
const BOOT: &str = include_str!("../../../../src/features/run/gradleBoot.gradle");
const TESTS: &str = include_str!("../../../../src/features/run/gradleTests.gradle");
const MAIN: &str = r#"package a;
public class Main {
public static void main(String[] args) {
String token = "";
for (String a : java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments())
if (a.startsWith("-Dopenidea.")) token += " " + a;
System.out.println("APP " + String.join(",", args) + " enc=" + System.getProperty("file.encoding") + " vm=" + System.getProperty("openidea.vm") + token);
}
}
"#;
const TEST: &str = r#"package l;
class LTest {
@org.junit.jupiter.api.Test
void ok() {
System.out.println("TEST vm=" + System.getProperty("openidea.vm") + " late=" + System.getProperty("openidea.late"));
}
}
"#;
const JUNIT: &str = "org.junit.jupiter:junit-jupiter:5.11.0";
fn gradle() -> Option<PathBuf> {
std::env::var_os("JAVA_HOME")?;
std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()))
}
fn write(root: &Path, files: &[(&str, &str)]) {
for (rel, text) in files {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
}
/// Runs `tasks` with every init script; the output, or the failure with it.
fn run(gradle: &Path, root: &Path, tasks: &[&str]) -> Result<String, String> {
let scripts = root.parent().unwrap().join("scripts");
let mut args = vec!["--console=plain".to_owned()];
for name in ["jvm", "encoding", "run", "boot", "tests"] {
args.extend(["--init-script".to_owned(), scripts.join(format!("{name}.init.gradle")).display().to_string()]);
}
args.extend(
[
"-Dopenidea.run.project=:app",
"-Dopenidea.run.main=a.Main",
r#"-Dopenidea.run.args=["openidea"]"#,
"-Dopenidea.run.token=t1",
]
.map(String::from),
);
args.extend(tasks.iter().map(|t| t.to_string()));
let out = Command::new(gradle).args(&args).current_dir(root).output().unwrap();
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
if out.status.success() { Ok(text) } else { Err(text) }
}
/// The test-events script reported the test, with its output, from a test JVM given the VM options.
fn assert_test_events(out: &str) {
for event in [
"##teamcity[testStarted name='ok()' className='l.LTest'",
"##teamcity[testStdOut name='ok()' className='l.LTest' reportName='ok()' out='TEST vm=1",
"##teamcity[testFinished name='ok()' className='l.LTest'",
] {
assert!(out.contains(event), "no `{event}`:\n{out}");
}
}
fn app_line<'a>(out: &'a str, arg: &str) -> &'a str {
let prefix = format!("APP {arg} ");
out.lines().find(|l| l.starts_with(&prefix)).unwrap_or_else(|| panic!("no `{prefix}` line:\n{out}"))
}
/// Gradle's version, as (major, minor).
fn version(gradle: &Path) -> (u32, u32) {
let out = Command::new(gradle).arg("--version").output().unwrap();
let text = String::from_utf8_lossy(&out.stdout);
let v = text.lines().find_map(|l| l.strip_prefix("Gradle ")).expect("a `Gradle x.y` line");
let mut parts = v.trim().split('.').map(|p| p.parse::<u32>().unwrap_or(0));
(parts.next().unwrap(), parts.next().unwrap_or(0))
}
#[test]
fn run_debug_and_test_scripts_configure_each_project() {
let Some(gradle) = gradle() else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let jvm = ide_run::gradle_jvm::init_script(&["-Dopenidea.vm=1".to_owned()]);
write(
&base,
&[
("scripts/jvm.init.gradle", &jvm),
("scripts/encoding.init.gradle", ide_core::output_encoding::GRADLE_FILE_ENCODING_SCRIPT),
("scripts/run.init.gradle", RUN),
("scripts/boot.init.gradle", BOOT),
("scripts/tests.init.gradle", TESTS),
],
);
// Without Isolated Projects, in the Groovy DSL: the build's own setting still wins over the
// scripts' UTF-8 default, also when the root configures its subprojects.
let plain = base.join("plain");
write(
&plain,
&[
("gradle.properties", "org.gradle.daemon=false\n"),
("settings.gradle", "rootProject.name = 'plain'\ninclude 'app', 'lib'\n"),
(
"build.gradle",
"subprojects { tasks.withType(JavaExec).configureEach { defaultCharacterEncoding = 'ISO-8859-1' } }\n",
),
(
"app/build.gradle",
"plugins { id 'application' }\napplication { mainClass = 'a.Main' }\ntasks.named('run') { args 'run' }\n\
tasks.register('bootRun', JavaExec) { mainClass = 'a.Main'; classpath = sourceSets.main.runtimeClasspath; args 'boot' }\n",
),
("app/src/main/java/a/Main.java", MAIN),
(
"lib/build.gradle",
&format!(
"plugins {{ id 'java' }}\nrepositories {{ mavenCentral() }}\n\
dependencies {{ testImplementation '{JUNIT}'; testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }}\n\
test {{ useJUnitPlatform() }}\n"
),
),
("lib/src/test/java/l/LTest.java", TEST),
],
);
let out = run(&gradle, &plain, &[":app:run", ":app:bootRun", ":app:openideaRun", ":lib:test"]).unwrap();
assert_eq!(app_line(&out, "run"), "APP run enc=ISO-8859-1 vm=1 -Dopenidea.vm=1");
assert_eq!(app_line(&out, "boot"), "APP boot enc=ISO-8859-1 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1");
assert_eq!(app_line(&out, "openidea"), "APP openidea enc=ISO-8859-1 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1");
assert_test_events(&out);
// With Isolated Projects, in the Kotlin DSL, on a configuration cache miss and then a hit.
let isolated = base.join("isolated");
write(
&isolated,
&[
(
"gradle.properties",
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\n\
org.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
),
("settings.gradle.kts", "rootProject.name = \"isolated\"\ninclude(\"app\", \"lib\")\n"),
("build.gradle.kts", ""),
(
"app/build.gradle.kts",
"plugins { application }\napplication { mainClass.set(\"a.Main\") }\n\
tasks.named<JavaExec>(\"run\") { args(\"run\"); defaultCharacterEncoding = \"ISO-8859-1\"; jvmArgs(\"-Dopenidea.vm=build\") }\n\
tasks.register<JavaExec>(\"bootRun\") { mainClass.set(\"a.Main\"); classpath = sourceSets[\"main\"].runtimeClasspath; args(\"boot\") }\n\
afterEvaluate { tasks.named<JavaExec>(\"bootRun\") { setJvmArgs(listOf(\"-Dopenidea.late=1\")) } }\n",
),
("app/src/main/java/a/Main.java", MAIN),
(
"lib/build.gradle.kts",
&format!(
"plugins {{ java }}\nrepositories {{ mavenCentral() }}\n\
dependencies {{ testImplementation(\"{JUNIT}\"); testRuntimeOnly(\"org.junit.platform:junit-platform-launcher\") }}\n\
tasks.test {{ useJUnitPlatform() }}\n\
afterEvaluate {{ tasks.named<Test>(\"test\") {{ systemProperty(\"openidea.late\", \"1\") }} }}\n"
),
),
("lib/src/test/java/l/LTest.java", TEST),
],
);
let tasks = [":app:run", ":app:bootRun", ":app:openideaRun", ":lib:test"];
if version(&gradle) < (8, 8) {
// Before Gradle 8.8 the scripts keep reading every project, as the build above checked.
return;
}
for pass in ["miss", "hit"] {
let out = run(&gradle, &isolated, &tasks).unwrap_or_else(|e| panic!("cache {pass}:\n{e}"));
assert_eq!(out.contains("Reusing configuration cache."), pass == "hit", "{out}");
// The build's own charset and VM option win over the scripts' values.
let run = app_line(&out, "run");
assert!(run.starts_with("APP run enc=ISO-8859-1 vm=build "), "{run}");
// The token comes after the build's own `afterEvaluate`, which replaced the JVM arguments.
assert_eq!(app_line(&out, "boot"), "APP boot enc=UTF-8 vm=null -Dopenidea.late=1 -Dopenidea.run.token=t1");
assert_eq!(app_line(&out, "openidea"), "APP openidea enc=UTF-8 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1");
// Test tasks always run, also on a cache hit.
assert_test_events(&out);
// The test task the build configures in its own `afterEvaluate` ran with that setting.
assert!(out.contains("out='TEST vm=1 late=1"), "{out}");
}
}
+1
Переглянути файл
@@ -2,6 +2,7 @@ mod config;
mod detect;
mod dotnet;
mod dotnet_cli;
mod gradle_init_scripts;
mod import_jetbrains;
mod import_vscode;
#[cfg(unix)]
+1 -1
Переглянути файл
@@ -624,7 +624,7 @@ fn long_java_classpath_is_shortened() {
let file = first
.split(' ')
.map(|a| a.trim_matches('\'').trim_start_matches('@'))
.find(|a| a.contains("openidea-classpath"))
.find(|a| a.contains("/classpath/classpath-"))
.unwrap_or_else(|| panic!("no pathing jar / argfile in {first}"));
assert!(!Path::new(file).exists(), "{file} not deleted");
}
+65 -17
Переглянути файл
@@ -44,6 +44,39 @@ fn search_path() -> OsString {
ide_core::process::host_var_os("PATH").unwrap_or_default()
}
/// Where a generator's programs are found, and what they run with.
pub(crate) struct Toolchain {
search: OsString,
goroot: Option<PathBuf>,
}
impl Toolchain {
/// The host `PATH`. A generator that needs `go` gets the GOROOT chosen in Settings first on
/// it and as `GOROOT`, as Run and gopls do, while that GOROOT still holds a `go`.
fn new(def: &Def, values: &Values, goroot: Option<&Path>) -> Self {
let search = search_path();
let needs_go = needs(def, values, "go");
let usable = |g: &&Path| ide_core::tool_path::find_command("go", g.join("bin").as_os_str(), g).is_some();
match goroot.filter(|_| needs_go).filter(usable) {
Some(goroot) => Toolchain {
search: std::env::join_paths(std::iter::once(goroot.join("bin")).chain(std::env::split_paths(&search)))
.unwrap_or(search),
goroot: Some(goroot.to_path_buf()),
},
None => Toolchain { search, goroot: None },
}
}
fn command(&self, program: &Path) -> Command {
let mut cmd = Command::new(program);
cmd.env("PATH", &self.search);
if let Some(goroot) = &self.goroot {
cmd.env("GOROOT", goroot);
}
cmd
}
}
/// `values` plus every field's rendered default it lacks, `name` included.
fn with_defaults(def: &Def, name: &str, values: &Values) -> Values {
let mut out = values.clone();
@@ -96,16 +129,16 @@ pub(crate) fn version_at_least(a: &str, b: &str) -> bool {
true
}
fn requirement(r: &RequireDef, values: &Values, search: &OsString) -> Requirement {
fn requirement(r: &RequireDef, values: &Values, tools: &Toolchain) -> Requirement {
let program = render(&r.program, values);
let min = r.min.clone();
let found_path = ide_core::process::find_executable(&program, search);
let found_path = ide_core::process::find_executable(&program, &tools.search);
let found = found_path.as_ref().and_then(|path| {
if r.version_args.is_empty() {
return Some(String::new());
}
let mut cmd = Command::new(path);
cmd.args(&r.version_args).env("PATH", search);
let mut cmd = tools.command(path);
cmd.args(&r.version_args);
let (ok, out) = run_quiet(cmd, std::time::Duration::from_secs(20))?;
// A failing version command (`dotnet` without an SDK) reports no version.
Some(if ok { parse_version(&out).unwrap_or_default() } else { String::new() })
@@ -118,14 +151,23 @@ fn requirement(r: &RequireDef, values: &Values, search: &OsString) -> Requiremen
Requirement { program, min, found: found.filter(|v| !v.is_empty()), satisfied, hint: r.hint.clone() }
}
fn needs(def: &Def, values: &Values, program: &str) -> bool {
def.requires.iter().any(|r| matches(&r.when, values) && render(&r.program, values) == program)
}
/// Whether generator `id` runs `program` for `values`.
pub fn needs_program(id: &str, values: &Values, program: &str) -> bool {
def(id).is_some_and(|def| needs(def, &with_defaults(def, "app", values), program))
}
/// The programs `id` needs for `values`, and whether this machine has them.
pub fn requirements(id: &str, values: &Values) -> IdeResult<Vec<Requirement>> {
pub fn requirements(id: &str, values: &Values, goroot: Option<&Path>) -> IdeResult<Vec<Requirement>> {
let def = def(id).ok_or_else(|| unknown(id))?;
let values = with_defaults(def, "app", values);
let search = search_path();
let tools = Toolchain::new(def, &values, goroot);
let mut out: Vec<Requirement> = Vec::new();
for r in def.requires.iter().filter(|r| matches(&r.when, &values)) {
let req = requirement(r, &values, &search);
let req = requirement(r, &values, &tools);
if !out.iter().any(|o| o.program == req.program) {
out.push(req);
}
@@ -243,13 +285,13 @@ fn run_step(
step: &StepDef,
values: &Values,
project: &Path,
search: &OsString,
tools: &Toolchain,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let argv = argv(step, values);
emit(ScaffoldEvent::Step { text: step.label.clone() });
let Some(program) = ide_core::process::find_executable(&argv[0], search) else {
let Some(program) = ide_core::process::find_executable(&argv[0], &tools.search) else {
if step.optional {
emit(ScaffoldEvent::Line { text: format!("`{}` is not installed; skipped", argv[0]) });
return Ok(());
@@ -260,8 +302,8 @@ fn run_step(
Cwd::Project => project.to_path_buf(),
Cwd::Parent => project.parent().unwrap_or(project).to_path_buf(),
};
let mut cmd = Command::new(program);
cmd.args(&argv[1..]).current_dir(cwd).env("PATH", search);
let mut cmd = tools.command(&program);
cmd.args(&argv[1..]).current_dir(cwd);
// Official CLIs take their defaults instead of asking when they see a CI run.
cmd.env("CI", "1").env("NO_COLOR", "1").env("FORCE_COLOR", "0").env("npm_config_yes", "true");
for (key, value) in &step.env {
@@ -396,14 +438,20 @@ fn download_service(
}
/// Creates the project `req` describes and returns its directory.
pub fn create(req: &CreateRequest, cancel: &CancellationToken, emit: Emit) -> IdeResult<PathBuf> {
pub fn create(
req: &CreateRequest,
goroot: Option<&Path>,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<PathBuf> {
let def = def(&req.generator).ok_or_else(|| unknown(&req.generator))?;
create_with(def, req, cancel, emit)
create_with(def, req, goroot, cancel, emit)
}
pub(crate) fn create_with(
def: &Def,
req: &CreateRequest,
goroot: Option<&Path>,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<PathBuf> {
@@ -431,12 +479,12 @@ pub(crate) fn create_with(
return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display())));
}
let search = search_path();
let tools = Toolchain::new(def, &values, goroot);
let mut missing = def
.requires
.iter()
.filter(|r| matches(&r.when, &values))
.map(|r| requirement(r, &values, &search))
.map(|r| requirement(r, &values, &tools))
.filter(|r| !r.satisfied);
if let Some(r) = missing.next() {
let need = r.min.as_ref().map(|m| format!(" {m} or later")).unwrap_or_default();
@@ -460,7 +508,7 @@ pub(crate) fn create_with(
if step.cwd == Cwd::Project {
std::fs::create_dir_all(&project)?;
}
run_step(step, &values, &project, &search, cancel, emit)?;
run_step(step, &values, &project, &tools, cancel, emit)?;
}
if !project.is_dir() {
return Err(IdeError::internal(format!("the generator did not create {}", project.display())));
@@ -474,7 +522,7 @@ pub(crate) fn create_with(
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
run_step(step, &values, &project, &search, cancel, emit)?;
run_step(step, &values, &project, &tools, cancel, emit)?;
}
let git_dir = project.join(".git");
if !(req.git && def.git) && git_dir.is_dir() {
+83 -10
Переглянути файл
@@ -43,7 +43,7 @@ fn create_template(generator: &str, name: &str, values: &[(&str, &str)]) -> (tem
def.after.clear();
def.requires.clear();
let req = request(generator, tmp.path(), name, values);
let path = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
let path = create_with(&def, &req, None, &CancellationToken::new(), &|_| {}).unwrap();
(tmp, path)
}
@@ -92,7 +92,8 @@ fn php_namespace_is_escaped_in_json() {
def.requires.clear();
def.after.clear();
let tmp = tempfile::tempdir().unwrap();
let dir = create_with(&def, &request("php", tmp.path(), "shop", &[]), &CancellationToken::new(), &|_| {}).unwrap();
let dir =
create_with(&def, &request("php", tmp.path(), "shop", &[]), None, &CancellationToken::new(), &|_| {}).unwrap();
let composer: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(dir.join("composer.json")).unwrap()).unwrap();
assert_eq!(composer.pointer("/autoload/psr-4/Acme\\Shop\\").unwrap(), "src/");
@@ -244,13 +245,13 @@ fn dotnet_templates_see_the_selected_sdk_before_running() {
step.program = def.requires[0].program.clone();
}
let req = request("dotnet", tmp.path(), "Shop", &[("sdk", "10.0.400")]);
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
let project = create_with(&def, &req, None, &CancellationToken::new(), &|_| {}).unwrap();
let pin: serde_json::Value = serde_json::from_slice(&std::fs::read(project.join("global.json")).unwrap()).unwrap();
assert_eq!(pin["sdk"]["version"], "10.0.400");
assert_eq!(std::fs::read_to_string(parent_pin).unwrap(), inherited);
// A solution named apart from the project names the folder.
let req = request("dotnet", tmp.path(), "Api", &[("sdk", "10.0.400"), ("solution-name", "Store")]);
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
let project = create_with(&def, &req, None, &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(project, tmp.path().join("Store"));
assert!(project.join("global.json").is_file());
}
@@ -264,7 +265,7 @@ fn a_failing_version_command_does_not_meet_a_minimum() {
let tool = bin.path().join("fake-dotnet");
std::fs::write(&tool, "#!/bin/sh\necho 'No .NET SDKs were found. Install 8.0 from the site.'\nexit 145\n").unwrap();
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
let search = bin.path().as_os_str().to_owned();
let search = Toolchain { search: bin.path().as_os_str().to_owned(), goroot: None };
let def = |min: &str| -> RequireDef { toml::from_str(&format!("program = \"fake-dotnet\"\n{min}")).unwrap() };
let req = requirement(&def(r#"min = "8.0""#), &Values::new(), &search);
assert!(!req.satisfied);
@@ -299,7 +300,8 @@ label = "Fail"
program = "definitely-not-a-program-openidea"
"#,
);
let err = create_with(&def, &request("t", tmp.path(), "p", &[]), &CancellationToken::new(), &|_| {}).unwrap_err();
let err =
create_with(&def, &request("t", tmp.path(), "p", &[]), None, &CancellationToken::new(), &|_| {}).unwrap_err();
assert!(err.message.contains("not installed"), "{}", err.message);
assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0);
}
@@ -316,7 +318,7 @@ optional = true
"#,
);
let lines = Mutex::new(Vec::new());
let dir = create_with(&def, &request("t", tmp.path(), "p", &[]), &CancellationToken::new(), &|e| {
let dir = create_with(&def, &request("t", tmp.path(), "p", &[]), None, &CancellationToken::new(), &|e| {
lines.lock().unwrap().push(format!("{e:?}"))
})
.unwrap();
@@ -330,7 +332,7 @@ fn cancelling_leaves_nothing_behind() {
let cancel = CancellationToken::new();
cancel.cancel();
let def = failing_def("");
let err = create_with(&def, &request("t", tmp.path(), "p", &[]), &cancel, &|_| {}).unwrap_err();
let err = create_with(&def, &request("t", tmp.path(), "p", &[]), None, &cancel, &|_| {}).unwrap_err();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0);
}
@@ -341,14 +343,14 @@ fn refuses_a_non_empty_target_and_bad_names() {
std::fs::create_dir(tmp.path().join("p")).unwrap();
std::fs::write(tmp.path().join("p/x"), "").unwrap();
let def = failing_def("");
assert!(create_with(&def, &request("t", tmp.path(), "p", &[]), &CancellationToken::new(), &|_| {}).is_err());
assert!(create_with(&def, &request("t", tmp.path(), "p", &[]), None, &CancellationToken::new(), &|_| {}).is_err());
assert!(std::fs::read_dir(tmp.path().join("p")).unwrap().count() == 1);
for bad in ["", " ", "a/b", "..", ".hidden"] {
assert!(name_error(bad).is_some(), "{bad:?}");
}
// An existing empty folder is used.
std::fs::create_dir(tmp.path().join("q")).unwrap();
let dir = create_with(&def, &request("t", tmp.path(), "q", &[]), &CancellationToken::new(), &|_| {}).unwrap();
let dir = create_with(&def, &request("t", tmp.path(), "q", &[]), None, &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(tree(&dir), ["a.txt"]);
}
@@ -637,3 +639,74 @@ fn xcode_builds_and_tests_apple_projects() {
}
}
}
/// A GOROOT holding a fake `go` that fails, like a real one, under another installation's GOROOT.
#[cfg(unix)]
fn fake_goroot(dir: &Path) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let goroot = dir.join("go-sdk");
std::fs::create_dir_all(goroot.join("bin")).unwrap();
let go = goroot.join("bin/go");
std::fs::write(
&go,
format!(
"#!/bin/sh\n[ \"$GOROOT\" = '{}' ] || exit 2\n\
if [ \"$1\" = version ]; then echo 1.99.0; exit 0; fi\n\
printf 'module %s\\n' \"$3\" > go.mod\n",
goroot.display()
),
)
.unwrap();
std::fs::set_permissions(&go, std::fs::Permissions::from_mode(0o755)).unwrap();
goroot
}
/// Go installed outside the login shell's `PATH`, chosen as GOROOT in Settings.
#[cfg(unix)]
#[test]
fn the_go_chosen_in_settings_is_found_and_runs_the_steps() {
let tmp = tempfile::tempdir().unwrap();
let goroot = fake_goroot(tmp.path());
let reqs = requirements("go", &Values::new(), Some(&goroot)).unwrap();
assert_eq!(reqs[0].found.as_deref(), Some("1.99.0"));
// A Go on `PATH` would write a `go` line too.
let req = request("go", tmp.path(), "hello", &[]);
let project = create(&req, Some(&goroot), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(std::fs::read_to_string(project.join("go.mod")).unwrap(), "module example.com/hello\n");
}
#[cfg(unix)]
#[test]
fn the_go_chosen_in_settings_stays_out_of_other_generators() {
let tmp = tempfile::tempdir().unwrap();
let goroot = fake_goroot(tmp.path());
let node = source_def("node");
let tools = Toolchain::new(&node, &with_defaults(&node, "app", &Values::new()), Some(&goroot));
assert_eq!(tools.search, search_path());
assert_eq!(tools.goroot, None);
}
/// A GOROOT whose `go` was removed, or lost its execute bit, leaves the `go` on `PATH` to run
/// on its own.
#[cfg(unix)]
#[test]
fn an_unusable_go_chosen_in_settings_is_ignored() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let go = source_def("go");
let values = with_defaults(&go, "app", &Values::new());
let tools = Toolchain::new(&go, &values, Some(&tmp.path().join("go1.25")));
assert_eq!((tools.search, tools.goroot), (search_path(), None));
let goroot = fake_goroot(tmp.path());
std::fs::set_permissions(goroot.join("bin/go"), std::fs::Permissions::from_mode(0o644)).unwrap();
let tools = Toolchain::new(&go, &values, Some(&goroot));
assert_eq!((tools.search, tools.goroot), (search_path(), None));
}
/// New Project asks for a discovered Go only for the generators that run `go`.
#[test]
fn only_go_generators_need_go() {
assert!(needs_program("go", &Values::new(), "go"));
assert!(!needs_program("node", &Values::new(), "go"));
assert!(!needs_program("no-such-generator", &Values::new(), "go"));
}
+1 -1
Переглянути файл
@@ -10,7 +10,7 @@ mod providers;
mod template;
pub use catalog::catalog;
pub use engine::{Emit, create, free_name, name_error, options, requirements, target_taken};
pub use engine::{Emit, create, free_name, name_error, needs_program, options, requirements, target_taken};
pub use model::{
ChoiceOption, CreateRequest, Dependency, DependencyGroup, Field, FieldKind, GeneratorInfo, Requirement,
ScaffoldEvent, Values,
+1 -1
Переглянути файл
@@ -17,7 +17,7 @@ fn smoke(generator: &str, values: &[(&str, &str)], build: &[&str]) {
git: true,
values: values.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
};
let dir = create(&req, &CancellationToken::new(), &|e| match e {
let dir = create(&req, None, &CancellationToken::new(), &|e| match e {
ScaffoldEvent::Step { text } => eprintln!("== {text}"),
ScaffoldEvent::Line { text } => eprintln!(" {text}"),
})
+6 -4
Переглянути файл
@@ -28,8 +28,8 @@ fn workspace(cfg: &LanguageServerConfig) -> Option<&Path> {
cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)).map(Path::new)
}
/// jdtls' temporary folder for `workspace`: `<workspace>/.tmp`, or a folder of its own in the
/// system temporary folder when the workspace path has whitespace (macOS's `Application Support`).
/// jdtls' temporary folder for `workspace`: `<workspace>/.tmp`, or a folder of its own in this
/// user's temporary folder when the workspace path has whitespace (macOS's `Application Support`).
/// Buildship writes its Gradle init script there and later splits the stored arguments at spaces,
/// so a path with a space reaches Gradle cut off and every Gradle import fails.
fn temp_dir(workspace: &Path) -> PathBuf {
@@ -42,8 +42,10 @@ fn temp_dir(workspace: &Path) -> PathBuf {
.to_string_lossy()
.bytes()
.fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
let shared = std::env::temp_dir().join(format!("openidea-jdtls-{hash:016x}"));
if has_whitespace(&shared) { own } else { shared }
match ide_core::private_temp::dir("jdtls") {
Ok(dir) if !has_whitespace(&dir) => dir.join(format!("{hash:016x}")),
_ => own,
}
}
fn has_whitespace(path: &Path) -> bool {
+4 -3
Переглянути файл
@@ -116,9 +116,10 @@ fn jdk_tool(name: &str, jdks: &[crate::java::Jdk]) -> Option<PathBuf> {
Some(jdk.home.join("bin").join(crate::exe(name))).filter(|p| p.is_file())
}
/// Directory for binaries compiled from single source files (`rustc`, `clang`).
pub fn compile_dir() -> PathBuf {
std::env::temp_dir().join("openidea-run")
/// Directory for binaries compiled from single source files (`rustc`, `clang`): a folder of this
/// user, as the binaries in it are run.
pub fn compile_dir() -> std::io::Result<PathBuf> {
ide_core::private_temp::dir("run")
}
/// The macOS SDK to pass to `clang -isysroot`. A newer compiler (e.g. Homebrew LLVM)
Переглянути файл
Whitespace-only changes.
+62
Переглянути файл
@@ -683,13 +683,39 @@ fn jump_hop(config: Option<&Path>, spec: &str) -> Hop {
Hop { forwards: Vec::new(), ..hop }
}
/// Whether a host name may stand for `%h` / `%n` in a command `sh -c` runs (`ProxyCommand`,
/// `Match exec`): OpenSSH's rule, as it applies to a host typed on its command line. A host
/// can come from a project's files (a data source's SSH tunnel), where `;` or `$(` would
/// run commands on this machine through the user's own `~/.ssh/config`.
fn valid_host(host: &str) -> bool {
!host.starts_with('-')
&& !host.chars().any(|c| c.is_whitespace() || c.is_control() || "'`\"$\\;&<>|(){},".contains(c))
}
/// [`valid_host`] for a user name (`%r`): OpenSSH's rule, which keeps `$` and a `\` that
/// isn't last (`DOMAIN\user`).
fn valid_user(user: &str) -> bool {
!user.starts_with('-')
&& !user.ends_with('\\')
&& !user.chars().any(|c| c.is_control() || "'`\";&<>|(){}".contains(c))
&& !user.contains(char::is_whitespace)
}
/// The SSH hosts to go through, the target last.
pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResult<Vec<Hop>> {
let host = target.host.trim();
if host.is_empty() {
return Err(IdeError::invalid("SSH host is empty"));
}
if !valid_host(host) {
return Err(IdeError::invalid(format!("SSH host contains characters a host name cannot have: {host}")));
}
let user_override = Some(target.user.trim()).filter(|u| !u.is_empty());
if let Some(user) = user_override
&& !valid_user(user)
{
return Err(IdeError::invalid(format!("SSH user contains characters a user name cannot have: {user}")));
}
let (hop, proxy_jump) = if target.auth == SshAuth::OpenSsh {
config_hop(config, host, target.port, user_override)
} else {
@@ -832,6 +858,42 @@ mod tests {
assert_eq!(Agent::Off.socket(), None);
}
#[test]
fn refuses_hosts_and_users_a_proxy_command_would_run_as_shell() {
let tmp = tempfile::tempdir().unwrap();
let config = tmp.path().join("config");
let marker = tmp.path().join("ran");
std::fs::write(&config, "Match exec \"test %h = x\"\n Port 2\nHost *\n ProxyCommand nc %h %p\n").unwrap();
let target = |host: &str, user: &str| SshTarget {
host: host.into(),
user: user.into(),
auth: SshAuth::OpenSsh,
..Default::default()
};
let touch = format!("touch {}", marker.display());
for (host, user) in [
(format!("a;{touch}").as_str(), ""),
(format!("$({touch})").as_str(), ""),
("box", format!("u;{touch}").as_str()),
("a`id`", ""),
("a b", ""),
("-oProxyCommand=x", ""),
("a|b", ""),
("box", "u;id"),
("box", "$(id)"),
("box", "-l"),
("box", "a b"),
("box", "trailing\\"),
] {
assert!(resolve_hops(&target(host, user), Some(&config)).is_err(), "{host} / {user}");
}
assert!(!marker.exists());
for (host, user) in [("box.example.com", "ops"), ("10.0.0.5", "DOMAIN\\me"), ("fe80::1%en0", "a.b-c_d@corp")] {
let hops = resolve_hops(&target(host, user), Some(&config)).unwrap();
assert_eq!(hops[0].proxy_command.as_deref().map(|c| c.starts_with(&format!("nc {host} 22"))), Some(true));
}
}
#[test]
fn resolves_include_match_equals_and_proxy_command() {
let tmp = tempfile::tempdir().unwrap();
Переглянути файл
Whitespace-only changes.
+4 -9
Переглянути файл
@@ -178,15 +178,11 @@ const POWERSHELL_ARGS: [&str; 5] = ["-ExecutionPolicy", "Bypass", "-NoExit", "-C
/// Directory holding the generated startup files (written on demand). Keyed by the scripts'
/// content as well as the version, so builds with different scripts (a dev build next to a
/// release, two checkouts on one machine) never rewrite each other's files under a starting shell.
fn scripts_dir() -> PathBuf {
fn scripts_dir() -> std::io::Result<PathBuf> {
use std::hash::{Hash, Hasher};
let mut hasher = std::hash::DefaultHasher::new();
(ZSHENV, ZPROFILE, ZSHRC, ZLOGIN, BASHRC).hash(&mut hasher);
std::env::temp_dir().join(format!(
"openidea-shell-integration-{}-{:016x}",
env!("CARGO_PKG_VERSION"),
hasher.finish()
))
ide_core::private_temp::dir(&format!("shell-integration-{}-{:016x}", env!("CARGO_PKG_VERSION"), hasher.finish()))
}
/// Writes through a temporary file and a rename, so a shell (or another process doing the
@@ -228,10 +224,9 @@ pub(crate) fn apply(shell_name: &str, args: &mut Vec<String>, env: &mut BTreeMap
return false;
}
let shell_name = if windows_bash { "bash" } else { shell_name };
let dir = scripts_dir();
let result = match shell_name {
"zsh" => (|| -> std::io::Result<()> {
let zdir = dir.join("zsh");
let zdir = scripts_dir()?.join("zsh");
write_if_changed(&zdir.join(".zshenv"), ZSHENV)?;
write_if_changed(&zdir.join(".zprofile"), ZPROFILE)?;
write_if_changed(&zdir.join(".zshrc"), ZSHRC)?;
@@ -249,7 +244,7 @@ pub(crate) fn apply(shell_name: &str, args: &mut Vec<String>, env: &mut BTreeMap
return false;
}
(|| -> std::io::Result<()> {
let rc = dir.join("bash").join("openidea.bashrc");
let rc = scripts_dir()?.join("bash").join("openidea.bashrc");
write_if_changed(&rc, BASHRC)?;
if args.iter().any(|a| a == "-l" || a == "--login") {
env.insert("OPENIDEA_LOGIN".into(), "1".into());
+27
Переглянути файл
@@ -739,6 +739,33 @@ mod tests {
assert!(cmd.status().unwrap().success(), "{cmd:?}");
}
/// The Git Log filters a short name that is both a tag and a local branch by git's own
/// disambiguated forms (`git rev-parse --abbrev-ref=strict`): `tags/<name>`, `heads/<name>`,
/// or the full ref when another ref takes those.
#[test]
fn resolves_disambiguated_short_names_of_a_tag_and_branch_sharing_a_name() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
run(Command::new("git").args(["init", "-q", "-b", "main"]).arg(&root));
let git = |args: &[&str]| {
let out = Command::new("git").current_dir(&root).args(args).output().unwrap();
assert!(out.status.success(), "{args:?}");
String::from_utf8(out.stdout).unwrap().trim().to_owned()
};
for message in ["one", "two"] {
git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", message]);
}
git(&["tag", "release"]);
git(&["branch", "release", "HEAD~1"]);
let tag = git(&["rev-parse", "refs/tags/release"]);
let branch = git(&["rev-parse", "refs/heads/release"]);
assert_ne!(tag, branch);
let repo = discover(&root).unwrap().unwrap().gix().unwrap();
assert_eq!(resolve(&repo, "tags/release").unwrap().to_string(), tag);
assert_eq!(resolve(&repo, "heads/release").unwrap().to_string(), branch);
assert_eq!(resolve(&repo, "refs/heads/release").unwrap().to_string(), branch);
}
/// More pack indices than the 32 slots `gix` gives a repository another user owns (#7138). The
/// owner can't be changed in a test, so this pins that discovery opens with slots sized by the
/// pack directory: objects in every pack stay readable through the cached handle.
+1 -1
Переглянути файл
@@ -156,7 +156,7 @@ The actions work on the selection in the Project view, or on the file in the act
- **Delete from Server**
- **Automatic Upload**: turns automatic upload on (Always) or off.
- **Open in Browser (Deployed)**: opens the file's URL on the web server.
- **Browse Remote Host**: opens the **Remote Host** tool window, a tree of the server's files with **Open** (edit a copy; saving uploads it back), **Download to Project**, **New Folder…**, **Rename…**, **Delete…**, **Refresh** and **Copy Path**.
- **Browse Remote Host**: opens the **Remote Host** tool window, a tree of the server's files with **Open** (edit a copy; saving uploads it back), **Download to Project**, **New Folder…**, **Rename…**, **Delete…**, **Refresh** and **Copy Path**. On an SFTP server, **Start SSH Session in Directory** opens a terminal tab with a login shell in the chosen folder (a file's parent folder, or the root on empty space).
Drag files or folders from **Project** or your desktop file manager into **Remote Host** to upload them without configuring mappings. Drop onto a folder to upload inside it, onto a file to use its parent folder, or onto the root path or empty tree space to use the displayed root. **Upload Files…** in the context menu opens a file picker (multiple files), and **Upload Folder…** opens a folder picker. The selected folder is uploaded under its own name, including its contents. Existing names ask for confirmation before replacing files and merging folders; cancelling leaves them unchanged. The transfer appears in background tasks and can be cancelled. These direct uploads do not apply deployment exclusions; source symbolic links are skipped. Desktop file-manager drops are not available in Remote Development windows; dragging paths from that window's **Project** tree is supported.
+1 -1
Переглянути файл
@@ -110,7 +110,7 @@ For SSH, the list shows the keys ssh-agent holds, then the public keys in `~/.ss
### Modal commit
With **Use non-modal commit interface** turned off (**Settings › Version Control › Commit**), there is no Commit tool window: **Local Changes**, **Shelf** and **Stash** become tabs of the Git tool window, and **Commit…** opens a **Commit Changes** dialog.
With **Use non-modal commit interface** turned off (**Settings › Version Control › Commit**), there is no Commit tool window: **Local Changes**, **Shelf** and **Stash** become tabs of the Git tool window, and **Commit…** opens a **Commit Changes** dialog. The dialog shows the selected file's diff below the message; **Preview Diff** in its toolbar hides or shows it.
## Changes in the editor
+1 -1
Переглянути файл
@@ -13,7 +13,7 @@ Use any of these:
- The **Vim** widget in the status bar: click it and check **Enabled**.
- **Settings › Editor › Vim** › **Enable Vim emulation**.
The setting applies to every editor in every window right away and is remembered across restarts. While Vim mode is on, the status bar widget shows the current mode: `NORMAL`, `INSERT`, `VISUAL`, `V-LINE`, `V-BLOCK` or `REPLACE`.
The setting applies to every editor in every window right away and is remembered across restarts. It also applies to the commit message and to GitHub pull request comment and review fields; there, Escape first leaves Insert or Visual mode, and an Escape in Normal mode does what it does without Vim (leave the field, cancel the comment). While Vim mode is on, the status bar widget shows the current mode: `NORMAL`, `INSERT`, `VISUAL`, `V-LINE`, `V-BLOCK` or `REPLACE`.
## What works
+1 -1
Переглянути файл
@@ -153,7 +153,7 @@ OpenIDEA 能识别 `Dockerfile`、`Containerfile`、`Dockerfile.<名称>`、`*.d
- **从服务器删除**
- **自动上传**:开启(始终)或关闭自动上传。
- **在浏览器中打开(已部署)**:在 Web 服务器上打开文件对应的 URL。
- **浏览远程主机**:打开 **远程主机** 工具窗口,以树的形式浏览服务器文件,支持 **打开**(编辑本地副本,保存时自动上传回去)、**下载到项目**、**新建文件夹…**、**重命名…**、**删除…**、**刷新** 和 **复制路径**。
- **浏览远程主机**:打开 **远程主机** 工具窗口,以树的形式浏览服务器文件,支持 **打开**(编辑本地副本,保存时自动上传回去)、**下载到项目**、**新建文件夹…**、**重命名…**、**删除…**、**刷新** 和 **复制路径**。SFTP 服务器上的 **在目录中启动 SSH 会话** 会打开一个终端标签页,登录 shell 从所选文件夹启动(选中文件时为其父文件夹,在空白处时为根目录)。
可以从 **项目** 视图或桌面文件管理器拖入文件、文件夹到 **远程主机**,无需配置路径映射。拖到文件夹上传到其内部,拖到文件上传到其父目录,拖到根路径或文件树空白处则上传到当前显示的根目录。右键菜单中的 **上传文件…** 可多选文件,**上传文件夹…** 则打开文件夹选择器;选中的文件夹会连同其内容以原文件夹名称上传。同名项目会先询问是否替换文件并合并文件夹;取消确认不会修改它们。传输会显示在后台任务中,可以取消。这类直接上传不应用部署排除规则,源符号链接会被跳过。远程开发窗口暂不支持从桌面文件管理器拖入本机文件,但支持从该窗口的 **项目** 文件树拖入。
+1 -1
Переглянути файл
@@ -108,7 +108,7 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓
### 模态提交
在 **设置 › 版本控制 › 提交** 中关闭 **使用非模态提交界面** 后,就没有提交工具窗口了:**本地更改**、**搁置** 和 **贮藏** 变成 Git 工具窗口的标签页,**提交…** 会打开 **提交更改** 对话框。
在 **设置 › 版本控制 › 提交** 中关闭 **使用非模态提交界面** 后,就没有提交工具窗口了:**本地更改**、**搁置** 和 **贮藏** 变成 Git 工具窗口的标签页,**提交…** 会打开 **提交更改** 对话框。对话框在提交消息下方显示所选文件的差异,工具栏中的 **预览差异** 可以隐藏或显示它。
## 编辑器中的更改标记
+1 -1
Переглянути файл
@@ -13,7 +13,7 @@ OpenIDEA 内置了 Vim 模拟,参照的是 IntelliJ IDEA 的 IdeaVim 插件。
- 状态栏的 **Vim** 微件:单击后勾选 **已启用**。
- **设置 › 编辑器 › Vim** › **启用 Vim 模拟**。
设置会立即应用到所有窗口的所有编辑器,重启后保持不变。Vim 模式开启时,状态栏微件显示当前模式:`NORMAL`、`INSERT`、`VISUAL`、`V-LINE`、`V-BLOCK` 或 `REPLACE`。
设置会立即应用到所有窗口的所有编辑器,重启后保持不变。提交消息和 GitHub 拉取请求的评论、评审输入框也使用 Vim 模式:在这些输入框里 Escape 先退出插入或可视模式,在普通模式下再按 Escape 则和未开 Vim 时一样(离开输入框或取消评论)。Vim 模式开启时,状态栏微件显示当前模式:`NORMAL`、`INSERT`、`VISUAL`、`V-LINE`、`V-BLOCK` 或 `REPLACE`。
## 支持哪些功能
+1 -1
Переглянути файл
@@ -561,7 +561,7 @@ test("usage locations and preview stay readable as the available space changes",
await page.keyboard.press("Meta+Alt+F7");
const popup = page.getByRole("dialog", { name: "Usages" });
const scope = popup.getByRole("button", { name: "Scope" });
const openWindow = popup.getByRole("button", { name: /^Open in Find Window/ });
const openWindow = popup.getByRole("button", { name: "Open in Find Tool Window" });
await expect(popup.getByTestId("usage-row")).toHaveCount(3);
await popup.getByRole("button", { name: "Show Preview" }).click();
const code = popup.getByRole("region", { name: "Preview" });
+20 -19
Переглянути файл
@@ -4,7 +4,7 @@
*/
import type { Page } from "@playwright/test";
import type { PartialCommitFile } from "../src/bindings";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
@@ -357,7 +357,7 @@ test("Commit reviews a paused cherry-pick without collecting unrelated changes o
await expect(author).toHaveValue("Original Author <[email protected]>");
await expect(review.getByRole("list", { name: "Staged Changes" }).getByRole("button")).toHaveText("build.gradle.kts");
await review.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(draft).toHaveValue("Unrelated and shared draft");
await expect.poll(() => fieldText(draft)).toBe("Unrelated and shared draft");
await local.click();
await draft.fill("Commit panel draft for the pick");
await panel.getByRole("button", { name: "Commit Options", exact: true }).click();
@@ -392,7 +392,7 @@ test("Commit reviews a paused cherry-pick without collecting unrelated changes o
},
]);
expect(await ipcCalls(page, "vcs_commit")).toEqual([]);
await expect(draft).toHaveValue("");
await expect.poll(() => fieldText(draft)).toBe("");
});
test("continuing a resolved operation applies commit modifications to the reviewed staging snapshot", async ({
@@ -965,7 +965,7 @@ test("opening a TODO review from the modal commit leaves the draft available", a
const todo = page.getByRole("region", { name: "TODO", exact: true });
await expect(todo.getByRole("tree").getByText("TODO from the commit dialog")).toBeVisible();
await page.keyboard.press("Meta+k");
await expect(dialog.getByRole("textbox", { name: "Commit message" })).toHaveValue("Keep this draft");
await expect.poll(() => fieldText(dialog.getByRole("textbox", { name: "Commit message" }))).toBe("Keep this draft");
expect(await ipcCalls(page, "vcs_commit")).toEqual([]);
});
@@ -1132,7 +1132,7 @@ test("the Commit tool window restores the draft and author options for the inclu
await page.keyboard.press("Escape");
await base.click();
await feature.click();
await expect(message).toHaveValue("Message from the changelist");
await expect.poll(() => fieldText(message)).toBe("Message from the changelist");
await message.fill("Feature draft");
await gear.click();
await expect(author).toHaveValue("");
@@ -1141,13 +1141,13 @@ test("the Commit tool window restores the draft and author options for the inclu
await date.fill(featureDate);
await page.keyboard.press("Escape");
await feature.click();
await expect(message).toHaveValue("Default draft");
await expect.poll(() => fieldText(message)).toBe("Default draft");
await gear.click();
await expect(author).toHaveValue("Default Author <[email protected]>");
await expect(date).toHaveValue(baseDate);
await page.keyboard.press("Escape");
await feature.click();
await expect(message).toHaveValue("Feature draft");
await expect.poll(() => fieldText(message)).toBe("Feature draft");
await panel.getByRole("button", { name: "Commit", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "vcs_commit"))
@@ -1155,7 +1155,7 @@ test("the Commit tool window restores the draft and author options for the inclu
const [committed] = await ipcCalls(page, "vcs_commit");
const expectedDate = await page.evaluate((local) => new Date(local).toISOString(), featureDate);
expect(new Date((committed!.options as { authorDate: string }).authorDate).toISOString()).toBe(expectedDate);
await expect(message).toHaveValue("Default draft");
await expect.poll(() => fieldText(message)).toBe("Default draft");
});
test("commit message history shows compact message previews above the editor", async ({ workbench: page }) => {
@@ -1181,7 +1181,8 @@ test("commit message history shows compact message previews above the editor", a
const menu = page.getByRole("menu", { name: "Recent commit messages" });
const row = menu.getByRole("menuitem", { name: /Update inventory.*Review settlement totals/ });
await expect(row).toBeVisible();
const messageBox = (await message.boundingBox())!;
// The field's box: the editor's host, around its content.
const messageBox = (await message.locator("xpath=ancestor::div[contains(@class, 'cm-editor')]/..").boundingBox())!;
const menuBox = (await menu.locator("..").boundingBox())!;
const rowBox = (await row.boundingBox())!;
expect(messageBox.y - menuBox.y - menuBox.height).toBeCloseTo(3, 0);
@@ -1193,7 +1194,7 @@ test("commit message history shows compact message previews above the editor", a
await row.press("Escape");
await expect(menu).toBeHidden();
await expect(message).toHaveValue("Draft");
await expect.poll(() => fieldText(message)).toBe("Draft");
await history.click();
await row.press("Home");
await expect(row).toBeFocused();
@@ -1201,7 +1202,7 @@ test("commit message history shows compact message previews above the editor", a
const second = menu.getByRole("menuitem", { name: /Update inventory.*Reconcile export records/ });
await expect(second).toBeFocused();
await page.keyboard.press("Enter");
await expect(message).toHaveValue("Update inventory\n\nReconcile export records");
await expect.poll(() => fieldText(message)).toBe("Update inventory\n\nReconcile export records");
await expect(message).toBeFocused();
});
@@ -1364,7 +1365,7 @@ test("Amend sizes the chooser for long subjects while keeping the last commit ac
await expect(list).toBeHidden();
await page.setViewportSize({ width: 1040, height: 700 });
await page.keyboard.press("Meta+k");
await expect(panel.getByRole("textbox", { name: "Commit message" })).toHaveValue(earlier);
await expect.poll(() => fieldText(panel.getByRole("textbox", { name: "Commit message" }))).toBe(earlier);
});
test("Amend can select an earlier commit before protected history", async ({ workbench: page }) => {
@@ -1381,14 +1382,14 @@ test("Amend can select an earlier commit before protected history", async ({ wor
await expect(picker.getByText("Published commit", { exact: true })).toHaveCount(0);
await expect(picker.getByText("Before published commit", { exact: true })).toHaveCount(0);
await earlier.click();
await expect(message).toHaveValue("Earlier local commit");
await expect.poll(() => fieldText(message)).toBe("Earlier local commit");
await expect(panel.getByRole("treeitem", { name: /Earlier local commit 1 file/ })).toBeVisible();
await expect(panel.getByRole("treeitem", { name: "earlier.txt", exact: true })).toBeVisible();
await choose.click();
await picker.getByRole("option", { name: /^Amend Last Commit/ }).click();
await expect(message).toHaveValue("Last local commit");
await expect.poll(() => fieldText(message)).toBe("Last local commit");
await panel.getByRole("checkbox", { name: "Amend", exact: true }).uncheck();
await expect(message).toHaveValue("Draft");
await expect.poll(() => fieldText(message)).toBe("Draft");
await choose.click();
await earlier.click();
@@ -1454,7 +1455,7 @@ test("Amend filters commit subjects while loading and supports keyboard selectio
await search.press("Escape");
await expect(picker).toBeHidden();
await expect(choose).toBeFocused();
await expect(message).toHaveValue("Draft");
await expect.poll(() => fieldText(message)).toBe("Draft");
await choose.press("ArrowDown");
await expect(search).toHaveValue("");
@@ -1470,7 +1471,7 @@ test("Amend filters commit subjects while loading and supports keyboard selectio
await search.dispatchEvent("keydown", { key: "Enter", isComposing: true });
await expect(search).toBeFocused();
await search.press("Enter");
await expect(message).toHaveValue("Improve local docs");
await expect.poll(() => fieldText(message)).toBe("Improve local docs");
await choose.press("ArrowDown");
await expect(docs).toHaveAttribute("aria-selected", "true");
@@ -1503,7 +1504,7 @@ for (const editDraft of [false, true]) {
await panel.getByRole("button", { name: "Choose Commit to Amend", exact: true }).click();
await page.getByRole("option", { name: "Earlier local commit", exact: true }).click();
const message = panel.getByRole("textbox", { name: "Commit message" });
await expect(message).toHaveValue("Earlier local commit");
await expect.poll(() => fieldText(message)).toBe("Earlier local commit");
await panel.getByRole("button", { name: "Amend Commit", exact: true }).click();
const keep = page.getByRole("button", { name: "Create Amend Commit Anyway", exact: true });
@@ -1514,7 +1515,7 @@ for (const editDraft of [false, true]) {
await expect.poll(() => ipcCalls(page, "vcs_keep_amend_commit")).toEqual([{ repo: ROOT, commit: "prepared" }]);
await expect(page.getByText("Amend commit created", { exact: true })).toBeVisible();
expect(await ipcCalls(page, "vcs_commit")).toHaveLength(1);
await expect(message).toHaveValue(editDraft ? "New draft after conflict" : "Earlier local commit");
await expect.poll(() => fieldText(message)).toBe(editDraft ? "New draft after conflict" : "Earlier local commit");
await expect(panel.getByRole("checkbox", { name: "Amend", exact: true })).not.toBeChecked();
if (editDraft)
await expect
+20
Переглянути файл
@@ -132,3 +132,23 @@ test("F4 in the changes tree opens the source file even where activation opens t
await expect(sourceTab(page)).toHaveAttribute("aria-selected", "true");
await expect(diffTab(page)).toHaveCount(0);
});
test("modal Commit dialog shows the selected file's diff below the message, and Preview Diff hides it", async ({
workbench: page,
}, info) => {
await stubRepository(page);
await stubSettingsWrites(page);
await setCommitSetting(page, "nonModal", false);
await page.keyboard.press("Meta+k");
const dialog = page.getByRole("dialog", { name: "Commit Changes" });
const diff = dialog.getByRole("region", { name: "Diff", exact: true });
await expect(diff.getByText("Select a file to preview its changes")).toBeVisible();
await dialog.getByRole("tree", { name: "Changes" }).getByText(FILE, { exact: true }).click();
await expect(diff.locator(".cm-content").first()).toContainText("plugins {}");
await expect(page.getByRole("tab", { name: FILE })).toHaveCount(0);
await page.screenshot({ path: info.outputPath("commit-dialog-diff.png"), animations: "disabled" });
await dialog.getByRole("button", { name: "Preview Diff", exact: true }).click();
await expect(diff).toHaveCount(0);
await dialog.getByRole("button", { name: "Preview Diff", exact: true }).click();
await expect(diff.locator(".cm-content").first()).toContainText("plugins {}");
});
+4 -4
Переглянути файл
@@ -3,7 +3,7 @@
* latest task write the message. The agent and git are stubbed at the IPC layer.
*/
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const PATCH =
@@ -110,11 +110,11 @@ test("the agent of the latest task writes the commit message of the included cha
await page.keyboard.press("Meta+k");
const panel = page.getByRole("region", { name: "Commit", exact: true });
const message = panel.getByRole("textbox", { name: "Commit message" });
await expect(message).toHaveValue("");
await expect.poll(() => fieldText(message)).toBe("");
await panel.getByRole("button", { name: "Generate Commit Message with Agent" }).click();
await expect(message).toHaveValue("Update the Gradle build\n\nBump the Kotlin plugin.");
await expect.poll(() => fieldText(message)).toBe("Update the Gradle build\n\nBump the Kotlin plugin.");
const [request] = await ipcCalls(page, "agent_create");
const created = request!.request as {
provider: string;
@@ -153,5 +153,5 @@ test("a message typed while the agent works is not overwritten", async ({ workbe
await message.fill("My own message");
await expect(page.getByText("Commit message not replaced")).toBeVisible();
await expect(message).toHaveValue("My own message");
await expect.poll(() => fieldText(message)).toBe("My own message");
});
+3
Переглянути файл
@@ -151,6 +151,9 @@ test("C# parameter info bolds the argument being typed, `params` included", asyn
// The third argument: past the last parameter. Reopened, so the old popup can't answer for it.
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
// Past the refresh the typing scheduled: it must not bring the closed popup back.
await page.waitForTimeout(500);
await expect(popup).toBeHidden({ timeout: 10 });
await page.keyboard.press("Meta+p");
await expect(popup.locator("b")).toHaveText("args");
if (SHOTS) await page.screenshot({ path: `${SHOTS}/csharp-parameter-info.png` });
+35
Переглянути файл
@@ -46,12 +46,31 @@ test("includes and excludes original and working lines in a unified diff selecti
const marker = page.locator(".cm-include-hunk");
await expect(marker).toBeChecked();
const file = page.getByRole("checkbox", { name: "Include file in commit" });
await expect(file).toBeChecked();
// The block checkbox sits on the block's first row, its first deleted line.
const first = page.locator(".cm-deletedLine").filter({ hasText: "old one" });
await expect
.poll(async () => {
const box = await marker.boundingBox();
const row = await first.boundingBox();
return box && row && Math.abs(box.y + box.height / 2 - row.y - row.height / 2);
})
.toBeLessThan(2);
await marker.uncheck();
await expect(file).not.toBeChecked();
await marker.check();
await expect(file).toBeChecked();
const old = page.locator(".cm-deletedLine").filter({ hasText: "old two" });
await old.click({ button: "right", position: { x: 14, y: 8 } });
const menu = page.getByRole("menu", { name: "Context menu" });
await menu.getByRole("menuitem", { name: "Exclude Selected Lines from Commit" }).click();
await expect(marker).toHaveJSProperty("indeterminate", true);
await expect(file).toHaveJSProperty("indeterminate", true);
const toolbar = page.getByRole("toolbar", { name: "Diff", exact: true });
await expect(toolbar).toContainText("6 differences, 5 included");
const start = (await old.boundingBox())!;
const end = (await page.locator(".cm-line").filter({ hasText: "new one" }).boundingBox())!;
await page.mouse.move(start.x + 1, start.y + start.height / 2);
@@ -82,6 +101,22 @@ test("includes and excludes original and working lines in a unified diff selecti
await menu.getByRole("menuitem", { name: "Include Selected Lines in Commit" }).click();
await expect(marker).toBeChecked();
await expect(marker).toHaveJSProperty("indeterminate", false);
await file.focus();
await page.keyboard.press("Space");
await expect(marker).not.toBeChecked();
await expect(toolbar).toContainText("1 difference, 0 included");
await toolbar.getByRole("button", { name: "Side-by-side Viewer", exact: true }).click();
await expect(file).not.toBeChecked();
await expect
.poll(async () => {
const header = (await file.boundingBox())!;
const gutter = (await marker.boundingBox())!;
return Math.abs(header.x + header.width / 2 - gutter.x - gutter.width / 2);
})
.toBeLessThan(2);
await marker.check();
await expect(file).toBeChecked();
await expect(toolbar).not.toContainText("0 included");
});
test("a narrow diff keeps navigation, settings and the difference count visible", async ({ workbench: page }) => {
+3 -3
Переглянути файл
@@ -44,7 +44,7 @@ test("Find Usages places read and write filters with the other actions", async (
}
await actions.getByRole("button", write).click();
await expect(popup.getByRole("option")).toHaveCount(1);
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
await popup.getByRole("button", { name: "Open in Find Tool Window" }).click();
const view = page.getByRole("region", { name: "Find Usages", exact: true });
const toolbar = view.getByRole("toolbar", { name: "Usages actions", exact: true });
@@ -174,7 +174,7 @@ for (const theme of ["light", "dark"] as const) {
await expect(popup.getByRole("region", { name: "Preview", exact: true })).toBeVisible();
await preview.click();
await expect(popup.getByRole("region", { name: "Preview", exact: true })).toHaveCount(0);
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
await popup.getByRole("button", { name: "Open in Find Tool Window" }).click();
const usages = page.getByRole("region", { name: "Find Usages", exact: true });
const usageTree = usages.getByRole("tree", { name: "Usages", exact: true });
@@ -258,7 +258,7 @@ test("Find Usages lines use the tree font and keep line numbers beside the snipp
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
const popupMatch = popup.getByRole("option").first().locator("mark");
const popupFont = await popupMatch.evaluate((node) => getComputedStyle(node).fontFamily);
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
await popup.getByRole("button", { name: "Open in Find Tool Window" }).click();
const usages = page.getByRole("region", { name: "Find Usages", exact: true });
await expect(usages.locator("mark")).toHaveCount(3);
+14 -1
Переглянути файл
@@ -1,5 +1,5 @@
/** Shared helpers: open the workbench with the injected sample project and fail on page errors. */
import { expect, test as base, type Page } from "@playwright/test";
import { expect, test as base, type Locator, type Page } from "@playwright/test";
export const PROJECT = "acme-api";
@@ -146,6 +146,19 @@ export async function stubSettingsWrites(page: Page) {
}
/** The commands the page has invoked so far under `stubDesktop`, by name. */
/** The text of an editor-based field (`src/editor/TextField.tsx`), as a textarea's value: one line per row, placeholder left out. */
export async function fieldText(field: Locator): Promise<string> {
return field.evaluate((el) =>
[...el.querySelectorAll(".cm-line")]
.map((line) => {
const copy = line.cloneNode(true) as Element;
for (const hint of copy.querySelectorAll(".cm-placeholder")) hint.remove();
return copy.textContent ?? "";
})
.join("\n"),
);
}
export async function ipcCalls(page: Page, cmd: string): Promise<Record<string, unknown>[]> {
return page.evaluate((cmd) => window.__ipc.calls.filter((c) => c.cmd === cmd).map((c) => c.args), cmd);
}
+1 -1
Переглянути файл
@@ -88,7 +88,7 @@ test("the Usages preview match covers the whole row", async ({ workbench: page }
});
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
await expect(popup.getByRole("option")).toHaveCount(2);
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
await popup.getByRole("button", { name: "Open in Find Tool Window" }).click();
const view = page.getByRole("region", { name: "Find Usages", exact: true });
const mark = view.locator("mark").first();
await expect(mark).toHaveText("settlement");
+62
Переглянути файл
@@ -379,3 +379,65 @@ test("does not open the external link prompt for hover, forged link handlers, or
await page.waitForTimeout(200);
await expect(dialog).toHaveCount(0);
});
async function openLiveMdx(page: import("@playwright/test").Page, file: string, lines: string[]) {
await page.evaluate(
async ({ file, text }) => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
docBackend().files.set(file, text);
await editorService().openFile(file);
},
{ file, text: lines.join("\n") },
);
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
return page.frameLocator(`iframe[data-mdx-path="${file}"]`);
}
test("forwards an IDE shortcut typed in the MDX frame", async ({ workbench: page }) => {
const frame = await openLiveMdx(page, "/dev/acme-api/keys.mdx", ["# Keys", "", '<input aria-label="Probe field" />']);
const field = frame.getByRole("textbox", { name: "Probe field" });
await field.click();
await page.keyboard.press("Meta+Shift+o");
await expect(page.getByRole("combobox", { name: "Search query" })).toBeVisible();
});
test("ignores shortcuts the MDX code posts over a bridge port it took by replaying the handshake", async ({
workbench: page,
}) => {
const frame = await openLiveMdx(page, "/dev/acme-api/forged-keys.mdx", [
'import { useEffect, useState } from "react";',
"",
"export function Hijack() {",
" const [posted, setPosted] = useState(0);",
" useEffect(() => {",
" const onMessage = (e) => {",
" const d = e.data;",
' if (d && d.tag === "openidea-view" && typeof d.document === "string") {',
' const nonce = /__OPENIDEA_MDX_NONCE__="([0-9a-f]+)"/.exec(d.document)?.[1];',
' window.parent.postMessage({ tag: "openidea-mdx-preview", op: "guestHello", nonce }, "*");',
' } else if (d && d.op === "connect" && e.ports[0]) {',
" const port = e.ports[0];",
" for (let i = 0; i < 5; i++) {",
' port.postMessage({ tag: "openidea-mdx-preview", op: "keydown", key: "o", code: "KeyO", metaKey: true, shiftKey: true, ctrlKey: false, altKey: false });',
" }",
" setPosted(5);",
" }",
" };",
' window.addEventListener("message", onMessage);',
' window.parent.postMessage({ tag: "openidea-view", ready: true }, "*");',
' return () => window.removeEventListener("message", onMessage);',
" }, []);",
" return <p>{`Forged keys: ${posted}`}</p>;",
"}",
"",
"# Forged keys",
"",
"<Hijack />",
]);
await expect(frame.getByText("Forged keys: 5")).toBeVisible();
await page.waitForTimeout(300);
await expect(page.getByRole("combobox", { name: "Search query" })).toHaveCount(0);
});
+36 -6
Переглянути файл
@@ -8,12 +8,13 @@ async function showRemoteHost(page: Page) {
const settingsModule = "/src/platform/remoteSettings.ts";
const routeModule = "/src/platform/tauriCore.ts";
const actionsModule = "/src/platform/actions.ts";
const [{ useProject }, { DEFAULT_DEPLOYMENT_SERVER }, { setInvokeRoute }, { executeAction }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ settingsModule),
import(/* @vite-ignore */ routeModule),
import(/* @vite-ignore */ actionsModule),
]);
const [{ useProject }, { DEFAULT_DEPLOYMENT_SERVER, DEFAULT_SSH_CONFIG }, { setInvokeRoute }, { executeAction }] =
await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ settingsModule),
import(/* @vite-ignore */ routeModule),
import(/* @vite-ignore */ actionsModule),
]);
const entry = (path: string, isDir: boolean) => ({
path,
name: path.split("/").at(-1)!,
@@ -52,6 +53,7 @@ async function showRemoteHost(page: Page) {
useProject.setState({
settings: {
...useProject.getState().settings,
ssh: { configs: [{ ...DEFAULT_SSH_CONFIG, id: "demo", name: "Demo", host: "demo.example" }] },
deployment: {
servers: [
{
@@ -180,3 +182,31 @@ test("Upload Folder… opens a directory picker and cancellation leaves the serv
await expect.poll(async () => (await ipcCalls(page, "plugin:dialog|open")).length).toBe(2);
expect(await uploads(page)).toHaveLength(1);
});
test("Start SSH Session in Directory opens a shell in the folder, a file's folder or the root", async ({
workbench: page,
}) => {
await showRemoteHost(page);
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers["ssh_open_terminal"] = () => {
throw new Error("connection refused");
};
});
const remote = page.getByRole("tree", { name: "Remote files" });
const item = page.getByRole("menuitem", { name: "Start SSH Session in Directory", exact: true });
await remote.getByRole("treeitem", { name: "assets", exact: true }).click({ button: "right" });
await item.click();
await remote.getByRole("treeitem", { name: "index.html", exact: true }).click({ button: "right" });
await item.click();
const box = (await remote.boundingBox())!;
await page.mouse.click(box.x + 70, box.y + box.height - 10, { button: "right" });
await item.click();
const sessions = async () => (await ipcCalls(page, "ssh_open_terminal")).map(({ id, cwd }) => ({ id, cwd }));
await expect.poll(async () => (await sessions()).length).toBe(3);
expect(await sessions()).toEqual([
{ id: "demo", cwd: "/srv/demo/assets" },
{ id: "demo", cwd: "/srv/demo" },
{ id: "demo", cwd: "/srv/demo" },
]);
});
Loaded 100 of 248 files, more files were not shown because too many files have changed in this diff. Show more