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

...
Автор SHA1 Повідомлення Дата
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
161 змінених файлів з 4500 додано та 826 видалено

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")));
}
}
+5 -4
Переглянути файл
@@ -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")))
}
+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();
+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"] {
+82
Переглянути файл
@@ -54,6 +54,24 @@ fn isolated_projects(dir: &Path, user_home: Option<&Path>) -> bool {
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")]
pub struct GradleModel {
@@ -1166,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]
+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)]
+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}");
+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}"
);
}
}
}
}
+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());
}
+21
Переглянути файл
@@ -790,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)]
@@ -3814,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,
+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);
})
})
+2 -1
Переглянути файл
@@ -148,7 +148,8 @@ async fn ssh_session_in_a_directory_starts_the_login_shell_there() {
)
.await
.unwrap();
let out = read_until(&output, "\n");
// 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;
}
+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();
+1
Переглянути файл
@@ -40,6 +40,7 @@ mod roslyn;
mod scope;
mod server;
mod source_actions;
mod spring_aop;
mod spring_beans;
mod switch_source_header;
mod tcp;
+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,
}
+84
Переглянути файл
@@ -11014,3 +11014,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());
}
+27 -10
Переглянути файл
@@ -21,18 +21,35 @@ 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"
)
}
@@ -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}");
}
+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)]
+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}"),
})
+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
Переглянути файл
@@ -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
Переглянути файл
@@ -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` });
+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");
+3 -3
Переглянути файл
@@ -1,6 +1,6 @@
import type { Page } from "@playwright/test";
import type { EditorView } from "@codemirror/view";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test("edits the staged version and keeps an unsaved draft when the index changes", async ({ workbench: page }) => {
const root = "/dev/acme-api";
@@ -907,7 +907,7 @@ test("Amend previews the original commit independently of the staged changes", a
const changes = panel.getByRole("tree", { name: "Changes", exact: true });
await message.fill("Unsent draft");
await amend.check();
await expect(message).toHaveValue("Original commit\n\nDescription");
await expect.poll(() => fieldText(message)).toBe("Original commit\n\nDescription");
await expect(changes.getByRole("treeitem", { name: /Original commit 1 file/ })).toHaveAttribute(
"aria-expanded",
"true",
@@ -930,5 +930,5 @@ test("Amend previews the original commit independently of the staged changes", a
await expect(await ipcCalls(page, "vcs_commit")).toHaveLength(0);
await amend.uncheck();
await expect(changes.getByText("Original commit", { exact: true })).toHaveCount(0);
await expect(message).toHaveValue("Unsent draft");
await expect.poll(() => fieldText(message)).toBe("Unsent draft");
});
+4 -4
Переглянути файл
@@ -1,5 +1,5 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, stubDesktop, test } from "./fixtures";
async function seedReview(page: Page) {
await stubDesktop(page);
@@ -75,11 +75,11 @@ test("centers the unanchored composer, follows the editor font and reflows its r
const comment = (await popup.getByRole("button", { name: "Comment", exact: true }).boundingBox())!;
expect(comment.y).toBeGreaterThan(approve.y);
expect(comment.x + comment.width).toBeLessThan(300);
await expect(editor).toHaveValue("Please double-check the rounding step.");
await expect.poll(() => fieldText(editor)).toBe("Please double-check the rounding step.");
await editor.press("Escape");
await expect(popup).toHaveCount(0);
await openReview(page);
await expect(editor).toHaveValue("Please double-check the rounding step.");
await expect.poll(() => fieldText(editor)).toBe("Please double-check the rounding step.");
});
test("keeps anchored review controls and the comment visible after a long submission error", async ({
@@ -109,7 +109,7 @@ test("keeps anchored review controls and the comment visible after a long submis
const error = popup.getByRole("alert");
await expect(error).toContainText("Review request failed.");
await expect(button).toBeEnabled();
await expect(editor).toHaveValue("Check the batch limit.");
await expect.poll(() => fieldText(editor)).toBe("Check the batch limit.");
const box = (await popup.boundingBox())!;
const buttonBox = (await button.boundingBox())!;
expect(box.y + box.height).toBeLessThan(350);
+1 -1
Переглянути файл
@@ -111,7 +111,7 @@ function showAt(x: number, y: number, scenario: Scenario) {
clearTimeout(pendingLoad);
// A fresh mount also resets any position chosen by the previous drag.
flushSync(() => dismissUsagesPopup());
useUsageAccessOptions.setState({ read: true, write: true });
useUsageAccessOptions.setState({ read: true, write: true, imports: true });
useUsagesPopup.setState({
open: true,
anchor: { x, y },
+2 -2
Переглянути файл
@@ -1,4 +1,4 @@
import { expect, openFromTree, test } from "./fixtures";
import { expect, fieldText, openFromTree, test } from "./fixtures";
test("VCS Operations keeps its centered title visible in a short window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 640, height: 320 });
@@ -45,7 +45,7 @@ test("VCS Operations keeps its centered title visible in a short window", async
await expect(commitWindow).toBeVisible();
const message = commitWindow.getByRole("textbox", { name: "Commit message" });
await expect(message).toBeFocused();
expect(await message.evaluate((el) => (el instanceof HTMLTextAreaElement ? el.value : el.textContent))).toBe("");
expect(await fieldText(message)).toBe("");
});
test("VCS Operations offers repository setup and Local History outside Git", async ({ workbench: page }) => {
+1 -1
Переглянути файл
@@ -20,7 +20,7 @@ something to show.
| `java-app/` | JDK 21, Maven 3.9 | `mvn compile exec:java` | `mvn test` | `mvn test -DopenideaFail=true` | unused variable in `App.java` |
| `java-multimodule/` | JDK 21, Maven 3.9 | `mvn -q compile` | — | — | — |
| `kotlin-gradle-multi/` | JDK 21, Gradle 8 (no wrapper) | `gradle :app:run` | — | — | — |
| `spring-app/` | JDK 21, Maven 3.9, Spring Framework 6.2 | `mvn compile exec:java -Dexec.mainClass=com.example.shop.AppConfig` | — | — | — |
| `spring-app/` | JDK 21, Maven 3.9, Spring Framework 6.2, AspectJ 1.9 | `mvn compile exec:java -Dexec.mainClass=com.example.shop.AppConfig` | — | — | — |
| `c-app/` | gcc / g++ 12+, make, GDB 14+ | `make all` | — | — | — |
| `php-app/` | PHP 8.5, Composer | `composer quote` | `vendor/bin/pest` | `OPENIDEA_FAIL=1 vendor/bin/pest` | unused variable in `ThresholdCustoms.php` |
| `unittest-app/` | Python 3.10+ (standard library only) | — | `python -m unittest`; doctests in `inventory/stock.py` | `OPENIDEA_FAIL=1 python -m unittest` | unused import in `inventory/stock.py` |
+6 -1
Переглянути файл
@@ -7,7 +7,7 @@
<groupId>com.example</groupId>
<artifactId>openidea-fixture-spring</artifactId>
<version>0.1.0</version>
<description>OpenIDEA QA fixture: Spring beans and their injection points</description>
<description>OpenIDEA QA fixture: Spring beans, injection points and Spring AOP advice navigation</description>
<properties>
<maven.compiler.release>21</maven.compiler.release>
@@ -20,5 +20,10 @@
<artifactId>spring-context</artifactId>
<version>6.2.12</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.24</version>
</dependency>
</dependencies>
</project>
+37
Переглянути файл
@@ -0,0 +1,37 @@
package com.example.shop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
/**
* Order from {@link Ordered#getOrder()}, so {@code audit} is second in {@code place}'s chooser.
* {@code trace} matches {@code @annotation} on the method and {@code @within} on the class, and
* references {@link LoggingAspect}'s pointcut by its qualified name.
*/
@Aspect
@Component
public class AuditAspect implements Ordered {
@Pointcut("execution(* com.example.shop.OrderService.place(..))")
public void orderPlacement() {}
@Override
public int getOrder() {
return 2;
}
@After("orderPlacement()")
public void audit(JoinPoint joinPoint) {
System.out.println("audit " + joinPoint.getSignature().toShortString());
}
@Before("com.example.shop.LoggingAspect.serviceLayer() && (@annotation(com.example.shop.Audited) || @within(com.example.shop.Audited))")
public void trace(JoinPoint joinPoint) {
System.out.println("traced " + joinPoint.getSignature().toShortString());
}
}
+15
Переглянути файл
@@ -0,0 +1,15 @@
package com.example.shop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Method-level {@code @annotation} and type-level {@code @within} target for AOP navigation:
* {@link OrderService#place(String)} and {@link Inventory#reconcile()} carry it on the method,
* {@link Checkout} on the class.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Audited {}
+3
Переглянути файл
@@ -10,7 +10,10 @@ import org.springframework.stereotype.Component;
* Bean navigation: each injection point has a gutter icon to its bean, and each bean one back to
* where it is injected. Remove {@code @Qualifier("sms")} and both notifiers become candidates for
* {@code channel}; remove {@code @Component} from SmsNotifier and its icons go away.
* AOP navigation: the class-level {@code @Audited} makes {@code checkout} an {@code @within}
* target of AuditAspect.trace.
*/
@Audited
@Component
public class Checkout {
@Autowired
+17
Переглянути файл
@@ -0,0 +1,17 @@
package com.example.shop;
import org.springframework.stereotype.Component;
/**
* Negation demo with {@link NegationAspect}: {@code stock} carries no {@code @Audited}, so that
* aspect's advice matches it; {@code reconcile} is annotated, so {@code !@annotation} excludes it.
*/
@Component
public class Inventory {
public String stock(String item) {
return "stock:" + item;
}
@Audited
public void reconcile() {}
}
+39
Переглянути файл
@@ -0,0 +1,39 @@
package com.example.shop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* AOP navigation: {@code place} is advised by four advices (the chooser), {@code checkout} by
* two, {@code SmsNotifier.send} by one (a direct jump). {@code serviceLayer} is the named
* pointcut another aspect references; the after advices use Spring's {@code pointcut} alias.
*/
@Aspect
@Component
@Order(1)
public class LoggingAspect {
@Pointcut("within(com.example.shop..*)")
public void serviceLayer() {}
@Before("serviceLayer() && execution(* com.example.shop.OrderService.*(..))")
public void beforeOrder(JoinPoint joinPoint) {
System.out.println("before " + joinPoint.getSignature().toShortString());
}
@AfterReturning(pointcut = "execution(* com.example.shop.Checkout.checkout(..))", returning = "order")
public void afterCheckout(Object order) {
System.out.println("checkout returned " + order);
}
@AfterThrowing(pointcut = "execution(* com.example.shop.EmailNotifier.send(..))", throwing = "error")
public void afterSendFailure(Throwable error) {
System.out.println("email failed: " + error);
}
}
+22
Переглянути файл
@@ -0,0 +1,22 @@
package com.example.shop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* Negation: {@code !@annotation(com.example.shop.Audited)} excludes {@link Inventory#reconcile()}
* from this advice, while {@link Inventory#stock(String)} carries no annotation and is matched:
* the advice method's icon navigates to {@code stock} only, and {@code reconcile} shows just
* {@link AuditAspect#trace}, the {@code @annotation} advice it still matches.
*/
@Aspect
@Component
public class NegationAspect {
@Before("execution(* com.example.shop.Inventory.*(..)) && !@annotation(com.example.shop.Audited)")
public void beforeUnannotated(JoinPoint joinPoint) {
System.out.println("unannotated " + joinPoint.getSignature().toShortString());
}
}
+20
Переглянути файл
@@ -0,0 +1,20 @@
package com.example.shop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* No order, so its rows show the advice kind only. {@code Notifier+} matches both
* implementations: the advice's chooser has two targets, and each notifier has this one advice.
*/
@Aspect
@Component
public class NotificationAspect {
@After("execution(* com.example.shop.Notifier+.send(..))")
public void afterEverySend(JoinPoint joinPoint) {
System.out.println("sent " + joinPoint.getSignature().toShortString());
}
}
+2
Переглянути файл
@@ -4,6 +4,8 @@ import org.springframework.stereotype.Service;
@Service
public class OrderService {
/** {@code @annotation(Audited)} in AuditAspect.trace matches this method. */
@Audited
public String place(String item) {
return "order:" + item;
}
+27
Переглянути файл
@@ -0,0 +1,27 @@
package com.example.shop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* {@code execution} with {@code *} (return type and method) and {@code ..} (package and
* arguments), and {@code @Order(3)}: its advice is last in {@code place}'s chooser.
*/
@Aspect
@Component
@Order(3)
public class TimingAspect {
@Around("execution(* com.example.shop..*Service.*(..))")
public Object timed(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.nanoTime();
try {
return joinPoint.proceed();
} finally {
System.out.println(joinPoint.getSignature().toShortString() + " took " + (System.nanoTime() - start) + " ns");
}
}
}
+20
Переглянути файл
@@ -0,0 +1,20 @@
package com.example.shop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* {@code args(...)} is outside the first slice: this advice contributes no AOP marker, and its
* advice method shows no icon.
*/
@Aspect
@Component
public class UnsupportedAspect {
@Before("execution(* com.example.shop..*.*(..)) && args(java.lang.String)")
public void logArgument(JoinPoint joinPoint) {
System.out.println("argument " + joinPoint.getArgs()[0]);
}
}
+22 -5
Переглянути файл
@@ -1,7 +1,8 @@
diff --git a/vim.js b/vim.js
index 3cafa6bcf0c99f2ae25a5da8936d3f29445f2d6d..64c9c9bbf2bfa5fd6313d36ac6495b605a8a79d7 100644
--- a/vim.js
+++ b/vim.js
@@ -236,6 +236,8 @@
@@ -236,6 +236,8 @@ export function initVim(CM) {
{ keys: '"<register>', type: 'action', action: 'setRegister' },
{ keys: '<C-r><register>', type: 'action', action: 'insertRegister', context: 'insert', isEdit: true },
{ keys: '<C-o>', type: 'action', action: 'oneNormalCommand', context: 'insert' },
@@ -10,7 +11,7 @@ diff --git a/vim.js b/vim.js
{ keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
{ keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
@@ -248,6 +250,11 @@
@@ -248,6 +250,11 @@ export function initVim(CM) {
{ keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },
{ keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },
// Text object motions
@@ -22,7 +23,7 @@ diff --git a/vim.js b/vim.js
{ keys: 'a<register>', type: 'motion', motion: 'textObjectManipulation' },
{ keys: 'i<register>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
// Search
@@ -1974,6 +1981,8 @@
@@ -1974,6 +1981,8 @@ export function initVim(CM) {
if (command.type == 'keyToEx') {
// Handle user defined Ex to Ex mappings
exCommandDispatcher.processCommand(cm, command.exArgs.input);
@@ -31,7 +32,7 @@ diff --git a/vim.js b/vim.js
} else {
/**@type{import("./types").PromptOptions} */
var promptOptions = {
@@ -2582,6 +2591,8 @@
@@ -2582,6 +2591,8 @@ export function initVim(CM) {
if (head.sticky == "before") head.ch--;
return head;
},
@@ -40,7 +41,7 @@ diff --git a/vim.js b/vim.js
textObjectManipulation: function(cm, head, motionArgs, vim) {
// TODO: lots of possible exceptions that can be thrown here. Try da(
// outside of a () block.
@@ -3423,6 +3434,8 @@
@@ -3423,6 +3434,8 @@ export function initVim(CM) {
cm.replaceSelection(text);
}
},
@@ -49,3 +50,19 @@ diff --git a/vim.js b/vim.js
oneNormalCommand: function(cm, actionArgs, vim) {
exitInsertMode(cm, true);
vim.insertModeReturn = true;
@@ -5870,6 +5883,15 @@ export function initVim(CM) {
};
}
} else {
+ // OpenIDEA: IdeaVim's `<Action>(id)` right-hand side runs the IDE action, as rc mappings do.
+ var ideAction = /^<Action>\(([^)\s]+)\)$/i.exec(rhs);
+ if (ideAction) {
+ /**@type {any} */
+ var exMapping = { keys: lhs, type: 'keyToEx', exArgs: { input: 'action ' + ideAction[1] } };
+ if (ctx) { exMapping.context = ctx; }
+ _mapCommand(exMapping);
+ return;
+ }
// Key to key or ex mapping
/**@type {vimKey} */
var mapping = {
Створено
+3 -3
Переглянути файл
@@ -11,7 +11,7 @@ patchedDependencies:
'@codemirror/[email protected]': eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc
'@codemirror/view': 3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e
'@lezer/lr': 1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8
'@replit/[email protected]': 9342a63bb360d0e59c906874d06f35281b15f933a43889566f74554fe12d3263
'@replit/[email protected]': e5f0b0d3fd721504269ba2268124524f764f83a04ac4ffa6a0ff8fd121583e4f
importers:
@@ -3752,7 +3752,7 @@ snapshots:
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@replit/[email protected](patch_hash=9342a63bb360d0e59c906874d06f35281b15f933a43889566f74554fe12d3263)': {}
'@replit/[email protected](patch_hash=e5f0b0d3fd721504269ba2268124524f764f83a04ac4ffa6a0ff8fd121583e4f)': {}
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected](patch_hash=eb0f811cd8918704234484dcb1f6740e5cd133ac639d82b968e5b87ae992b9dc))(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected](patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e))':
dependencies:
@@ -3761,7 +3761,7 @@ snapshots:
'@codemirror/search': 6.7.2
'@codemirror/state': 6.7.6
'@codemirror/view': 6.44.2(patch_hash=3b03bac82db7f12cd29725565880e68e8313a585ca1262b19f3d9785f860ce3e)
'@replit/codemirror-vim-core': 0.1.0(patch_hash=9342a63bb360d0e59c906874d06f35281b15f933a43889566f74554fe12d3263)
'@replit/codemirror-vim-core': 0.1.0(patch_hash=e5f0b0d3fd721504269ba2268124524f764f83a04ac4ffa6a0ff8fd121583e4f)
'@rolldown/[email protected]':
optional: true
+1 -1
Переглянути файл
@@ -755,7 +755,7 @@ pub(crate) async fn check_update(app: &AppHandle, source: UpdateSource) -> IdeRe
let update = tokio::time::timeout(std::time::Duration::from_secs(60), updater.check())
.await
.map_err(|e| IdeError::unavailable(e.to_string()))?
.map_err(|e| IdeError::unavailable(e.to_string()))?;
.map_err(|e| IdeError::unavailable(ide_http::client::describe(&e)))?;
Ok(UpdateCheck {
enabled: true,
update: update.map(|u| UpdateInfo {
+5 -4
Переглянути файл
@@ -195,10 +195,11 @@ pub(crate) async fn download_update(
mut progress: impl FnMut(u64, Option<u64>),
) -> IdeResult<DownloadedUpdate> {
let updater = updater(app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
let update =
cancellable(token, async { updater.check().await.map_err(|error| IdeError::unavailable(error.to_string())) })
.await?
.ok_or_else(|| IdeError::not_found("no update available"))?;
let update = cancellable(token, async {
updater.check().await.map_err(|error| IdeError::unavailable(ide_http::client::describe(&error)))
})
.await?
.ok_or_else(|| IdeError::not_found("no update available"))?;
let directory = app
.path()
.app_cache_dir()
+3 -2
Переглянути файл
@@ -47,7 +47,8 @@ pub(crate) async fn fetch(
if offset > 0 {
request = request.header(RANGE, format!("bytes={offset}-"));
}
let response = request.send().await.map_err(|error| IdeError::unavailable(error.to_string()))?;
let response =
request.send().await.map_err(|error| IdeError::unavailable(ide_http::client::describe(&error)))?;
let status = response.status();
if status == StatusCode::RANGE_NOT_SATISFIABLE && offset > 0 {
@@ -171,7 +172,7 @@ async fn append_body(
progress(downloaded, total);
}
Ok(None) => break Ok(()),
Err(error) => break Err(IdeError::unavailable(error.to_string())),
Err(error) => break Err(IdeError::unavailable(ide_http::client::describe(&error))),
}
};
// tokio writes in the background: flush even when the body broke off, so the bytes
+1
Переглянути файл
@@ -501,6 +501,7 @@ lsp_snapshot_completion trusted project_host bin
lsp_snapshot_diagnostics trusted project_host bindings async
lsp_source_action_text trusted project_host bindings async
lsp_source_definition trusted project_host bindings async
lsp_spring_aop_markers trusted project_host bindings async
lsp_spring_bean_markers trusted project_host bindings async
lsp_stop trusted project_host bindings async
lsp_switch_source_header trusted project_host bindings async
+45 -3
Переглянути файл
@@ -1349,6 +1349,12 @@ export const commands = {
* instead of its `.d.ts`. Cancel with `cancel_request(request)`.
*/
lspSourceDefinition: (request: RequestId, doc: DocId, pos: Pos) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_source_definition", { request, doc, pos })),
/**
* 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)`.
*/
lspSpringAopMarkers: (request: RequestId, doc: DocId) => typedError<SpringAopMarker[] | null, IdeError>(__TAURI_INVOKE("lsp_spring_aop_markers", { request, doc })),
/**
* The document's Spring bean markers (injection points and bean declarations with their
* targets); `None` when no server attached to it provides them. Cancel with `cancel_request(request)`.
@@ -4238,11 +4244,13 @@ export type AgentPluginCapabilities_Deserialize = {
commandCount: number,
hookFiles?: string[],
stdioCommands?: string[],
/** Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts. */
lspCommands?: string[],
hasLsp?: boolean,
hasCanvasOrApp?: boolean,
/** Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle. */
nativeHarnesses?: 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). */
capabilityHash?: string | null,
requiresConsent?: boolean,
};
@@ -4258,11 +4266,13 @@ export type AgentPluginCapabilities_Serialize = {
commandCount: number,
hookFiles?: string[],
stdioCommands?: string[],
/** Language server commands (`.lsp.json`, `lsp.json`, a manifest's `lspServers`) the agent starts. */
lspCommands?: string[],
hasLsp: boolean,
hasCanvasOrApp: boolean,
/** Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle. */
nativeHarnesses?: 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). */
capabilityHash?: string | null,
requiresConsent: boolean,
};
@@ -13023,7 +13033,9 @@ export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" |
/** The Dart server published a document's Flutter outline. */
"flutterOutline" |
/** Spring bean markers of open documents may have changed. */
"springBeanMarkers";
"springBeanMarkers" |
/** Spring AOP markers of open documents may have changed. */
"springAopMarkers";
export type MainToolbarSettings = {
left?: string[],
@@ -17566,6 +17578,36 @@ export type SpellingSettings = {
defaultDictionary?: string | null,
};
export type SpringAopAdviceKind = "before" | "after" | "afterReturning" | "afterThrowing" | "around";
export type 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";
/**
* A Spring AOP marker on a Java method: an advised method (`ToAdvice`) or an advice
* method (`ToAdvised`), whichever server found it.
*/
export type SpringAopMarker = {
/** The method's name range. */
range: Range,
name: string,
direction: SpringAopDirection,
/** Never empty. */
targets: SpringAopTarget[],
};
export type SpringAopTarget = {
location: Location,
label: string,
/** Set on an advice target; `None` on an advised method. */
adviceKind: SpringAopAdviceKind | null,
/** The advice's Spring `order`; `None` when it has none. */
order: number | null,
};
export type SpringBeanDirection = "toBean" | "toInjectionPoint";
/**
+223
Переглянути файл
@@ -0,0 +1,223 @@
/** The editor-based text field: Vim goes first on Escape, the field stays controlled. */
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render } from "@testing-library/react";
import { useRef, useState } from "react";
import { EditorView } from "@codemirror/view";
import { activate as activateVim } from "@/features/vim";
import { useVimSettings } from "@/features/vim/settings";
import { TextField, type TextFieldHandle } from "./TextField";
const contentOf = (label: string) => {
const el = document.querySelector<HTMLElement>(`[aria-label="${label}"]`);
if (!el) throw new Error("field not rendered");
return el;
};
const viewOf = (label: string): EditorView => {
const view = EditorView.findFromDOM(contentOf(label));
if (!view) throw new Error("not an editor field");
return view;
};
/** Waits until Vim mode's contribution has reached the field (the engine loads lazily). */
const untilVim = async (label: string): Promise<EditorView> => {
const view = viewOf(label);
await vi.waitFor(() => expect(view.dom.getAttribute("data-openidea-vim")).toBeTruthy(), { timeout: 5000 });
return view;
};
/** Parent stores the text, like the commit message store does. */
function renderControlled(label: string, initial: string) {
const onChange = vi.fn();
function Holder() {
const [text, setText] = useState(initial);
return (
<TextField
path="test://field"
ariaLabel={label}
value={text}
onChange={(t) => {
onChange(t);
setText(t);
}}
/>
);
}
render(<Holder />);
return { onChange };
}
/** Parent owns the value outright: rerender replaces it from the outside. */
function renderStatic(label: string, initial: string) {
const onChange = vi.fn();
function Holder({ text }: { text: string }) {
return <TextField path="test://field" ariaLabel={label} value={text} onChange={onChange} />;
}
const { rerender } = render(<Holder text={initial} />);
return { rerender: (next: string) => rerender(<Holder text={next} />) };
}
/** A controlled field exposing the handle, for focus and view assertions. */
function renderHandleField(label: string, initial: string) {
function Holder() {
const [text, setText] = useState(initial);
const ref = useRef<TextFieldHandle>(null);
return (
<>
<TextField path="test://field" ariaLabel={label} value={text} onChange={setText} ref={ref} />
<button onClick={() => ref.current?.focus()}>focus field</button>
</>
);
}
render(<Holder />);
}
afterEach(() => {
useVimSettings.setState({ enabled: false, handlers: {} }, true);
});
describe("TextField", () => {
it("is a focusable editor textbox that reports typed text", () => {
const { onChange } = renderControlled("Field", "");
const view = viewOf("Field");
expect(contentOf("Field").getAttribute("role")).toBe("textbox");
act(() => {
view.focus();
view.dispatch(view.state.replaceSelection("typed"), { userEvent: "input.type" });
});
expect(view.state.doc.toString()).toBe("typed");
expect(onChange).toHaveBeenLastCalledWith("typed");
});
it("follows an external value change", () => {
const { rerender } = renderStatic("Field", "first");
const view = viewOf("Field");
expect(view.state.doc.toString()).toBe("first");
rerender("second");
expect(view.state.doc.toString()).toBe("second");
});
it("keeps the focus in the field while Vim is off and Esc still leaves it", () => {
renderHandleField("Field", "text");
const view = viewOf("Field");
act(() => view.focus());
expect(document.activeElement).toBe(view.contentDOM);
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
});
it("with Vim mode on, Esc leaves Insert mode and keeps the focus in the field", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
try {
renderHandleField("Field", "hello");
const view = await untilVim("Field");
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("insert");
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
expect(document.activeElement).toBe(view.contentDOM);
} finally {
disposeVim();
}
});
it("with Vim mode on, a further Esc in Normal mode returns the focus (explicit)", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
try {
renderHandleField("Field", "hello");
const view = await untilVim("Field");
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
} finally {
disposeVim();
}
});
it("with Vim mode on, operators edit the field's text (dd)", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
try {
const { onChange } = renderControlled("Field", "subject\nbody");
const view = await untilVim("Field");
act(() => {
view.focus();
view.dispatch({ selection: { anchor: 0 } });
});
fireEvent.keyDown(view.contentDOM, { key: "d" });
fireEvent.keyDown(view.contentDOM, { key: "d" });
expect(view.state.doc.toString()).toBe("body");
expect(onChange).toHaveBeenLastCalledWith("body");
} finally {
disposeVim();
}
});
it("takes no edits while read-only, and reports caret moves that don't change the text", () => {
const onSelectionChange = vi.fn();
function Holder({ readOnly }: { readOnly: boolean }) {
const [text, setText] = useState("hello");
return (
<TextField
path="test://field"
ariaLabel="Field"
value={text}
onChange={setText}
readOnly={readOnly}
onSelectionChange={onSelectionChange}
/>
);
}
const { rerender } = render(<Holder readOnly={false} />);
const view = viewOf("Field");
act(() => view.dispatch({ selection: { anchor: 2 } }));
expect(onSelectionChange).toHaveBeenCalledWith(2, view);
rerender(<Holder readOnly />);
expect(view.state.readOnly).toBe(true);
expect(contentOf("Field").getAttribute("contenteditable")).toBe("false");
rerender(<Holder readOnly={false} />);
expect(view.state.readOnly).toBe(false);
});
it("with Vim mode on, gives a key to onKeyDownFirst before Vim and to onKeyDown after it", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
const first = vi.fn((e: KeyboardEvent) => e.key === "ArrowDown");
const after = vi.fn((_e: KeyboardEvent) => false);
try {
function Holder() {
const [text, setText] = useState("one\ntwo");
return (
<TextField
path="test://field"
ariaLabel="Field"
value={text}
onChange={setText}
onKeyDownFirst={first}
onKeyDown={after}
/>
);
}
render(<Holder />);
const view = await untilVim("Field");
act(() => view.focus());
act(() => view.dispatch({ selection: { anchor: 0 } }));
fireEvent.keyDown(view.contentDOM, { key: "ArrowDown" });
expect(first).toHaveBeenCalledTimes(1);
expect(view.state.selection.main.head).toBe(0);
fireEvent.keyDown(view.contentDOM, { key: "i" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("insert");
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
expect(after.mock.calls.some(([e]) => e.key === "Escape" && !e.defaultPrevented)).toBe(false);
} finally {
disposeVim();
}
});
});
+224
Переглянути файл
@@ -0,0 +1,224 @@
/**
* A multi-line text field built on the code editor: Vim and every other `embedded`
* editor contribution apply through the shared embedded-editor mechanism
* (`embeddedEditorExtensions`) and are reconfigured live, so with Vim mode on
* `Esc` goes to Vim first and only moves the focus when Vim does not use it.
* The commit message field is the first user (#7024).
*/
import { forwardRef, useImperativeHandle, useLayoutEffect, useRef, type CSSProperties, type RefObject } from "react";
import { Annotation, Compartment, EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap, placeholder as cmPlaceholder } from "@codemirror/view";
import { defaultKeymap, history } from "@codemirror/commands";
import { embeddedEditorExtensions } from "./api";
/** Marks a transaction the field itself made (an external value or a host echo): no `onChange`. */
export const fieldEcho = Annotation.define<boolean>();
/** Created once: every `EditorView.theme` call mounts new CSS rules into the document. */
const FIELD_THEME = EditorView.theme({
"&": { height: "100%", backgroundColor: "transparent" },
".cm-scroller": {
backgroundColor: "transparent",
fontFamily: "inherit",
fontWeight: "inherit",
lineHeight: "inherit",
},
".cm-content": { padding: "6px var(--pad, 10px)" },
".cm-line": { padding: "0" },
".cm-placeholder": {
color: "var(--fg-subtle)",
fontFamily: "var(--font-ui)",
fontSize: "var(--fs-ui)",
},
});
const readOnlyExtension = (readOnly: boolean) =>
readOnly ? [EditorState.readOnly.of(true), EditorView.editable.of(false)] : [];
export interface TextFieldHandle {
focus(): void;
/** The live editor view, null before mount and after unmount. */
view(): EditorView | null;
}
export interface TextFieldProps {
value: string;
/** Text typed or deleted in the field; not called for the field's own echo transactions. */
onChange: (text: string, view: EditorView) => void;
/** A stable pseudo document path; embedded editor contributions and their events use it. */
path: string;
placeholder?: string;
ariaLabel?: string;
spellCheck?: boolean;
/** Marks the editor as its tool window's late-focus target (`data-autofocus`). */
autoFocus?: boolean;
/** Whether long lines wrap (a textarea-like field always does). */
wrap?: boolean;
/** Reported on the editor as `aria-invalid` (a failed check at the field). */
invalid?: boolean;
/** The editor's content lost the focus. */
onBlur?: () => void;
/** Runs after Vim has had the key; return true when the key was handled. */
onKeyDown?: (event: KeyboardEvent, view: EditorView) => boolean | void;
/** Runs before Vim and the editor's keys (a completion list open at the field); true when handled. */
onKeyDownFirst?: (event: KeyboardEvent, view: EditorView) => boolean | void;
/** The caret moved without the text changing. */
onSelectionChange?: (head: number, view: EditorView) => void;
/** No editing (a request in flight); the text stays selectable. */
readOnly?: boolean;
className?: string;
style?: CSSProperties;
/** Receives the host element, to anchor popups at the field. */
hostRef?: RefObject<HTMLDivElement | null>;
}
/** A controlled editor field; see the module comment. */
export const TextField = forwardRef<TextFieldHandle, TextFieldProps>(function TextField(
{
value,
onChange,
path,
placeholder,
ariaLabel,
spellCheck,
autoFocus,
wrap = true,
invalid,
onBlur,
onKeyDown,
onKeyDownFirst,
onSelectionChange,
readOnly = false,
className,
style,
hostRef,
},
ref,
) {
const host = useRef<HTMLDivElement>(null);
const view = useRef<EditorView | null>(null);
const wrapCompartment = useRef(new Compartment());
const readOnlyCompartment = useRef(new Compartment());
// The handlers change every render; the view is built once and reads them through refs.
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const onKeyDownRef = useRef(onKeyDown);
onKeyDownRef.current = onKeyDown;
const onKeyDownFirstRef = useRef(onKeyDownFirst);
onKeyDownFirstRef.current = onKeyDownFirst;
const onSelectionChangeRef = useRef(onSelectionChange);
onSelectionChangeRef.current = onSelectionChange;
const onBlurRef = useRef(onBlur);
onBlurRef.current = onBlur;
const valueRef = useRef(value);
valueRef.current = value;
useLayoutEffect(() => {
if (!host.current) return;
const editor = new EditorView({
parent: host.current,
state: EditorState.create({
doc: valueRef.current,
extensions: [
FIELD_THEME,
history(),
keymap.of(defaultKeymap),
wrapCompartment.current.of(wrap ? EditorView.lineWrapping : []),
readOnlyCompartment.current.of(readOnlyExtension(readOnly)),
Prec.highest(
EditorView.domEventHandlers({
keydown: (event, current) => onKeyDownFirstRef.current?.(event, current) === true,
}),
),
...(placeholder ? [cmPlaceholder(placeholder)] : []),
embeddedEditorExtensions(path),
EditorView.updateListener.of((update) => {
if (!update.docChanged) {
if (update.selectionSet) onSelectionChangeRef.current?.(update.state.selection.main.head, update.view);
return;
}
if (update.transactions.some((tr) => tr.annotation(fieldEcho))) return;
onChangeRef.current?.(update.state.doc.toString(), update.view);
}),
EditorView.domEventHandlers({
keydown(event, current) {
if (onKeyDownRef.current && onKeyDownRef.current(event, current) === true) return true;
// Vim had the key first (its handlers run at highest precedence);
// only an Escape Vim does not use moves the focus, as the textarea's did.
if (event.key === "Escape" && !event.defaultPrevented && !current.composing) {
current.contentDOM.blur();
return true;
}
return false;
},
blur(_event, current) {
// A view being destroyed (unmount, or React re-running the effect) blurs on removal:
// only the live field's blur counts.
if (view.current === current) onBlurRef.current?.();
return false;
},
}),
EditorView.contentAttributes.of({
"aria-label": ariaLabel ?? "",
"aria-multiline": "true",
role: "textbox",
spellcheck: spellCheck ? "true" : "false",
}),
],
}),
});
view.current = editor;
return () => {
view.current = null;
editor.destroy();
};
// The field is created once; `path` identifies it for its lifetime.
// eslint-disable-next-line react-hooks/exhaustive-deps -- placeholder/aria are stable per field
}, []);
useLayoutEffect(() => {
view.current?.dispatch({ effects: wrapCompartment.current.reconfigure(wrap ? EditorView.lineWrapping : []) });
}, [wrap]);
useLayoutEffect(() => {
view.current?.dispatch({ effects: readOnlyCompartment.current.reconfigure(readOnlyExtension(readOnly)) });
}, [readOnly]);
useLayoutEffect(() => {
const editor = view.current;
if (!editor || editor.state.doc.toString() === value) return;
editor.dispatch({
changes: { from: 0, to: editor.state.doc.length, insert: value },
selection: { anchor: value.length },
annotations: fieldEcho.of(true),
});
}, [value]);
// `data-autofocus` moves at runtime (the Commit window takes the activation focus
// only when Commit… asked for the message), like the textarea attribute did. Set before
// paint: the tool window looks for it in the next animation frame.
useLayoutEffect(() => {
const el = view.current?.contentDOM;
if (!el) return;
if (invalid) el.setAttribute("aria-invalid", "true");
else el.removeAttribute("aria-invalid");
if (autoFocus) el.setAttribute("data-autofocus", "true");
else el.removeAttribute("data-autofocus");
}, [invalid, autoFocus]);
useImperativeHandle(ref, () => ({
focus: () => view.current?.focus(),
view: () => view.current,
}));
return (
<div
ref={(el) => {
host.current = el;
if (hostRef) hostRef.current = el;
}}
className={className}
style={style}
/>
);
});
+13 -7
Переглянути файл
@@ -96,7 +96,12 @@ function selectCopiedLines(view: EditorView, lines: ReturnType<typeof distinctCa
});
}
/** Delete whole caret lines, merging adjacent lines and keeping one caret per surviving position. */
/**
* Delete whole caret lines, merging adjacent lines and keeping one caret per surviving position.
* As in IntelliJ (`CutHandler`), each caret goes to the start of the line that takes the cut
* line's place, so repeated cuts take the following lines; after the last line, to the start of
* the line before it.
*/
function cutCaretLines(view: EditorView, lines: ReturnType<typeof distinctCaretLines>) {
const state = view.state;
const spans: Array<[first: number, last: number]> = [];
@@ -113,12 +118,13 @@ function cutCaretLines(view: EditorView, lines: ReturnType<typeof distinctCaretL
}),
);
const doc = changes.apply(state.doc);
const mapped = lines.map(({ line, pos }) => {
const target = doc.lineAt(changes.mapPos(line.from, -1));
return {
line: line.number,
range: EditorSelection.cursor(target.from + Math.min(pos - line.from, target.length)),
};
const mapped = lines.map(({ line }) => {
const last = spans.find(([first, end]) => line.number >= first && line.number <= end)![1];
const target =
last < state.doc.lines
? changes.mapPos(state.doc.line(last + 1).from, 1)
: doc.lineAt(changes.mapPos(line.from, -1)).from;
return { line: line.number, range: EditorSelection.cursor(target) };
});
const unique = mapped.filter(({ range }, i) => mapped.findIndex((other) => other.range.head === range.head) === i);
const mainLine = state.doc.lineAt(state.selection.main.head).number;
+12 -3
Переглянути файл
@@ -360,7 +360,7 @@ describe("line-wise paste", () => {
const view = make("one\ntwo", [5]);
expect(copy(view, "cut")).toBe("two");
expect(view.state.doc.toString()).toBe("one");
expect(view.state.selection.main.head).toBe(1);
expect(view.state.selection.main.head).toBe(0);
expect(clipboardHistory()[0]).toEqual({ text: "two", linewise: true });
});
@@ -401,7 +401,7 @@ describe("line-wise paste", () => {
const view = make("one\ntwo\nthree\nfour\nfive", [1, 2, 15]);
expect(copy(view, "cut")).toBe("one\nfour");
expect(view.state.doc.toString()).toBe("two\nthree\nfive");
expect(view.state.selection.ranges.map((range) => range.head)).toEqual([1, 5]);
expect(view.state.selection.ranges.map((range) => range.head)).toEqual([0, 10]);
expect(clipboardHistory()[0]).toEqual({ text: "one\nfour", linewise: true });
});
@@ -409,7 +409,16 @@ describe("line-wise paste", () => {
const view = make("one\ntwo\nthree\nfour", [1, 2, 5, 9]);
expect(copy(view, "cut")).toBe("one\ntwo\nthree");
expect(view.state.doc.toString()).toBe("four");
expect(view.state.selection.ranges.map((range) => range.head)).toEqual([1]);
expect(view.state.selection.ranges.map((range) => range.head)).toEqual([0]);
});
it("keeps the caret on the cut line's number, at the start of the line moved up, so repeated cuts go down", () => {
const view = make("one\n two\nthree", [6]);
expect(copy(view, "cut")).toBe(" two");
expect(view.state.doc.toString()).toBe("one\nthree");
expect(view.state.selection.main.head).toBe(4);
expect(copy(view, "cut")).toBe("three");
expect(view.state.doc.toString()).toBe("one");
});
it("allows line copy but not deletion in a read-only editor", () => {
+27 -43
Переглянути файл
@@ -16,6 +16,7 @@ vi.mock("./fileAttributes", async (original) => ({
}));
const ctrl = editorController();
const cells: EditorView[] = [];
let disposeActions: () => void;
beforeAll(() => {
disposeActions = registerEditorActions();
@@ -30,6 +31,12 @@ afterEach(() => {
useEditorStatus.setState({ status: null });
useContextKeys.setState({}, true);
_setFocusedCellEditor(null);
// A live view's pending focus timer would run after jsdom is torn down.
for (const view of cells.splice(0)) {
const host = view.dom.parentElement;
view.destroy();
host?.remove();
}
toggleReadOnlyMock.mockClear();
});
@@ -39,32 +46,23 @@ function focusedCell(doc = "x = 1\n"): { view: EditorView; clear: () => void } {
document.body.appendChild(host);
// `columnModeField`: what a cell editor carries through its own extension list.
const view = new EditorView({ doc, parent: host, extensions: columnModeField });
cells.push(view);
view.focus();
if (!view.hasFocus) throw new Error("the jsdom view did not take focus");
_setFocusedCellEditor(view);
return { view, clear: () => _setFocusedCellEditor(null) };
}
function disposeView(cell: { view: EditorView }): void {
cell.view.destroy();
cell.view.dom.remove();
}
describe("editor context keys with a focused notebook cell", () => {
it("keeps the keys on while a cell editor has focus, with no text editor open", () => {
const cell = focusedCell();
try {
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
expect(getContext().editorTextFocus).toBe(true);
// Republishing (tab churn, pane focus) must not drop the keys.
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
expect(getContext().editorTextFocus).toBe(true);
} finally {
cell.clear();
disposeView(cell);
}
focusedCell();
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
expect(getContext().editorTextFocus).toBe(true);
// Republishing (tab churn, pane focus) must not drop the keys.
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
expect(getContext().editorTextFocus).toBe(true);
});
it("lets a focused cell editor win over the mounted but unfocused text editor", async () => {
@@ -75,12 +73,10 @@ describe("editor context keys with a focused notebook cell", () => {
try {
const textView = slot.mount(host);
ctrl.onMounted(slot);
const cell = focusedCell();
focusedCell();
ctrl.publishContext();
expect(getContext().editorTextFocus).toBe(true);
expect(textView.hasFocus).toBe(false);
cell.clear();
disposeView(cell);
} finally {
host.remove();
}
@@ -88,16 +84,12 @@ describe("editor context keys with a focused notebook cell", () => {
it("drops the keys once no cell editor has focus", () => {
const cell = focusedCell();
try {
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
cell.clear();
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(false);
expect(getContext().editorTextFocus).toBe(false);
} finally {
disposeView(cell);
}
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
cell.clear();
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(false);
expect(getContext().editorTextFocus).toBe(false);
});
it("keeps a text tab's own keys when no cell editor is focused", async () => {
@@ -132,8 +124,6 @@ describe("editor actions in a focused notebook cell", () => {
await executeAction("editor.toggleColumnSelection");
expect(isColumnMode(cell.view.state)).toBe(true);
expect(isColumnMode(textView.state)).toBe(false);
cell.clear();
disposeView(cell);
} finally {
host.remove();
}
@@ -183,8 +173,6 @@ describe("editor actions in a focused notebook cell", () => {
} finally {
uninstall();
disposeStub();
cell.clear();
disposeView(cell);
}
});
});
@@ -211,13 +199,9 @@ describe("Copy Path with a notebook tab", () => {
},
},
}));
const cell = focusedCell();
try {
ctrl.publishContext();
expect(ctrl.activePath()).toBe("/p/a.ipynb");
expect(evaluateWhen("textEditorActive", getContext())).toBe(true);
} finally {
cell.clear();
}
focusedCell();
ctrl.publishContext();
expect(ctrl.activePath()).toBe("/p/a.ipynb");
expect(evaluateWhen("textEditorActive", getContext())).toBe(true);
});
});
+2
Переглянути файл
@@ -51,6 +51,7 @@ import {
implementationGutter,
pythonStubGutter,
registerNavigationActions,
springAopGutter,
springBeanGutter,
} from "@/editor/navigation";
import {
@@ -140,6 +141,7 @@ export function activate(): () => void {
registerEditorContribution({ id: "lsp.lineMarkers", order: 56, extensions: implementationGutter }),
registerEditorContribution({ id: "lsp.pythonStubs", order: 57, extensions: pythonStubGutter }),
registerEditorContribution({ id: "lsp.springBeans", order: 58, extensions: springBeanGutter }),
registerEditorContribution({ id: "lsp.springAop", order: 59, extensions: springAopGutter }),
// After the templates (order 90): live template / postfix expansion keeps ⇥ first.
registerEditorContribution({ id: "lsp.parameterTab", order: 95, extensions: () => parameterTabKeys }),
registerOverlay({ id: "editor-lsp.popups", component: LspPopups }),
+65
Переглянути файл
@@ -224,6 +224,71 @@ describe("parameter info replies", () => {
await vi.waitFor(() => expect(shown(a)).toBe("f"));
expect(shown(b)).toBe("g");
});
const escape = (view: EditorView) =>
view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
it("stays closed after Escape while the refresh for the last keystroke is pending", async () => {
lspSignatureHelp.mockResolvedValueOnce(named("f") as never);
const view = editor();
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(shown(view)).toBe("f"));
typeChar(view, ",");
escape(view);
expect(shown(view)).toBeNull();
await new Promise((r) => setTimeout(r, 300));
expect(shown(view)).toBeNull();
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(shown(view)).not.toBeNull());
});
it("stays closed after the editor loses focus while a refresh is pending", async () => {
lspSignatureHelp.mockResolvedValueOnce(named("f") as never);
const view = editor();
view.focus();
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(shown(view)).toBe("f"));
typeChar(view, ",");
view.contentDOM.blur();
await vi.waitFor(() => expect(shown(view)).toBeNull());
await new Promise((r) => setTimeout(r, 300));
expect(shown(view)).toBeNull();
});
it("doesn't open the auto-popup once the editor lost focus before it showed", async () => {
const view = editor("f", 1);
view.focus();
typeChar(view, "(");
view.contentDOM.blur();
await new Promise((r) => setTimeout(r, 1200));
expect(lspSignatureHelp).not.toHaveBeenCalled();
expect(shown(view)).toBeNull();
});
it("doesn't open parameter info after a completed call once Escape was pressed before the reply", async () => {
const inside = pending();
lspSignatureHelp.mockReturnValueOnce(inside.promise as never);
const view = editor();
const left = parameterInfoOrLeave(view, 2);
escape(view);
inside.resolve(named("f"));
await left;
expect(shown(view)).toBeNull();
expect(view.state.selection.main.head).toBe(2);
});
it("stays closed after Escape when an automatic reply was already on its way", async () => {
const late = pending();
lspSignatureHelp.mockResolvedValueOnce(named("f") as never).mockReturnValueOnce(late.promise as never);
const view = editor();
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(shown(view)).toBe("f"));
triggerSignatureHelp(view, false);
escape(view);
late.resolve(named("f2"));
await settle();
expect(shown(view)).toBeNull();
});
});
describe("C# parameter info", () => {
+23 -2
Переглянути файл
@@ -188,10 +188,13 @@ function signatureTooltip(s: SigState): Tooltip {
};
}
/** Per view: requests sent, and the tooltip value the newest shown reply set, with the document and caret it was asked at. */
/**
* Per view: requests sent, the newest request sent before the user closed the tooltip,
* and the tooltip value the newest shown reply set, with the document and caret it was asked at.
*/
const requests = new WeakMap<
EditorView,
{ sent: number; shown?: { id: number; value: SigState; doc: Text; head: number } }
{ sent: number; dismissed?: number; shown?: { id: number; value: SigState; doc: Text; head: number } }
>();
async function fetchSignature(view: EditorView, explicit: boolean) {
@@ -204,6 +207,8 @@ async function fetchSignature(view: EditorView, explicit: boolean) {
const head = state.selection.main.head;
// A late reply asked at another caret never overrides what a newer request still shows for this one.
const superseded = () => {
// The user closed the tooltip after this automatic request was sent: its reply must not reopen it.
if (!explicit && id <= (order.dismissed ?? 0)) return true;
const shown = order.shown;
return (
!!shown &&
@@ -244,12 +249,17 @@ async function fetchSignature(view: EditorView, explicit: boolean) {
export async function parameterInfoOrLeave(view: EditorView, inside: number) {
const doc = docOf(view);
const state = view.state;
// An automatic request: Escape or leaving the editor before the reply drops it.
let order = requests.get(view);
if (!order) requests.set(view, (order = { sent: 0 }));
const id = ++order.sent;
let help: SignatureHelp | null = null;
try {
if (doc) help = await lspRequest(() => commands.lspSignatureHelp(doc.doc, offsetToPos(state.doc, inside)));
} catch {
// No signature help: treated as nothing to fill in.
}
if (id <= (order.dismissed ?? 0)) return;
if (view.state.doc !== state.doc || view.state.selection.main.head !== inside) return;
if (help?.signatures.some((sig) => sig.parameters.length))
view.dispatch({ effects: setSignature.of({ pos: inside, help }) });
@@ -273,7 +283,16 @@ const signaturePlugin = ViewPlugin.fromClass(
clearTimeout(this.popupTimer);
this.popupTimer = setTimeout(() => void fetchSignature(this.view, false), Math.max(0, p.parameterInfoDelay));
}
/** The user closed the tooltip: automatic requests already scheduled or sent don't reopen it. */
dismiss() {
clearTimeout(this.popupTimer);
this.refresh.cancel();
const order = requests.get(this.view);
if (order) order.dismissed = order.sent;
}
update(u: ViewUpdate) {
// Leaving the editor closes the tooltip like Escape does (`focusChangeEffect` below), and nothing pending opens it.
if (u.focusChanged && !u.view.hasFocus) this.dismiss();
const active = u.state.field(signatureField, false);
let typedTrigger = false;
if (
@@ -409,6 +428,8 @@ export function signatureExtension(): Extension {
{
key: "Escape",
run: (view) => {
// Also before the popup shows: an automatic one on its way stays away, and Escape goes on.
view.plugin(signaturePlugin)?.dismiss();
if (!view.state.field(signatureField, false)) return false;
view.dispatch({ effects: setSignature.of(null) });
return true;
+1
Переглянути файл
@@ -348,5 +348,6 @@ export function registerNavigationActions(): () => void {
}
export { implementationGutter } from "./implementationGutter";
export { springAopGutter } from "./springAopGutter";
export { springBeanGutter } from "./springBeanGutter";
export { pythonStubGutter } from "./pythonStubs";
+235
Переглянути файл
@@ -0,0 +1,235 @@
/**
* Per-document gutter markers answered by one language-server request: Spring bean and Spring
* AOP navigation (`lspSpringBeanMarkers`, `lspSpringAopMarkers`). One cancellable request per
* document and 500 ms debounce; late answers are dropped. The markers follow their lines through
* edits, and are asked again when the server says they changed, when it settles, and when a
* source server stops or is removed. Library sources and documents without Gutter Icons ask
* nothing; a navigation the user waits for is served first.
*/
import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea";
import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/localAppearance";
import { isLibrarySource, shownAgain, type EditorDocContext } from "@/editor/api";
import { debounce, lspRequest } from "@/editor/lsp/lsp";
import { onLspRefresh, onServerSettled } from "@/editor/lsp/availability";
import { inForeground, onForeground } from "@/editor/lsp/foreground";
import {
commands,
isCancelled,
nextRequestId,
onIdeEvent,
type IdeError,
type LspRefreshKind,
type RequestId,
} from "@/platform/ipc";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
const DEBOUNCE_MS = 500;
export interface PlacedMarker<M> {
marker: M;
/** Start of the marker's line in the current state. */
pos: number;
}
export interface MarkerGutterOptions<M> {
/** Ask the server for this document's markers; `null` when no attached server provides them. */
request: (
request: RequestId,
doc: number,
) => Promise<{ status: "ok"; data: M[] | null } | { status: "error"; error: IdeError }>;
/** The refresh kind the server sends when these markers may have changed. */
refreshKind: LspRefreshKind;
/** Markers to show, left to right within a line. */
place: (doc: Text, markers: readonly M[]) => PlacedMarker<M>[];
/** The gutter icon (a button) for one placed marker. */
marker: (value: M) => GutterMarker;
/** Position in the shared icon area, after the inheritance icons (50). */
order: number;
}
interface LivePlugin {
readonly refreshKind: LspRefreshKind;
refreshSoon(): void;
yieldToNavigation(): void;
resumeAfterNavigation(): void;
}
const live = new Set<LivePlugin>();
const watchedKinds = new Set<LspRefreshKind>();
let watching = false;
function refreshAll(kind?: LspRefreshKind) {
for (const plugin of live) if (kind === undefined || plugin.refreshKind === kind) plugin.refreshSoon();
}
function watchChanges(kind: LspRefreshKind) {
if (!watchedKinds.has(kind)) {
watchedKinds.add(kind);
// The server's own "markers changed" (another file edited, a re-import).
onLspRefresh(kind, () => refreshAll(kind));
}
if (watching) return;
watching = true;
// Answers given while a server was importing may be incomplete.
onServerSettled(() => refreshAll());
// A stopped or removed source must not leave icons that navigate to old targets.
onIdeEvent("languageServer", (e) => {
if (e.status === "stopped" || e.status === "crashed") refreshAll();
});
onIdeEvent("languageServerRemoved", () => refreshAll());
// Requests the user waits for go first (Go to Declaration, a refactoring), as for the inheritance icons.
onForeground((foreground) => {
for (const plugin of live) {
if (foreground) plugin.yieldToNavigation();
else plugin.resumeAfterNavigation();
}
});
}
/** Gutter markers of `ctx`'s document, placed as `options` says and drawn by its `marker` factory. */
export function lspMarkerGutter<M>(ctx: EditorDocContext, options: MarkerGutterOptions<M>): Extension {
const setPlaced = StateEffect.define<PlacedMarker<M>[]>();
const field = StateField.define<PlacedMarker<M>[]>({
create: () => [],
update(value, tr) {
for (const e of tr.effects) if (e.is(setPlaced)) return e.value;
if (!tr.docChanged || !value.length) return value;
return value.map((p) => ({ ...p, pos: mapLineStart(tr, p.pos) }));
},
});
/** Marker sets by field value: the icon area asks on every view update (caret moves, scrolling). */
const markerSets = new WeakMap<readonly PlacedMarker<M>[], RangeSet<GutterMarker>>();
function placedSet(placed: readonly PlacedMarker<M>[]): RangeSet<GutterMarker> {
let set = markerSets.get(placed);
if (!set) {
set = RangeSet.of(
placed.map(({ marker, pos }) => options.marker(marker).range(pos)),
true,
);
markerSets.set(placed, set);
}
return set;
}
class MarkerPlugin implements LivePlugin {
readonly refreshKind = options.refreshKind;
private refresh = debounce(() => void this.run(), DEBOUNCE_MS);
private generation = 0;
private skipped = false;
private request: RequestId | null = null;
/** A pass was cancelled or held back by a navigation: run again once it is done. */
private yielded = false;
private offSettings: () => void;
constructor(private view: EditorView) {
live.add(this);
watchChanges(options.refreshKind);
this.refresh();
// Turning Gutter Icons back on asks again.
this.offSettings = useProject.subscribe((s, prev) => {
if (s.settings !== prev.settings) this.refresh();
});
}
/** The markers on screen may be stale: an answer already on its way is dropped. */
refreshSoon() {
this.generation++;
this.cancelRequest();
this.refresh();
}
yieldToNavigation() {
if (this.request === null) return;
this.generation++;
this.cancelRequest();
this.yielded = true;
}
resumeAfterNavigation() {
if (!this.yielded) return;
this.yielded = false;
this.refresh();
}
update(u: ViewUpdate) {
if (u.docChanged) {
this.generation++;
this.cancelRequest();
this.refresh();
} else if (this.skipped && shownAgain(u)) this.refresh();
// A local Gutter Icons override can turn the icons on.
else if (u.startState.field(localAppearanceField, false) !== u.state.field(localAppearanceField, false))
this.refresh();
}
private cancelRequest() {
if (this.request === null) return;
void commands.cancelRequest(this.request).catch(() => {});
this.request = null;
}
private show(placed: PlacedMarker<M>[]) {
const current = this.view.state.field(field);
if (current.length || placed.length) this.view.dispatch({ effects: setPlaced.of(placed) });
}
private async run() {
const view = this.view;
this.skipped = !view.dom.isConnected;
if (this.skipped) return;
if (inForeground()) {
this.yielded = true;
return;
}
const gen = ++this.generation;
this.cancelRequest();
// Checked on every pass, as Code Vision does: excluding or including a folder changes it.
if (isLibrarySource(ctx) || !gutterIconsOn(view.state, undefined, editorPrefs())) {
this.show([]);
return;
}
const text = view.state.doc;
const stale = () => gen !== this.generation || view.state.doc !== text;
const request = (this.request = nextRequestId());
try {
const markers = await lspRequest(
() => options.request(request, ctx.doc),
() => !stale(),
);
if (stale()) return;
this.show(options.place(text, markers ?? []));
} catch (e) {
if (stale()) return;
// A failed answer leaves no icon that could navigate to an old target.
this.show([]);
if (!isCancelled(e)) console.debug("[lspMarkers]", e);
} finally {
if (this.request === request) this.request = null;
}
}
destroy() {
this.refresh.cancel();
this.cancelRequest();
this.offSettings();
this.generation++;
live.delete(this);
}
}
return [
field,
ViewPlugin.define((view) => new MarkerPlugin(view)),
// In the shared icon area, beside the inheritance icons and the other language markers.
iconAreaSource.of({
order: options.order,
markers: (view) => (gutterIconsOn(view.state) ? placedSet(view.state.field(field)) : RangeSet.empty),
}),
];
}
+348
Переглянути файл
@@ -0,0 +1,348 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
const ipc = vi.hoisted(() => ({ lspSpringAopMarkers: vi.fn(), cancelRequest: vi.fn(async () => ({ status: "ok" })) }));
const nav = vi.hoisted(() => ({
navigateTo: vi.fn(),
openPopup: vi.fn(),
pinToFind: vi.fn((symbol: string) => ({ label: "Open in Find Tool Window", run: () => symbol })),
}));
const library = vi.hoisted(() => ({ excluded: false }));
const refresh = vi.hoisted(() => ({
listeners: [] as (() => void)[],
ide: [] as { event: string; fn: (e: { status?: string }) => void }[],
}));
vi.mock("@/platform/ipc", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/ipc")>()),
isTauri: () => true,
nextRequestId: () => 7,
onIdeEvent: (event: string, fn: (e: { status?: string }) => void) => {
refresh.ide.push({ event, fn });
return () => {};
},
commands: ipc,
}));
vi.mock("@/editor/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/editor/api")>()),
whenAllSynced: () => Promise.resolve(),
isLibrarySource: () => library.excluded,
}));
vi.mock("@/editor/lsp/availability", async (importOriginal) => ({
...(await importOriginal<typeof import("@/editor/lsp/availability")>()),
onLspRefresh: (_: string, fn: () => void) => refresh.listeners.push(fn),
onServerSettled: () => () => {},
}));
vi.mock("@/editor/lsp/navigation", async (importOriginal) => ({
...(await importOriginal<typeof import("@/editor/lsp/navigation")>()),
navigateTo: nav.navigateTo,
pinToFind: nav.pinToFind,
locationItems: async (locs: { name?: string; path: string }[]) =>
locs.map((l, i) => ({ id: `${i}`, label: l.name ?? l.path })),
}));
vi.mock("@/editor/lsp/popupStore", async (importOriginal) => ({
...(await importOriginal<typeof import("@/editor/lsp/popupStore")>()),
openPopup: nav.openPopup,
}));
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
import type { SpringAopMarker, SpringAopTarget } from "@/platform/ipc";
import { foregroundStarted } from "@/editor/lsp/foreground";
import { useI18n } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { aopTooltip, springAopGutter } from "./springAopGutter";
// An aspect with one advice, a service whose `place` has two advices (the toAdvice chooser) and
// whose `cancel` has one (a direct jump).
const SOURCE = [
"@Aspect", // 0
"class AuditAspect {", // 1
' @Before("execution(* Service.place(..))")', // 2
" void before() {}", // 3 advice, advises two methods
"}", // 4
"class Service {", // 5
" void place() {}", // 6 advised by two advices
" void cancel() {}", // 7 advised by one advice
"}", // 8
].join("\n");
const range = (line: number, col: number, len: number) => ({
start: { line, col },
end: { line, col: col + len },
});
const target = (
path: string,
line: number,
label: string,
adviceKind: SpringAopTarget["adviceKind"],
order: number | null,
): SpringAopTarget => ({ location: { path, range: range(line, 6, 4) }, label, adviceKind, order });
const marker = (
line: number,
col: number,
name: string,
direction: SpringAopMarker["direction"],
targets: SpringAopTarget[],
): SpringAopMarker => ({ range: range(line, col, name.length), name, direction, targets });
const BEFORE = target("/p/AuditAspect.java", 3, "before · AuditAspect.before()", "before", 1);
const AROUND = target("/p/TimingAspect.java", 4, "timed · TimingAspect.timed()", "around", null);
const AFTER = target("/p/NotificationAspect.java", 3, "sent · NotificationAspect.sent()", "after", 2);
const PLACE = target("/p/Service.java", 6, "place · Service.place()", null, null);
const CANCEL = target("/p/Service.java", 7, "cancel · Service.cancel()", null, null);
const MARKERS: SpringAopMarker[] = [
// Unsorted on purpose: the gutter orders icons by line.
marker(6, 7, "place", "toAdvice", [AROUND, BEFORE]),
marker(7, 7, "cancel", "toAdvice", [AFTER]),
marker(3, 7, "before", "toAdvised", [PLACE, CANCEL]),
// No target and a line past the end of the text: no icon.
marker(2, 20, "unmatched", "toAdvice", []),
marker(99, 0, "gone", "toAdvised", [PLACE]),
];
const answer = (markers: SpringAopMarker[] | null) => ({ status: "ok", data: markers });
describe("spring AOP gutter", () => {
let view: EditorView | null = null;
afterEach(() => {
view?.destroy();
view = null;
vi.clearAllMocks();
});
function open(language = "java", doc = 1) {
const ctx = { doc, path: "/p/AuditAspect.java", language, virtual: false } as Parameters<typeof springAopGutter>[0];
view = new EditorView({
state: EditorState.create({ doc: SOURCE, extensions: [springAopGutter(ctx), iconAreaExtension] }),
parent: document.body,
});
return view;
}
const buttons = () => [...view!.dom.querySelectorAll<HTMLButtonElement>("[data-spring-aop]")];
const button = (row: string) =>
buttons().find((b) =>
b.title
.split("\n")
.slice(1)
.some((r) => r.startsWith(row)),
)!;
it("puts an icon on each advised method and advice, in line order", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
open();
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
expect(ipc.lspSpringAopMarkers).toHaveBeenCalledExactlyOnceWith(7, 1);
expect(buttons().map((b) => b.dataset.springAop)).toEqual(["toAdvised", "toAdvice", "toAdvice"]);
expect(buttons().map((b) => b.title.split("\n")[0])).toEqual([
"Navigate to Advised Methods",
"Navigate to AOP Advices",
"Navigate to AOP Advices",
]);
});
it("navigates to a single advice or advised method directly", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
open();
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
fireEvent.click(button("sent · NotificationAspect.sent()"));
await vi.waitFor(() =>
expect(nav.navigateTo).toHaveBeenCalledWith({ ...AFTER.location, name: "sent · NotificationAspect.sent()" }),
);
// An advice with one advised method navigates there too.
ipc.lspSpringAopMarkers.mockResolvedValue(
answer([marker(3, 7, "cancel", "toAdvised", [CANCEL]), marker(7, 7, "cancel", "toAdvice", [AFTER])]),
);
refresh.listeners.forEach((l) => l());
await vi.waitFor(() => expect(buttons()).toHaveLength(2), { timeout: 2000 });
fireEvent.click(buttons()[0]!);
await vi.waitFor(() => expect(nav.navigateTo).toHaveBeenCalledTimes(2));
expect(nav.navigateTo.mock.calls[1]![0].path).toBe("/p/Service.java");
expect(nav.openPopup).not.toHaveBeenCalled();
});
it("opens the chooser with the exact titles, advice rows saying kind and order", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
open();
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
fireEvent.click(button("timed · TimingAspect.timed()"));
await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce());
const chooser = nav.openPopup.mock.calls[0]![0];
expect(chooser.title).toBe("Navigate to AOP Advices");
expect(chooser.items).toEqual([
{ id: "0", label: "timed · TimingAspect.timed()", detail: "Around advice" },
{ id: "1", label: "before · AuditAspect.before()", detail: "Before advice · order 1" },
]);
expect(nav.pinToFind).toHaveBeenCalledWith("place", expect.any(Array), undefined);
expect(nav.navigateTo).not.toHaveBeenCalled();
});
it("lists advised methods by their label only", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
open();
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
fireEvent.click(button("place · Service.place()"));
await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce());
const chooser = nav.openPopup.mock.calls[0]![0];
expect(chooser.title).toBe("Navigate to Advised Methods");
expect(chooser.items).toEqual([
{ id: "0", label: "place · Service.place()" },
{ id: "1", label: "cancel · Service.cancel()" },
]);
});
it("writes each tooltip row like the chooser, kind and order included", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
open();
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
expect(button("timed · TimingAspect.timed()").title).toBe(
"Navigate to AOP Advices\ntimed · TimingAspect.timed() — Around advice\nbefore · AuditAspect.before() — Before advice · order 1",
);
expect(button("sent · NotificationAspect.sent()").title).toBe(
"Navigate to AOP Advices\nsent · NotificationAspect.sent() — After advice · order 2",
);
expect(buttons()[0]!.title).toBe("Navigate to Advised Methods\nplace · Service.place()\ncancel · Service.cancel()");
// The accessible name is the tooltip, so the icon works from the keyboard.
expect(button("timed · TimingAspect.timed()").getAttribute("aria-label")).toBe(
button("timed · TimingAspect.timed()").title,
);
});
it("names advice kinds and orders in the current locale", async () => {
const texts = { "Before advice": "前置通知", "order {n}": "顺序 {n}" };
useI18n.setState({ locale: "zh", texts });
try {
ipc.lspSpringAopMarkers.mockResolvedValue(answer([MARKERS[0]!]));
open();
await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 });
expect(buttons()[0]!.title).toBe(
"Navigate to AOP Advices\ntimed · TimingAspect.timed() — Around advice\nbefore · AuditAspect.before() — 前置通知 · 顺序 1",
);
fireEvent.click(buttons()[0]!);
await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce());
expect(nav.openPopup.mock.calls[0]![0].items[1]).toEqual({
id: "1",
label: "before · AuditAspect.before()",
detail: "前置通知 · 顺序 1",
});
} finally {
useI18n.setState({ locale: "en", texts: {} });
}
});
it("keeps a late answer for older text from replacing the current one", async () => {
let first!: (v: unknown) => void;
ipc.lspSpringAopMarkers.mockReturnValueOnce(new Promise((r) => (first = r)));
open();
await vi.waitFor(() => expect(ipc.lspSpringAopMarkers).toHaveBeenCalledOnce(), { timeout: 2000 });
ipc.lspSpringAopMarkers.mockResolvedValue(answer([MARKERS[1]!]));
view!.dispatch({ changes: { from: 0, insert: " " } });
await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 });
first(answer(MARKERS));
await new Promise((r) => setTimeout(r, 50));
expect(buttons()).toHaveLength(1);
expect(ipc.cancelRequest).toHaveBeenCalled();
});
it("asks again when the server says the markers changed, clearing stale icons", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
open();
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
// The advice's pointcut was narrowed in another file.
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS.filter((m) => m.name !== "place")));
refresh.listeners.forEach((l) => l());
await vi.waitFor(() => expect(buttons()).toHaveLength(2), { timeout: 2000 });
// No source any more (another server took over): no icons.
ipc.lspSpringAopMarkers.mockResolvedValue(answer(null));
refresh.listeners.forEach((l) => l());
await vi.waitFor(() => expect(buttons()).toHaveLength(0), { timeout: 2000 });
});
it("drops an answer already on its way when the markers changed", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
open();
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
let late!: (v: unknown) => void;
ipc.lspSpringAopMarkers.mockReturnValueOnce(new Promise((r) => (late = r)));
refresh.listeners.forEach((l) => l());
await vi.waitFor(() => expect(ipc.lspSpringAopMarkers).toHaveBeenCalledTimes(2), { timeout: 2000 });
ipc.lspSpringAopMarkers.mockResolvedValue(answer([MARKERS[1]!]));
refresh.listeners.forEach((l) => l());
late(answer(MARKERS.slice(0, 2)));
await new Promise((r) => setTimeout(r, 50));
expect(buttons()).toHaveLength(3);
await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 });
});
it("asks again when the source server stops, clearing its icons", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
open();
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
ipc.lspSpringAopMarkers.mockResolvedValue(answer(null));
for (const { event, fn } of refresh.ide) if (event === "languageServer") fn({ status: "stopped" });
await vi.waitFor(() => expect(buttons()).toHaveLength(0), { timeout: 2000 });
});
it("asks nothing and shows nothing while Gutter Icons are off, then asks when turned on", async () => {
const settings = useProject.getState().settings;
const withIcons = (on: boolean) =>
useProject.setState({ settings: { ...(settings as object), editor: { showGutterIcons: on } } as never });
try {
withIcons(false);
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
open();
await new Promise((r) => setTimeout(r, 700));
expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled();
expect(buttons()).toHaveLength(0);
withIcons(true);
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
} finally {
useProject.setState({ settings });
}
});
it("asks nothing for a document in an excluded folder", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
library.excluded = true;
try {
open();
await new Promise((r) => setTimeout(r, 700));
expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled();
} finally {
library.excluded = false;
}
});
it("waits for a navigation the user started before asking", async () => {
ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS));
const done = foregroundStarted();
open();
await new Promise((r) => setTimeout(r, 700));
expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled();
done();
await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 });
});
it("registers nothing for other languages or virtual documents", async () => {
open("kotlin");
view!.destroy();
open("java", -1);
await new Promise((r) => setTimeout(r, 700));
expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled();
expect(buttons()).toHaveLength(0);
});
});
describe("aopTooltip", () => {
it("names each advice's kind and order, and each advised method by its label", () => {
expect(aopTooltip(MARKERS[2]!)).toBe(
"Navigate to Advised Methods\nplace · Service.place()\ncancel · Service.cancel()",
);
expect(aopTooltip(MARKERS[1]!)).toBe(
"Navigate to AOP Advices\nsent · NotificationAspect.sent() — After advice · order 2",
);
});
});
+116
Переглянути файл
@@ -0,0 +1,116 @@
/**
* Spring AOP gutter icons on Java documents: an advised method navigates to the advices applied
* to it, an advice method to the methods it advises. One cancellable request per document answers
* both directions (`lspSpringAopMarkers`); a server without them means no icons. Advice rows say
* their kind and, when statically known, their order.
*/
import type { Extension, Text } from "@codemirror/state";
import { GutterMarker } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { locationItems } from "@/editor/lsp/navigation";
import { commands, type SpringAopAdviceKind, type SpringAopMarker, type SpringAopTarget } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { gutterIconMarkup } from "@/ui";
import { openTargets } from "./implementationGutter";
import { lspMarkerGutter, type PlacedMarker } from "./lspMarkerGutter";
import styles from "./LineMarkers.module.css";
/** The advice kinds as the tooltip and chooser name them. */
const KIND_LABELS: Record<SpringAopAdviceKind, string> = {
before: "Before advice",
after: "After advice",
afterReturning: "After returning advice",
afterThrowing: "After throwing advice",
around: "Around advice",
};
/** Markers on lines of `doc`, left to right within a line. */
export function placeAopMarkers(doc: Text, markers: readonly SpringAopMarker[]): PlacedMarker<SpringAopMarker>[] {
return markers
.filter((m) => m.range.start.line < doc.lines && m.targets.length)
.sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col)
.map((marker) => ({ marker, pos: doc.line(marker.range.start.line + 1).from }));
}
/** An advice row's detail: its kind and, when known, the Spring order. */
export function adviceDetail(target: SpringAopTarget): string | null {
const parts: string[] = [];
if (target.adviceKind) parts.push(tx(KIND_LABELS[target.adviceKind]));
if (target.order !== null) parts.push(tx`order ${target.order}`);
return parts.length ? parts.join(" · ") : null;
}
/** Tooltip and accessible name: what clicking does, then each target, an advice with its kind and order. */
export function aopTooltip(marker: SpringAopMarker): string {
const head = marker.direction === "toAdvice" ? tx("Navigate to AOP Advices") : tx("Navigate to Advised Methods");
const rows = marker.targets.map((target) => {
if (marker.direction !== "toAdvice") return target.label;
const detail = adviceDetail(target);
return detail ? `${target.label} — ${detail}` : target.label;
});
return [head, ...rows].join("\n");
}
/** One target navigates; several open the chooser, advice rows saying their kind and order. */
export async function openAopTargets(marker: SpringAopMarker, anchor: { x: number; y: number }) {
const targets = marker.targets.map((t) => ({ ...t.location, name: t.label }));
const title = marker.direction === "toAdvice" ? tx("Navigate to AOP Advices") : tx("Navigate to Advised Methods");
await openTargets(targets, anchor, title, marker.name, async (locs) => {
const items = await locationItems(locs);
if (marker.direction !== "toAdvice") return items;
return items.map((item, i) => {
const detail = adviceDetail(marker.targets[i]!);
return detail ? { ...item, detail } : item;
});
});
}
class AopMarker extends GutterMarker {
readonly tooltip: string;
readonly icon: string;
constructor(readonly marker: SpringAopMarker) {
super();
this.tooltip = aopTooltip(marker);
this.icon = marker.direction === "toAdvice" ? "gutter-spring-aop-to-advice" : "gutter-spring-aop-to-advised";
}
// The DOM holds the marker it navigates with: other targets need a new button.
override eq(other: GutterMarker): boolean {
return other instanceof AopMarker && other.marker === this.marker;
}
override toDOM(): Node {
const button = document.createElement("button");
button.type = "button";
button.className = styles.stubMarker ?? "";
button.dataset.springAop = this.marker.direction;
button.title = this.tooltip;
button.setAttribute("aria-label", this.tooltip);
button.innerHTML = gutterIconMarkup(this.icon) ?? "";
// Keep the caret where it was; the click navigates, so the icon also works from the keyboard.
button.addEventListener("mousedown", (event) => {
event.preventDefault();
event.stopPropagation();
});
button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
const rect = button.getBoundingClientRect();
void openAopTargets(this.marker, { x: rect.left, y: rect.bottom + 2 });
});
return button;
}
}
/** Java source documents of the project; library classes and virtual documents have no aspects to find. */
export function springAopGutter(ctx: EditorDocContext): Extension {
if (ctx.doc < 0 || ctx.language !== "java") return [];
return lspMarkerGutter(ctx, {
request: (request, doc) => commands.lspSpringAopMarkers(request, doc),
refreshKind: "springAopMarkers",
place: placeAopMarkers,
marker: (marker) => new AopMarker(marker),
order: 52,
});
}
+13 -197
Переглянути файл
@@ -5,51 +5,19 @@
* server provides them, and none means no icons. Asked again after edits, when the server says
* the bean model changed (other files edited, a re-import) and when a server settles.
*/
import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea";
import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/localAppearance";
import { isLibrarySource, shownAgain, type EditorDocContext } from "@/editor/api";
import { debounce, lspRequest } from "@/editor/lsp/lsp";
import { onLspRefresh, onServerSettled } from "@/editor/lsp/availability";
import { inForeground, onForeground } from "@/editor/lsp/foreground";
import type { Extension, Text } from "@codemirror/state";
import { GutterMarker } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { locationItems } from "@/editor/lsp/navigation";
import {
commands,
isCancelled,
nextRequestId,
onIdeEvent,
type RequestId,
type SpringBeanMarker,
} from "@/platform/ipc";
import { commands, type SpringBeanMarker } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { gutterIconMarkup } from "@/ui";
import { openTargets } from "./implementationGutter";
import { lspMarkerGutter, type PlacedMarker } from "./lspMarkerGutter";
import styles from "./LineMarkers.module.css";
const DEBOUNCE_MS = 500;
interface PlacedBean {
marker: SpringBeanMarker;
/** Start of the marker's line in the current state. */
pos: number;
}
const setBeans = StateEffect.define<PlacedBean[]>();
const beansField = StateField.define<PlacedBean[]>({
create: () => [],
update(value, tr) {
for (const e of tr.effects) if (e.is(setBeans)) return e.value;
if (!tr.docChanged || !value.length) return value;
return value.map((b) => ({ ...b, pos: mapLineStart(tr, b.pos) }));
},
});
/** Markers on lines of `doc`, left to right within a line. */
export function placeBeans(doc: Text, markers: readonly SpringBeanMarker[]): PlacedBean[] {
export function placeBeans(doc: Text, markers: readonly SpringBeanMarker[]): PlacedMarker<SpringBeanMarker>[] {
return markers
.filter((m) => m.range.start.line < doc.lines && m.targets.length)
.sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col)
@@ -130,166 +98,14 @@ class BeanMarker extends GutterMarker {
}
}
/** Marker sets by field value: the icon area asks on every view update (caret moves, scrolling). */
const markerSets = new WeakMap<readonly PlacedBean[], RangeSet<BeanMarker>>();
function beanSet(placed: readonly PlacedBean[]): RangeSet<BeanMarker> {
let set = markerSets.get(placed);
if (!set) {
set = RangeSet.of(
placed.map(({ marker, pos }) => new BeanMarker(marker).range(pos)),
true,
);
markerSets.set(placed, set);
}
return set;
}
const live = new Set<BeansPlugin>();
let watching = false;
function watchChanges() {
if (watching) return;
watching = true;
const refreshAll = () => {
for (const plugin of live) plugin.refreshSoon();
};
// The server's own "markers changed" (another file edited, a re-import), or it (re)started.
onLspRefresh("springBeanMarkers", refreshAll);
// Answers given while a server was importing may be incomplete.
onServerSettled(refreshAll);
// A stopped or removed source must not leave icons that navigate to old targets.
onIdeEvent("languageServer", (e) => {
if (e.status === "stopped" || e.status === "crashed") refreshAll();
});
onIdeEvent("languageServerRemoved", refreshAll);
// Requests the user waits for go first (Go to Declaration, a refactoring), as for the inheritance icons.
onForeground((foreground) => {
for (const plugin of live) {
if (foreground) plugin.yieldToNavigation();
else plugin.resumeAfterNavigation();
}
});
}
class BeansPlugin {
private refresh = debounce(() => void this.run(), DEBOUNCE_MS);
private generation = 0;
private skipped = false;
private request: RequestId | null = null;
/** A pass was cancelled or held back by a navigation: run again once it is done. */
private yielded = false;
private offSettings: () => void;
constructor(
private view: EditorView,
private ctx: EditorDocContext,
) {
live.add(this);
watchChanges();
this.refresh();
// Turning Gutter Icons back on asks again.
this.offSettings = useProject.subscribe((s, prev) => {
if (s.settings !== prev.settings) this.refresh();
});
}
/** The markers on screen may be stale: an answer already on its way is dropped. */
refreshSoon() {
this.generation++;
this.cancelRequest();
this.refresh();
}
yieldToNavigation() {
if (this.request === null) return;
this.generation++;
this.cancelRequest();
this.yielded = true;
}
resumeAfterNavigation() {
if (!this.yielded) return;
this.yielded = false;
this.refresh();
}
update(u: ViewUpdate) {
if (u.docChanged) {
this.generation++;
this.cancelRequest();
this.refresh();
} else if (this.skipped && shownAgain(u)) this.refresh();
// A local Gutter Icons override can turn the icons on.
else if (u.startState.field(localAppearanceField, false) !== u.state.field(localAppearanceField, false))
this.refresh();
}
private cancelRequest() {
if (this.request === null) return;
void commands.cancelRequest(this.request).catch(() => {});
this.request = null;
}
private show(placed: PlacedBean[]) {
const current = this.view.state.field(beansField);
if (current.length || placed.length) this.view.dispatch({ effects: setBeans.of(placed) });
}
private async run() {
const view = this.view;
this.skipped = !view.dom.isConnected;
if (this.skipped) return;
if (inForeground()) {
this.yielded = true;
return;
}
const gen = ++this.generation;
this.cancelRequest();
// Checked on every pass, as Code Vision does: excluding or including a folder changes it.
if (isLibrarySource(this.ctx) || !gutterIconsOn(view.state, undefined, editorPrefs())) {
this.show([]);
return;
}
const text = view.state.doc;
const stale = () => gen !== this.generation || view.state.doc !== text;
const request = (this.request = nextRequestId());
try {
const markers = await lspRequest(
() => commands.lspSpringBeanMarkers(request, this.ctx.doc),
() => !stale(),
);
if (stale()) return;
this.show(placeBeans(text, markers ?? []));
} catch (e) {
if (stale()) return;
// A failed answer leaves no icon that could navigate to an old target.
this.show([]);
if (!isCancelled(e)) console.debug("[springBeans]", e);
} finally {
if (this.request === request) this.request = null;
}
}
destroy() {
this.refresh.cancel();
this.cancelRequest();
this.offSettings();
this.generation++;
live.delete(this);
}
}
/** Java source documents of the project; library classes and virtual documents have no beans to find. */
export function springBeanGutter(ctx: EditorDocContext): Extension {
if (ctx.doc < 0 || ctx.language !== "java") return [];
return [
beansField,
ViewPlugin.define((view) => new BeansPlugin(view, ctx)),
// After the inheritance icons (order 50), in the shared icon area.
iconAreaSource.of({
order: 51,
markers: (view) => (gutterIconsOn(view.state) ? beanSet(view.state.field(beansField)) : RangeSet.empty),
}),
];
return lspMarkerGutter(ctx, {
request: (request, doc) => commands.lspSpringBeanMarkers(request, doc),
refreshKind: "springBeanMarkers",
place: placeBeans,
marker: (marker) => new BeanMarker(marker),
order: 51,
});
}
+6 -1
Переглянути файл
@@ -101,6 +101,7 @@ const SAMPLE_CATALOG: AgentPluginCatalog = {
commandCount: 0,
hookFiles: ["hooks/hooks.json"],
stdioCommands: ["azure: npx -y @azure/mcp server start"],
lspCommands: ["go: gopls serve"],
capabilityHash: "abc123",
requiresConsent: true,
},
@@ -297,6 +298,8 @@ describe("AgentPluginsPage", () => {
fireEvent.click(await screen.findByRole("button", { name: "Review & Enable…" }));
const dialog = await screen.findByRole("dialog", { name: /Approve Plugin Capabilities/ });
expect(within(dialog).getByText("azure: npx -y @azure/mcp server start")).toBeInTheDocument();
expect(within(dialog).getByText("Language Server Process")).toBeInTheDocument();
expect(within(dialog).getByText("go: gopls serve")).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Trust & Enable Plugin" }));
await waitFor(() =>
@@ -347,7 +350,9 @@ describe("AgentPluginsPage", () => {
const install = within(installDlg).getByRole("button", { name: "Trust & Install Plugin" });
expect(install).toBeDisabled();
fireEvent.click(within(installDlg).getByLabelText("Approve bundled MCP server and lifecycle hook execution"));
fireEvent.click(
within(installDlg).getByLabelText("Approve bundled MCP server, language server and lifecycle hook execution"),
);
fireEvent.click(within(installDlg).getByLabelText("Confirm static security scan warnings"));
expect(install).toBeDisabled();
fireEvent.click(within(installDlg).getByLabelText("Replace the existing plugin directory"));
+18 -3
Переглянути файл
@@ -1022,8 +1022,8 @@ function CapabilityConsentDialog({
<div className={styles.dialogBody}>
<span className={styles.hint}>
<T>
This agent plugin declares local MCP processes or lifecycle hooks that execute commands when active. Review
its capabilities before enabling:
This agent plugin declares local MCP processes, language servers or lifecycle hooks that execute commands
when active. Review its capabilities before enabling:
</T>
</span>
@@ -1038,6 +1038,16 @@ function CapabilityConsentDialog({
<div className={styles.codeLine}>{cmd}</div>
</div>
))}
{(cap.lspCommands ?? []).map((cmd) => (
<div key={`lsp:${cmd}`}>
<div>
<strong>
<T>Language Server Process</T>
</strong>
</div>
<div className={styles.codeLine}>{cmd}</div>
</div>
))}
{(cap.hookFiles ?? []).map((hf) => (
<div key={hf}>
<div>
@@ -1564,6 +1574,11 @@ function InstallPluginDialog({
MCP: {cmd}
</div>
))}
{(preview.capabilities.lspCommands ?? []).map((cmd) => (
<div key={`lsp:${cmd}`} className={styles.codeLine}>
LSP: {cmd}
</div>
))}
{(preview.capabilities.hookFiles ?? []).map((hf) => (
<div key={hf} className={styles.codeLine}>
Hook: {hf}
@@ -1580,7 +1595,7 @@ function InstallPluginDialog({
<Checkbox
checked={approveCaps}
onChange={setApproveCaps}
label={tx("Approve bundled MCP server and lifecycle hook execution")}
label={tx("Approve bundled MCP server, language server and lifecycle hook execution")}
/>
)}
{hasScanWarnings && (
+10
Переглянути файл
@@ -160,6 +160,16 @@ const paths = [
{ name: "new task", key: HOME, send: () => startTask(), mock: backend.create },
];
describe("new task agent", () => {
it("starts with the agent the composer shows when the draft names a removed agent", async () => {
updateDraft({ provider: "removed-agent" });
updateComposer(HOME, { ...emptyDraft(), text: "hello" });
backend.create.mockResolvedValueOnce(ok(task("created")));
await startTask();
expect(backend.create).toHaveBeenCalledWith(expect.objectContaining({ provider: "codex" }));
});
});
describe.each(paths)("$name acknowledgement", (path) => {
function begin() {
const response = deferred();
+9 -12
Переглянути файл
@@ -483,11 +483,8 @@ export function draftModelSettings(
}
export function setDraftOption(id: string, value: string) {
const { draft, providers } = useAgents.getState();
const config = draftConfig(
providers.find((p) => p.id === draft.provider),
draft,
);
const { draft } = useAgents.getState();
const config = draftConfig(selectedProvider(), draft);
const model = config.find((o) => o.category === "model")?.current;
const target = config.find((o) => o.id === id);
if (model && target && isPerModelOption(target)) {
@@ -1601,15 +1598,15 @@ export async function startTask(
projectRoot: string | null = null,
worktreePath?: string | null,
): Promise<void> {
const { draft, providers } = useAgents.getState();
const { draft } = useAgents.getState();
const composer = composerDraft(HOME);
if (!canSend(composer)) return;
const started = generation;
const command = shellCommand(composer);
const options = draftConfig(
providers.find((p) => p.id === draft.provider),
draft,
);
// The agent the composer shows: a draft naming a removed agent falls back to the first one.
const provider = selectedProvider();
const providerId = provider?.id ?? draft.provider;
const options = draftConfig(provider, draft);
if (
options.some(
(o) =>
@@ -1620,7 +1617,7 @@ export async function startTask(
)
return;
const model = options.find((o) => o.category === "model")?.current;
const defaults = providerDefaults(draft.provider);
const defaults = providerDefaults(providerId);
const config = options.flatMap((o) => {
// An untouched Codex tier inherits the runtime's default; explicit Off must still be sent.
const value =
@@ -1636,7 +1633,7 @@ export async function startTask(
commands.agentCreate({
projectRoot,
prompt: promptOf(HOME, composer),
provider: draft.provider,
provider: providerId,
config,
isolation,
base: isolation === "worktree" && !reusedWorktree ? draft.base : null,
+8 -4
Переглянути файл
@@ -351,7 +351,11 @@ export function NewProjectDialog({
const [edited, setEdited] = useState<Record<string, Values>>({});
const [dynamic, setDynamic] = useState<{ id: string; key: string; fields: Field[] } | null>(null);
const [dynamicError, setDynamicError] = useState<string | null>(null);
const [requirements, setRequirements] = useState<Requirement[]>([]);
// Tagged with their generator, so another generator's warnings don't linger until its own check returns.
const [requirements, setRequirements] = useState<{ generator: string; list: Requirement[] }>({
generator: "",
list: [],
});
/** Installed SDKs by kind, once detected. */
const [sdks, setSdks] = useState<Partial<Record<string, Sdk[]>>>({});
const detecting = useRef(new Set<string>());
@@ -427,8 +431,8 @@ export function NewProjectDialog({
let live = true;
const timer = setTimeout(() => {
call(commands.scaffoldRequirements(generator.id, JSON.parse(valuesKey) as Values))
.then((r) => live && setRequirements(r))
.catch(() => live && setRequirements([]));
.then((list) => live && setRequirements({ generator: generator.id, list }))
.catch(() => live && setRequirements({ generator: generator.id, list: [] }));
}, 300);
return () => {
live = false;
@@ -492,7 +496,7 @@ export function NewProjectDialog({
}, [path]);
const visibleFields = fields.filter((f) => isVisible(f, values));
const invalidField = visibleFields.find((f) => fieldError(f, values[f.id] ?? ""));
const missing = requirements.filter((r) => !r.satisfied);
const missing = requirements.generator === generator?.id ? requirements.list.filter((r) => !r.satisfied) : [];
const loadingDynamic = !!generator?.dynamic && !dynamicFields.length && !dynamicError;
const invalid =
!generator || !!nameError || !location.trim() || !!invalidField || missing.length > 0 || loadingDynamic;
+20 -1
Переглянути файл
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
detect: vi.fn(),
tauri: false,
xcodeIcon: vi.fn(),
requirements: vi.fn(),
}));
const empty: GeneratorInfo = {
id: "empty",
@@ -93,7 +94,7 @@ vi.mock("@/platform/ipc", async (original) => {
...actual.commands,
scaffoldCatalog: () => Promise.resolve([empty, dotnet, appleApp, appleFramework]),
sdkDetect: mocks.detect,
scaffoldRequirements: () => Promise.resolve({ status: "ok", data: [] }),
scaffoldRequirements: mocks.requirements,
scaffoldFreeName: mocks.freeName,
scaffoldTargetTaken: mocks.taken,
scaffoldCreate: mocks.create,
@@ -107,6 +108,9 @@ vi.mock("../windows", async (original) => ({
}));
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
beforeEach(() => {
mocks.requirements.mockImplementation(() => ok([]));
});
const nameInput = () => screen.getByLabelText("Name:");
const createButton = () => screen.getByRole("button", { name: "Create" });
@@ -124,6 +128,21 @@ describe("File › New Project… name and location", () => {
localStorage.clear();
});
it("drops the previous generator's missing-tool warning as soon as another generator is chosen", async () => {
let pending = false;
mocks.requirements.mockImplementation((id: string) => {
if (id !== "dotnet") return pending ? new Promise(() => {}) : ok([]);
return ok([{ program: "dotnet", min: null, found: null, satisfied: false, hint: "" }]);
});
render(<NewProjectOverlay />);
act(() => showNewProject());
fireEvent.click(await screen.findByRole("option", { name: ".NET" }));
expect(await screen.findByText(/dotnet is not installed/)).toBeInTheDocument();
pending = true;
fireEvent.click(screen.getByRole("option", { name: "Empty Project" }));
expect(screen.queryByText(/dotnet is not installed/)).toBeNull();
});
it("starts where the last project was created, named after the first free untitled folder", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
+44 -20
Переглянути файл
@@ -8,18 +8,20 @@ import styles from "./UsageAccessFilter.module.css";
export interface UsageAccessOptions {
read: boolean;
write: boolean;
imports: boolean;
}
const STORAGE_KEY = "openidea.usages.accessFilter.v1";
const ALL: UsageAccessOptions = { read: true, write: true, imports: true };
export function loadAccessOptions(): UsageAccessOptions {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "null") as UsageAccessOptions | null;
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "null") as Partial<UsageAccessOptions> | null;
if (saved && typeof saved.read === "boolean" && typeof saved.write === "boolean" && (saved.read || saved.write))
return saved;
return { read: saved.read, write: saved.write, imports: saved.imports !== false };
} catch {
/* unavailable or invalid storage: show everything */
}
return { read: true, write: true };
return ALL;
}
export const useUsageAccessOptions = create<UsageAccessOptions>(() => loadAccessOptions());
@@ -36,8 +38,13 @@ export function toggleUsageAccess(which: keyof UsageAccessOptions) {
}
}
/** A usage on a line that begins an import statement (`import a.b.C;`, `from a import C`). */
const IMPORT_LINE = /^\s*(?:import(?![\w$])|from\b.*\bimport\b)/;
export const isImportStatement = (u: Usage) => IMPORT_LINE.test(u.text);
export function filterUsageAccess(items: readonly Usage[], options: UsageAccessOptions): Usage[] {
return items.filter((u) => {
if (isImportStatement(u) && !options.imports) return false;
// Old categories and ordinary LSP locations are unclassified. Never infer
// access from an accessor name/category or silently hide unknown entries.
if (!u.access || u.access === "unknown" || u.access === "readWrite") return true;
@@ -46,33 +53,50 @@ export function filterUsageAccess(items: readonly Usage[], options: UsageAccessO
}
export const supportsUsageAccess = (items: readonly Usage[]) => items.some((u) => u.access && u.access !== "unknown");
export const hasImportStatements = (items: readonly Usage[]) => items.some(isImportStatement);
export function UsageAccessFilter({ items, vertical }: { items: readonly Usage[]; vertical?: boolean }) {
const tx = useTx();
const options = useUsageAccessOptions();
if (!supportsUsageAccess(items)) return null;
const access = supportsUsageAccess(items);
const imports = hasImportStatements(items);
if (!access && !imports) return null;
return (
<div
className={clsx(styles.toolbar, vertical && styles.vertical)}
role={vertical ? "group" : "toolbar"}
aria-label={tx("Usage access filters")}
>
<IconButton
icon="show-read-access"
size="small"
iconSize={16}
title="Show read accesses"
pressed={options.read}
onClick={() => toggleUsageAccess("read")}
/>
<IconButton
icon="show-write-access"
size="small"
iconSize={16}
title="Show write accesses"
pressed={options.write}
onClick={() => toggleUsageAccess("write")}
/>
{access && (
<>
<IconButton
icon="show-read-access"
size="small"
iconSize={16}
title="Show read accesses"
pressed={options.read}
onClick={() => toggleUsageAccess("read")}
/>
<IconButton
icon="show-write-access"
size="small"
iconSize={16}
title="Show write accesses"
pressed={options.write}
onClick={() => toggleUsageAccess("write")}
/>
</>
)}
{imports && (
<IconButton
icon="show-import-statements"
size="small"
iconSize={16}
title="Show import statements"
pressed={options.imports}
onClick={() => toggleUsageAccess("imports")}
/>
)}
</div>
);
}
-14
Переглянути файл
@@ -58,20 +58,6 @@
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.link {
max-width: 100%;
border: none;
background: none;
padding: 0;
font: inherit;
color: var(--link);
text-align: left;
cursor: pointer;
}
.link:hover {
color: var(--link-hover);
text-decoration: underline;
}
.body {
flex: 1 1 0;
display: flex;
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff. Show more