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

...
Автор SHA1 Повідомлення Дата
l0ng-ai b81ff473e0 fix(terminal): remove redundant scroll-to-end button 2026-11-06 22:48:28 +08:00
Arnaud Ritti 4f65f030ce feat(plugins): right-click menu on the items of plugin tree and list views (#1746)
A plugin can declare `[[contributes.menus]]` with `menu = "viewItem.context"` and `view = "<its view>"`. Right-clicking an item of that tree or list view lists the matching commands, each run with the item's key as argument; `when` sees `viewItem` (the key) and `viewItemKind` (the key up to its first `:`). Validation refuses the menu without `view`, with an undeclared or web view, `view` on another menu, and (new in API 1.2) a manifest whose engines.openidea still admits older IDEs.

Closes #1618

Co-authored-by: arnaud-ritti <[email protected]>
2026-11-06 22:47:40 +08:00
Arnaud Ritti e65825e661 feat(plugins): let a plugin set its own icon (#1761)
A plugin can set `icon` (and `icon-dark`) in plugin.toml. The SVGs go through the existing sanitiser (16 KiB each), ship with the package, and show in Settings › Plugins (list rows and detail header) and the marketplace, whose index entries carry them; the IDE sanitises index icons again and drops unsafe ones.

IDEs before plugin API 1.2 refuse a manifest with `icon`, so Manifest::needs_api refuses one whose engines.openidea still admits them (check and install), keeping the index from offering such a package to older IDEs.

Closes #1732

Co-authored-by: arnaud-ritti <[email protected]>
2026-11-06 22:45:42 +08:00
Lee Dong Geon 2dc59ef2e2 fix(i18n): fill in the Korean catalogs and align terms with IntelliJ and Microsoft (#1647)
452 strings had no Korean entry and showed in English, and some existing Korean text was literal or inconsistent between menus and elsewhere. Fill in the missing entries in locales/ko.json and locales/text/ko.json, and use Microsoft's Korean terms for general UI and IntelliJ's for development terms.

Closes #1646

Co-authored-by: ldg030201 <[email protected]>
2026-11-06 22:35:33 +08:00
arookieofc ee84185b91 feat(database): One-Row extractor, and ⌘C copies in the chosen extractor's format (#1842)
The grid's context menu gets Copy as ▸ TSV / CSV / One-Row, and the
toolbar extractor drop-down gains One-Row: every selected value on one
", "-separated line — numbers bare, strings single-quoted with '
doubled, NULL for nulls — for pasting into IN (…) lists.

The toolbar extractor also decides what plain ⌘C copies, for CSV and
One-Row (JSON / SQL Inserts / Markdown stay TSV, keeping ⌘C
cell-shaped). TSV remains the default.

Fixes #1835
2026-11-06 22:29:18 +08:00
arookieofc 58f567c954 fix(spelling): merge the two dictionary saves into one row (#1833)
A typo listed "Save to project-level dictionary" and "Save to
application-level dictionary" as two rows, each with the same →
submenu of both again — four ways to trigger two actions. The popup
now shows one "Save 'word' to dictionary" row that saves to the
project dictionary (application-level without a project); its →
submenu still offers each level, then the inspection controls.

Fixes #1832
2026-11-06 22:10:48 +08:00
arookieofc 798da979a1 test(smoke): retry the temp-directory cleanup on ENOTEMPTY (#1838)
Language servers and debug adapters still write into the fixture's
temp dir as the test's afterEach tears it down, so a bare rmSync raced
them and failed the suite on ENOTEMPTY (Language smoke kotlin, java).
Give the removal maxRetries + retryDelay so a few late writes can't
flake the job.
2026-11-06 22:10:30 +08:00
arookieofc b54a745d6d feat(trust): let users add trusted folders from settings (#1812)
* feat(trust): let users add trusted folders from settings

The trusted-locations check already matches projects by path prefix, but
the only way to populate it was the "Trust projects in…" checkbox on the
first-open dialog — a folder could never be trusted ahead of time.

Add a project_trust_add_location command that canonicalizes the picked
directory, rejects non-directories, and deduplicates, plus an "Add
folder…" button on the Project Trust settings page backed by the native
directory picker.

Fixes #1743

* fix(trust): translate the trusted-location additions into Chinese

The zh source-text catalog must cover every literal UI text; the three
new strings in the trusted-locations settings page were missing.
2026-11-06 22:08:10 +08:00
arookieofc 954ad354a1 fix(java): pass the configured Maven local repository to jdtls (#1813)
m2e resolves and downloads into maven.repo.local, which neither the
userSettings init option nor MAVEN_OPTS covers. Without it the embedded
Maven fell back to ~/.m2 even when every mvn run the IDE launches used
the configured repository, splitting the cache across two locations.

A -Dmaven.repo.local in the user's own jdtls VM options wins.

Fixes #1739
2026-11-06 22:01:53 +08:00
arookieofc 8e5507b9f2 fix(vfs): hint at inotify limits when the file watcher hits them (#793)
On Linux a watcher creation can fail with a bare OS error when the
kernel's inotify limits are exhausted: one instance per watcher
(EMFILE, os error 24) or one watch per directory (ENOSPC, mapped by
notify to MaxFilesWatch). Name the sysctl knob to raise in the error
message instead of leaving users to search engines (issue #788).
2026-11-06 21:59:03 +08:00
arookieofc a3ca40ccf4 fix(project-tree): reveal WSL paths through the wsl.localhost share (#1806)
* fix(project-tree): reveal WSL paths through the wsl.localhost share

"Reveal in Explorer" in a WSL project passed the distro-internal
/home/... path to revealItemInDir, which read it as a local path and
reported it missing. Translate to the \\wsl.localhost\<distro>\...
UNC share before revealing.

* fix(project-tree): match reveal failure title to the local file manager
2026-11-06 21:52:34 +08:00
arookieofc b6dfde07bf fix(go): sweep Delve's leftover __debug_bin files when a session ends (#1829)
Delve compiles the debuggee to __debug_bin in the session's cwd (on
Windows __debug_bin.exe plus __debug_bin.exe<digits> in DAP mode) and
removes it on a graceful exit. When shutdown doesn't reach that cleanup
the binaries pile up in the project directory.

After the session is down — the adapter disconnected and its process
reaped — remove the leftover files matching Delve's own names from the
session's cwd. Only a locally started adapter (no debugServer) is swept:
a remote Delve's cwd may be on another machine. Files that merely share
the prefix (__debug_bin.go sources, in-progress names with other
suffixes, directories) are left alone.

Fixes #1790
2026-11-06 21:52:15 +08:00
arookieofc 576e55cbe1 fix(vfs): tolerate fsync ENOTTY/EINVAL on filesystems without fsync (#1804)
* fix(vfs): tolerate fsync ENOTTY/EINVAL on filesystems without fsync

virtio-fs (macOS VMs) answers fsync/F_FULLFSYNC with "Inappropriate
ioctl for device" (os error 25), failing the whole atomic write. The
write itself already went through, so degrade like SQLite: log and
continue to the rename instead of propagating.

* fix(vcs): tolerate filesystems without fsync when updating ignore files
2026-11-06 21:48:14 +08:00
l0ng-ai a6d17543fd feat(usages): search Java usages in Project Files first, Project and Libraries on demand (#1837) 2026-11-06 21:46:29 +08:00
arookieofc ef95cd1716 fix(editor): paste one line per caret when the counts match (#1830)
* fix(editor): paste one line per caret when the counts match

Multi-caret paste inserted the whole clipboard at every caret: seven
carets and a six-line clipboard produced six full copies inside the
first pair of quotes and left the rest untouched.

When the clipboard has exactly one line per caret, each caret now gets
its own line — the JetBrains behavior the issue expects. Any other
count still pastes the full text at every caret. Shared by all three
paste entry points (normal, plain text, history) through dispatchPaste.

Fixes #1828

* test(editor): cover trailing-newline paste at seven carets
2026-11-06 21:40:08 +08:00
arookieofc e2d82e2ec8 fix(http): join multipart request bodies with CRLF (#1802)
* fix(http): join multipart request bodies with CRLF

Multipart parts are delimited by CRLF per RFC 2046; prepare() joined
body lines with LF, so strict servers (Tomcat) never found the boundary
and rejected the request as 413. Join with CRLF when the request's
Content-Type is multipart/*; other bodies keep LF.

Fixes #1700

* ci: retrigger after flaky mybatis test on windows

* ci: retrigger after flaky java debug smoke
2026-11-06 20:55:17 +08:00
arookieofc 796f3f1512 fix(run): run Gradle module tests from the build root (#1805) (#1820) 2026-11-06 20:51:06 +08:00
arookieofc 47db04a3aa feat(debugger): flash the taskbar when a breakpoint hits unfocused (#1803) (#1819) 2026-11-06 20:50:59 +08:00
arookieofc 73322b04a6 fix(mybatis): skip annotation arguments when parsing mapper method names (#1799) (#1818) 2026-11-06 20:50:54 +08:00
arookieofc 9d75f27a1c fix(tabs): keep close button visible in squeezed tab strip (#1798) (#1817) 2026-11-06 20:50:43 +08:00
arookieofc 84e1863ebf fix(menu): show tooltip for truncated labels (#1797) (#1816) 2026-11-06 20:50:38 +08:00
arookieofc a80ed81ca8 fix(editor): use search-match foreground color on find highlights (#1796) (#1815) 2026-11-06 20:50:33 +08:00
arookieofc b5ab3eed1f Revert merge-commit landings of #1796 #1797 #1798 #1799 #1803 #1805 (#1814)
* Revert "Merge pull request #1805 from a-rookie-of-C-language/fix/gradle-all-tests-cwd"

This reverts commit 37975fd71a, reversing
changes made to 2028772ab2.

* Revert "Merge pull request #1803 from a-rookie-of-C-language/feat/flash-taskbar-on-breakpoint"

This reverts commit 2028772ab2, reversing
changes made to 5b53b579d9.

* Revert "Merge pull request #1799 from a-rookie-of-C-language/fix/mybatis-annotation-method-name"

This reverts commit 5b53b579d9, reversing
changes made to 9db90c7141.

* Revert "Merge pull request #1798 from a-rookie-of-C-language/fix/squeezed-tab-close-button"

This reverts commit 9db90c7141, reversing
changes made to 3bb58ff542.

* Revert "Merge pull request #1797 from a-rookie-of-C-language/fix/open-recent-path-tooltip"

This reverts commit 3bb58ff542, reversing
changes made to f0ad100a25.

* Revert "Merge pull request #1796 from a-rookie-of-C-language/fix/find-match-fg-color"

This reverts commit f0ad100a25, reversing
changes made to fca9d1e08f.
2026-11-06 20:47:22 +08:00
arookieofc 37975fd71a Merge pull request #1805 from a-rookie-of-C-language/fix/gradle-all-tests-cwd
fix(run): run Gradle module tests from the build root
2026-11-06 20:32:06 +08:00
arookieofc 2028772ab2 Merge pull request #1803 from a-rookie-of-C-language/feat/flash-taskbar-on-breakpoint
feat(debugger): flash the taskbar when a breakpoint hits unfocused
2026-11-06 20:32:01 +08:00
arookieofc 5b53b579d9 Merge pull request #1799 from a-rookie-of-C-language/fix/mybatis-annotation-method-name
fix(mybatis): skip annotation arguments when parsing mapper method names
2026-11-06 20:31:56 +08:00
arookieofc 9db90c7141 Merge pull request #1798 from a-rookie-of-C-language/fix/squeezed-tab-close-button
fix(tabs): keep close button visible in squeezed tab strip
2026-11-06 20:31:51 +08:00
arookieofc 3bb58ff542 Merge pull request #1797 from a-rookie-of-C-language/fix/open-recent-path-tooltip
fix(menu): show tooltip for truncated labels
2026-11-06 20:31:45 +08:00
arookieofc f0ad100a25 Merge pull request #1796 from a-rookie-of-C-language/fix/find-match-fg-color
fix(editor): use search-match foreground color on find highlights
2026-11-06 20:31:38 +08:00
arookieofc 20cd00aaaf chore(mybatis): rebuild plugin.wasm for the annotation-name fix 2026-11-06 20:08:30 +08:00
arookieofc 0d526be1c3 fix(run): run Gradle module tests from the build root, not the module dir
"All Tests" on a Gradle module moved cwd to the module directory while
the command stayed './gradlew', so the wrapper could not be found. Keep
the run in the build root (where the wrapper resolves) and qualify the
task with the module's Gradle path (:services:api:test), using the build
model's real project path when loaded.
2026-11-06 19:41:17 +08:00
arookieofc 82ff476e8a feat(debugger): flash the taskbar when a breakpoint hits unfocused
When a debug session stops on a breakpoint and no OpenIDEA window is
focused, request user attention on every window so the taskbar icon
flashes — matching IDEA's behaviour of alerting the user that the
debuggee paused. The check runs on the main thread off TauriSink::emit,
which intercepts the DebugEvent::Stopped broadcast.

Fixes #1742
2026-11-06 19:36:23 +08:00
arookieofc 43409c2229 fix(mybatis): skip annotation arguments when parsing method names
A method-level annotation with arguments (`@DataPermission(column =
"id")`) made the statement's first `(` land inside the annotation,
so the parser read the annotation name as the method name and the
Mapper/XML gutter arrow broke. Find the `(` that opens the method's
parameter list instead: `(`s whose preceding token is an `@`-name
are skipped with their whole argument list (nested parens and string
literals included).

Fixes #1759
2026-11-06 19:32:37 +08:00
arookieofc 2591bbac8f fix(tabs): keep close button visible in squeezed tab strip
Closable tabs in a squeezed strip kept the 40px min-width of a plain
tab, so the close slot was clipped by overflow: hidden once the label
shrank. Give squeezed closable tabs a 64px min-width and pin the close
slot with flex: none so the X hit-target always stays visible.

Fixes #1740
2026-11-06 19:32:30 +08:00
arookieofc 0341b697ce fix(menu): show native tooltip for truncated item labels
Menu labels (e.g. Open Recent paths) overflow with ellipsis but offered
no way to read the full text. Give the label span a title attribute so
the browser shows the whole path on hover.

Fixes #1770
2026-11-06 19:25:15 +08:00
arookieofc 74f5ef8090 fix(editor): set search-match foreground color on find highlights
Find-in-file matches showed yellow background with the editor's green
syntax text underneath, making hits unreadable. Give .cm-openidea-findMatch
and .cm-openidea-findMatch-current the per-theme --fg-search-match color,
matching how .match rules elsewhere already set it.

Fixes #1733
2026-11-06 19:24:05 +08:00
youngledoтаyoungledo fca9d1e08f fix(window): keep merged project tabs from moving the frame or menu bar (#1697)
Merged project tabs are separate native windows. Switching tabs copied the selected frame with Tauri's position and size setters, which only queue the change, while macOS orders the shown window front at once, so the old rectangle appeared and then slid into place; two maximized windows could also share the maximized flag with different rectangles, so the copy was skipped. On macOS the AppKit frame is now written synchronously and the window is shown in the same turn, with frame constraining suspended for that write; elsewhere a differing outer rectangle is always assigned. A source window in native fullscreen still hands fullscreen over as before.

Focusing another project window re-pushed the shared menu config and replaced the macOS menu bar even when nothing changed; an identical config no longer rebuilds the menu.

Co-authored-by: youngledo <[email protected]>
2026-11-06 17:27:11 +08:00
Deng Liuтаdengliu a268b2c488 perf(vfs): share nested repo GitignoreStacks and bound synchronous watch_tree startup (#1705)
Opening a workspace with nested repositories, or a large repository on Linux, could stall open_project for minutes. GitignoreStack cached nested repositories per parent directory and cleared that cache on every created or removed path, so the startup walk rediscovered and recompiled the same nested repository's ignore rules for each directory; the per-directory watch walk also ran to completion on the open_project thread.

Nested stacks are now cached by repository root and invalidated only under the changed path (a `.git` appearing or disappearing included). The startup walk registers up to 256 directories synchronously and hands the rest to the watcher thread; children of a verified directory are matched by their own name only.

Tests cover the deferred startup watches and a repository created inside the workspace becoming an ignore boundary.

Co-authored-by: dengliu <[email protected]>
2026-11-06 17:26:26 +08:00
l0ng-ai d942f59dcd fix(vcs): exclude symbolic aliases from containing branches (#1747) 2026-11-06 17:18:48 +08:00
l0ng-ai ba9ce1d842 fix(workspace): unify nested project discovery and run ownership (#1716)
CI / Changes (push) Successful in 1s
Language smoke / Language smoke (go) (push) Failing after 6s
Language smoke / Language smoke (java) (push) Failing after 5s
Language smoke / Language smoke (kotlin) (push) Failing after 5s
Language smoke / Language smoke (python) (push) Failing after 4s
Language smoke / Language smoke (typescript) (push) Failing after 4s
Language smoke / Language smoke (rust) (push) Failing after 5s
CI / Rust (ubuntu-22.04) (push) Failing after 43s
CI / Plugins (SDK, official, fixtures) (push) Failing after 1m19s
CI / Remote server (linux musl) (push) Failing after 1m32s
CI / Cargo deny (push) Successful in 54s
CI / E2E (push) Successful in 15m57s
CI / Frontend (push) Successful in 24m49s
CI / Rust (macos-latest) (push) Canceled after 0s
CI / Rust (windows-latest) (push) Canceled after 0s
* fix(build): scope Kotlin bridge to linked Maven modules

* fix(run): resolve nested Go modules for context runs

* fix(gradle): discover nested builds and select compatible JVMs

* fix(workspace): share project discovery and module ownership

* fix(run): keep root toolchains for nested modules and resolve them once per module

- Python run configurations of a nested module without its own virtualenv use the closest one up to the project root.
- Gradle builds and runs fall back to the JDK matching the project's Java version when the Gradle version is unknown.
- Module-local interpreters and toolchains are resolved lazily, once per owning module.
- Tests build expected paths per segment so they hold on Windows.
2026-11-06 15:51:41 +08:00
l0ng-ai 763bcc056c fix(workbench): align settings with right stripe icons 2026-11-06 15:41:12 +08:00
l0ng-ai fc978292cc fix(app): ask before quitting from the Dock or a logout on macOS (#1730)
Quitting from the Dock, the system's app menu or a logout terminated OpenIDEA at once, skipping the exit, running-process and unsaved-changes prompts: tao's application delegate doesn't implement applicationShouldTerminate:. The delegate now cancels that termination unless a quit is already in progress and runs the same quit as Cmd+Q; cancelling a prompt keeps the app running.
2026-11-06 14:53:13 +08:00
l0ng-ai cf94ab7203 fix(run): stop runs and terminals when the app exits (#1727)
Closing a window stops what its project started, but a quit that exits without closing the windows first (the Dock's Quit, a logout) left every run's process tree alive: a server kept its port and the next run failed with "port already in use". The desktop exit handler now kills every run's process tree and every terminal shell, as the remote server's shutdown already does.

Fixes #1691
2026-11-06 14:46:55 +08:00
l0ng-ai 1c2eceb55f fix(debugger): run debug adapters on the tool search path (#1725)
Debug adapters were found on the tool search path but ran with the app's own PATH, so when the login shell's PATH didn't reach the app, what an adapter starts in turn was missing although Run found it: js-debug's wrapper failed with "exec: node: not found" and Delve's go build with "go: executable file not found". Adapters now get the search path language servers get unless the launch sets its own PATH, and adapter binaries are resolved on it. Covers every adapter (js-debug, Delve, debugpy, CodeLLDB, …), not only the two reported.

Fixes #1690
Fixes #1707
2026-11-06 14:40:29 +08:00
l0ng-ai f76c297fe9 fix(terminal): keep Windows shell paths intact (#1723)
The terminal's Shell path setting was split with POSIX rules, where a backslash escapes the next character, so C:\Windows\system32\cmd.exe reached the backend as C:Windowssystem32cmd.exe and every new terminal failed to start. On Windows a backslash is now a path separator, and an unquoted path up to its .exe/.cmd/.bat/.com is the program even with spaces; paths picked from the Installed Shells menu or Browse are quoted when they contain whitespace. This was the only place the setting is parsed.

Fixes #1327
2026-11-06 14:24:59 +08:00
l0ng-ai c75a630ede test(vcs): check the files a commit takes from its options
Commits take the checked files through vcs_commit's options instead of
staging them first; the Commit e2e tests now read them from there. Also
translates "Remote connection cancelled".
2026-11-06 14:14:44 +08:00
l0ng-ai 266e4eeb03 feat(updates): choose the update source, with a CNB mirror (#1673)
* feat(updates): choose the update source, with a CNB mirror

System Settings › Updates › Update source: Automatic, GitHub or CNB (China
mirror). Automatic uses CNB for the Chinese UI and GitHub otherwise. The
chosen source is tried first and the other one when it fails or has no
manifest, for the check, the startup check and the install.

* feat(updates): offer the other update source after a failed download

A failed or cancelled update download now offers "Retry with CNB" (or
"Retry with GitHub"): it switches the update source and downloads again
from there. Checks need no such action: they already try both sources.

* fix(updates): keep GitHub untranslated in the text catalog
2026-11-06 13:30:19 +08:00
l0ng-ai c1aa092d75 fix(tools): install GitHub releases when the API is rate-limited (#1715)
Language servers and debuggers published as GitHub releases were looked up only through api.github.com, which allows 60 unauthenticated requests an hour per IP address; behind a shared address installs failed with 403. When the API request fails, the release is now resolved from its web pages (latest-release redirect for the tag, the asset list for files and SHA-256 digests, the release notes for linked builds). This covers every GitHub-sourced tool, not only Kotlin. If both fail, the error names the release page and the Language Servers Path setting for a manual install.

Fixes #1651
2026-11-06 13:24:59 +08:00
158 змінених файлів з 6757 додано та 1535 видалено

No files matched your search

+7 -13
Переглянути файл
@@ -234,7 +234,12 @@ pub fn plan(
Ok(BuildPlan { system, title, steps })
}
fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
pub(super) fn maven_steps(
root: &Path,
model: &BuildModel,
kind: BuildKind,
module: Option<&Path>,
) -> IdeResult<Vec<BuildStep>> {
let fallback;
let m = match &model.maven {
Some(m) => m,
@@ -383,18 +388,7 @@ fn go_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
/// `pnpm` / `yarn` / `bun` / `npm`, from the lock file next to `package.json` or above it.
fn package_manager(dir: &Path) -> &'static str {
for d in dir.ancestors() {
if d.join("pnpm-lock.yaml").is_file() {
return "pnpm";
} else if d.join("yarn.lock").is_file() {
return "yarn";
} else if d.join("bun.lockb").is_file() || d.join("bun.lock").is_file() {
return "bun";
} else if d.join("package-lock.json").is_file() {
return "npm";
}
}
"npm"
ide_core::project_roots::package_manager(dir)
}
fn has_build_script(dir: &Path) -> bool {
+61 -16
Переглянути файл
@@ -218,21 +218,14 @@ fn normalize(p: &Path) -> PathBuf {
out
}
/// The directory of the Gradle build under `root`: the root itself, or a direct
/// subfolder, holding a settings or build script.
/// The first automatically discovered build, for callers operating on one build.
pub fn build_dir(root: &Path) -> Option<PathBuf> {
let has = |d: &Path| SETTINGS_FILES.iter().chain(BUILD_FILES).any(|f| d.join(f).is_file());
if has(root) {
return Some(root.to_path_buf());
}
let mut dirs: Vec<PathBuf> = std::fs::read_dir(root)
.ok()?
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !e.file_name().to_string_lossy().starts_with('.'))
.map(|e| e.path())
.collect();
dirs.sort();
dirs.into_iter().find(|d| SETTINGS_FILES.iter().any(|f| d.join(f).is_file()))
build_dirs(root).into_iter().next()
}
fn build_dirs(root: &Path) -> Vec<PathBuf> {
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
ide_core::project_roots::discover(root, &markers)
}
fn wrapper(dir: &Path) -> String {
@@ -495,7 +488,7 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
/// Linked build identities without reading their scripts (also used by index hot paths).
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
match &settings.linked_projects {
None => build_dir(root).map(|dir| rel(root, &dir)).into_iter().collect(),
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
Some(dirs) => {
let mut out = Vec::new();
for dir in dirs {
@@ -686,6 +679,55 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
#[cfg(test)]
mod tests {
#[test]
fn default_linkage_discovers_all_shallow_builds() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
for file in [
"Cargo.toml",
"package.json",
"fixtures/kotlin-gradle/settings.gradle.kts",
"fixtures/kotlin-gradle/build.gradle.kts",
"fixtures/kotlin-gradle/tools/settings.gradle",
"services/backend/api/settings.gradle",
"standalone/build.gradle",
"ignored/src/settings.gradle",
"ignored/out/build.gradle",
"node_modules/example/settings.gradle",
"target/example/build.gradle",
"build/example/settings.gradle",
"dist/example/build.gradle",
"vendor/example/settings.gradle",
".hidden/settings.gradle",
"too/deep/to/find/settings.gradle",
] {
let path = root.join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let models = super::load_linked(root, &Default::default());
assert_eq!(
models.iter().map(|m| m.dir.as_str()).collect::<Vec<_>>(),
["fixtures/kotlin-gradle", "ignored/src", "services/backend/api", "standalone"]
);
std::fs::write(root.join("build.gradle.kts"), "").unwrap();
let models = super::load_linked(root, &Default::default());
assert_eq!(models.len(), 1);
assert!(models[0].dir.is_empty());
}
#[cfg(unix)]
#[test]
fn default_linkage_does_not_follow_symlinks() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::create_dir(root.join("real")).unwrap();
std::fs::write(root.join("real/build.gradle"), "").unwrap();
std::os::unix::fs::symlink(root.join("real"), root.join("alias")).unwrap();
let models = super::load_linked(root, &Default::default());
assert_eq!(models.iter().map(|m| m.dir.as_str()).collect::<Vec<_>>(), ["real"]);
}
#[test]
fn a_path_from_the_ui_finds_the_saved_link() {
let temp = tempfile::tempdir().unwrap();
@@ -718,7 +760,10 @@ mod tests {
std::fs::create_dir(root.join(dir)).unwrap();
std::fs::write(root.join(dir).join("settings.gradle"), format!("rootProject.name = '{dir}'")).unwrap();
}
assert_eq!(super::load_linked(root, &Default::default())[0].dir, "a");
assert_eq!(
super::load_linked(root, &Default::default()).iter().map(|m| m.dir.as_str()).collect::<Vec<_>>(),
["a", "b"]
);
let mut settings = ide_core::settings::GradleSettings {
linked_projects: Some(vec!["b".into(), "./b".into(), "a".into()]),
..Default::default()
+116 -9
Переглянути файл
@@ -53,8 +53,12 @@ pub struct Outcome {
pub success: bool,
}
/// Inspect sources, excluding generated/build/VCS trees and never following symlinks.
pub fn has_kotlin(root: &Path) -> bool {
/// Only linked Maven modules contribute sources to the bridge.
pub fn has_kotlin(root: &Path, model: &BuildModel) -> bool {
model.maven.iter().flat_map(|m| &m.projects).any(|p| has_kotlin_sources(&root.join(&p.dir)))
}
fn has_kotlin_sources(root: &Path) -> bool {
let Ok(entries) = std::fs::read_dir(root) else { return false };
entries.flatten().any(|entry| {
let Ok(kind) = entry.file_type() else { return false };
@@ -66,11 +70,25 @@ pub fn has_kotlin(root: &Path) -> bool {
entry.file_name().to_str(),
Some("target" | "build" | "out" | "bin" | "node_modules" | ".git" | ".openidea")
)
&& has_kotlin(&entry.path())
&& !["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"]
.iter()
.any(|marker| entry.path().join(marker).is_file())
&& has_kotlin_sources(&entry.path())
}
})
}
fn plan(root: &Path, model: &BuildModel) -> IdeResult<compile::BuildPlan> {
if model.maven.as_ref().is_none_or(|m| m.projects.is_empty()) {
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
}
Ok(compile::BuildPlan {
system: compile::BuildSystem::Maven,
title: root.file_name().unwrap_or_default().to_string_lossy().into_owned(),
steps: compile::maven_steps(root, model, BuildKind::Build, None)?,
})
}
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
/// redirector loaded before Maven calculates its lifecycle execution plans.
pub fn build(
@@ -81,10 +99,7 @@ pub fn build(
cancel: &CancellationToken,
) -> IdeResult<Outcome> {
std::fs::create_dir_all(generation)?;
let mut plan = compile::plan(root, model, BuildKind::Build, None, None)?;
if plan.system != compile::BuildSystem::Maven {
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
}
let mut plan = plan(root, model)?;
let mut manifests = Vec::new();
for (index, step) in plan.steps.iter_mut().enumerate() {
step.args.push("--fail-at-end".into());
@@ -447,14 +462,106 @@ mod tests {
assert_eq!(error.message, "Kotlin bridge requires a Maven build root");
}
#[test]
fn kotlin_sources_belong_to_linked_maven_modules() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for file in [
"java/pom.xml",
"gradle/build.gradle.kts",
"gradle/src/main/kotlin/App.kt",
"java/unlinked/pom.xml",
"java/unlinked/src/main/kotlin/App.kt",
"java/gradle/settings.gradle.kts",
"java/gradle/src/main/kotlin/App.kt",
"java/target/generated/Old.kt",
"java/node_modules/dependency/App.kt",
"java/linked/pom.xml",
"java/linked/src/test/kotlin/Test.kt",
] {
let path = root.join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let mut model = BuildModel {
maven: Some(crate::MavenModel {
projects: vec![crate::MavenProject { dir: "java".into(), ..Default::default() }],
..Default::default()
}),
..Default::default()
};
assert!(!has_kotlin(root, &model));
model.maven.as_mut().unwrap().projects.push(crate::MavenProject {
dir: "java/linked".into(),
aggregated: true,
..Default::default()
});
assert!(has_kotlin(root, &model));
model.maven.as_mut().unwrap().projects.clear();
assert!(!has_kotlin(root, &model));
assert!(!has_kotlin(root, &BuildModel::default()));
}
#[test]
fn maven_bridge_ignores_the_workspace_build_system() {
for marker in ["Cargo.toml", "package.json", "build.gradle.kts", "go.mod", "CMakeLists.txt"] {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join(marker), "").unwrap();
let mut model = BuildModel { maven: Some(crate::MavenModel::default()), ..Default::default() };
for name in ["java", "kotlin"] {
let module = root.join(name);
std::fs::create_dir_all(&module).unwrap();
model.maven.as_mut().unwrap().projects.push(crate::MavenProject {
dir: name.into(),
command: format!("{name}-mvnw"),
options: vec!["-o".into(), "-Peditor".into()],
env: BTreeMap::from([("JAVA_HOME".into(), "/jdk".into())]),
..Default::default()
});
}
std::fs::write(root.join("kotlin/App.kt"), "class App").unwrap();
assert!(has_kotlin(root, &model), "{marker}");
let plan = plan(root, &model).unwrap();
assert_eq!(plan.system, compile::BuildSystem::Maven);
assert_eq!(plan.steps.len(), 2);
for (step, name) in plan.steps.iter().zip(["java", "kotlin"]) {
assert_eq!(step.cwd, root.join(name));
assert_eq!(step.program, format!("{name}-mvnw"));
assert_eq!(step.args, ["-B", "-Dstyle.color=never", "-o", "-Peditor", "test-compile"]);
assert_eq!(step.env.get("JAVA_HOME").map(String::as_str), Some("/jdk"));
}
}
}
#[test]
fn external_linked_maven_sources_are_included() {
let workspace = tempfile::tempdir().unwrap();
let external = tempfile::tempdir().unwrap();
std::fs::write(external.path().join("App.kt"), "class App").unwrap();
let model = BuildModel {
maven: Some(crate::MavenModel {
projects: vec![crate::MavenProject {
dir: external.path().to_string_lossy().into_owned(),
command: "mvn".into(),
..Default::default()
}],
..Default::default()
}),
..Default::default()
};
assert!(has_kotlin(workspace.path(), &model));
assert_eq!(plan(workspace.path(), &model).unwrap().steps[0].cwd, external.path());
}
#[test]
fn does_not_find_deleted_sources_in_build_outputs() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("target/generated")).unwrap();
std::fs::write(dir.path().join("target/generated/Old.kt"), "").unwrap();
assert!(!has_kotlin(dir.path()));
assert!(!has_kotlin_sources(dir.path()));
std::fs::write(dir.path().join("New.kt"), "").unwrap();
assert!(has_kotlin(dir.path()));
assert!(has_kotlin_sources(dir.path()));
}
#[test]
+1 -41
Переглянути файл
@@ -1013,10 +1013,7 @@ pub(crate) fn plugin(
// ---------------------------------------------------------------- loading
/// Directories never searched for POMs.
const SKIP_DIRS: &[&str] = &["node_modules", "target", "build", "out", "dist", "src", "vendor"];
const MAX_PROJECTS: usize = 1000;
const POM_SEARCH_DEPTH: usize = 3;
fn rel_path(root: &Path, p: &Path) -> String {
p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/")
@@ -1027,44 +1024,7 @@ fn rel_path(root: &Path, p: &Path) -> String {
/// aggregate POM directly inside `src/` counts too (issue #1001: `src/pom.xml`
/// with its modules beside it, `src/app/pom.xml` and so on).
fn top_level_poms(root: &Path) -> Vec<PathBuf> {
let top = root.join("pom.xml");
if top.is_file() {
return vec![top];
}
let mut out = Vec::new();
let src_pom = root.join("src").join("pom.xml");
if src_pom.is_file() {
out.push(src_pom);
}
let mut queue: Vec<(PathBuf, usize)> = vec![(root.to_path_buf(), 0)];
while let Some((dir, depth)) = queue.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
let mut dirs: Vec<PathBuf> = Vec::new();
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
if e.file_type().is_ok_and(|t| t.is_dir()) && !name.starts_with('.') && !SKIP_DIRS.contains(&name.as_str())
{
dirs.push(e.path());
}
}
dirs.sort();
for d in dirs.into_iter().rev() {
let pom = d.join("pom.xml");
if pom.is_file() {
out.push(pom);
continue;
}
let src_pom = d.join("src").join("pom.xml");
if src_pom.is_file() {
out.push(src_pom);
}
if depth + 1 < POM_SEARCH_DEPTH {
queue.push((d, depth + 1));
}
}
}
out.sort();
out
ide_core::project_roots::discover(root, &["pom.xml"]).into_iter().map(|dir| dir.join("pom.xml")).collect()
}
/// Whether `root` holds a Maven build (cheap: the same search as [`load`] without parsing).
+1
Переглянути файл
@@ -16,6 +16,7 @@ pub mod jsonc;
pub mod output_encoding;
pub mod process;
pub mod project_dir;
pub mod project_roots;
pub mod proxy_settings;
pub mod remote_settings;
pub mod settings;
+197
Переглянути файл
@@ -0,0 +1,197 @@
//! Shared filesystem rules for discovering builds and resolving their owners.
use std::path::{Component, Path, PathBuf};
pub const SEARCH_DEPTH: usize = 3;
pub fn children(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut dirs: Vec<_> = entries
.flatten()
.filter(|entry| {
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
return false;
}
let name = entry.file_name();
let name = name.to_string_lossy();
!name.starts_with('.')
&& !matches!(
name.as_ref(),
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
)
})
.map(|entry| entry.path())
.collect();
dirs.sort();
dirs
}
pub fn discover(root: &Path, markers: &[&str]) -> Vec<PathBuf> {
discover_matching(root, SEARCH_DEPTH, true, |dir| markers.iter().any(|marker| dir.join(marker).is_file()))
}
pub fn discover_matching(
root: &Path,
max_depth: usize,
stop_at_match: bool,
marked: impl Fn(&Path) -> bool,
) -> Vec<PathBuf> {
let mut found = Vec::new();
let mut pending = vec![(root.to_path_buf(), 0)];
while let Some((dir, depth)) = pending.pop() {
if marked(&dir) {
found.push(dir.clone());
if stop_at_match {
continue;
}
}
// A source folder may itself be a build root (e.g. src/pom.xml), but
// source trees without their own build marker are never searched.
let source = dir.join("src");
if source.is_dir() && !source.is_symlink() && marked(&source) {
found.push(source);
}
if depth < max_depth {
pending.extend(
children(&dir)
.into_iter()
.rev()
.filter(|child| !child.ends_with("src"))
.map(|child| (child, depth + 1)),
);
}
}
found.sort();
found.dedup();
found
}
/// The closest package manager declaration or lockfile, shared by build and run.
pub fn package_manager(root: &Path) -> &'static str {
for dir in root.ancestors() {
let package = std::fs::read(dir.join("package.json"))
.ok()
.and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());
if let Some(pm) = package.as_ref().and_then(|p| p.get("packageManager")).and_then(|p| p.as_str()) {
match pm.split('@').next().unwrap_or_default() {
"pnpm" => return "pnpm",
"yarn" => return "yarn",
"bun" => return "bun",
"npm" => return "npm",
_ => {}
}
}
for (marker, pm) in [
("pnpm-lock.yaml", "pnpm"),
("yarn.lock", "yarn"),
("bun.lock", "bun"),
("bun.lockb", "bun"),
("package-lock.json", "npm"),
] {
if dir.join(marker).is_file() {
return pm;
}
}
}
"npm"
}
pub fn resolve(root: &Path, path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in root.join(path).components() {
match component {
Component::CurDir => {}
Component::ParentDir if out.file_name().is_some() => {
out.pop();
}
component => out.push(component),
}
}
out
}
pub fn relative(root: &Path, path: &Path) -> PathBuf {
let path = resolve(root, path);
path.strip_prefix(resolve(root, Path::new(""))).unwrap_or(&path).to_path_buf()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn package_manager_declarations_are_shared_by_build_and_run() {
let temp = tempfile::tempdir().unwrap();
std::fs::write(temp.path().join("pnpm-lock.yaml"), "").unwrap();
let child = temp.path().join("packages/web");
std::fs::create_dir_all(&child).unwrap();
assert_eq!(package_manager(&child), "pnpm");
std::fs::write(child.join("package.json"), r#"{"packageManager":"[email protected]"}"#).unwrap();
assert_eq!(package_manager(&child), "yarn");
}
#[test]
fn discovery_has_one_depth_boundary_and_exclusion_policy_for_all_families() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let markers = [
"package.json",
"Cargo.toml",
"go.mod",
"pom.xml",
"build.gradle.kts",
"pyproject.toml",
"composer.json",
"Gemfile",
"CMakeLists.txt",
"project.godot",
"deno.json",
"Makefile",
"justfile",
];
for marker in markers {
for dir in [
"apps/one",
"services/backend/two",
"src",
"a/b/c/src",
"too/deep/to/find",
"node_modules/ignored",
"target/ignored",
"build/ignored",
"vendor/ignored",
".hidden",
"src/ignored",
] {
let path = root.join(dir).join(marker);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
assert_eq!(
discover(root, &[marker]),
["a/b/c/src", "apps/one", "services/backend/two", "src"].map(|dir| root.join(dir))
);
}
std::fs::write(root.join("Cargo.toml"), "").unwrap();
assert_eq!(discover(root, &["Cargo.toml"]), [root]);
}
#[cfg(unix)]
#[test]
fn discovery_never_follows_directory_symlinks() {
let temp = tempfile::tempdir().unwrap();
std::fs::create_dir(temp.path().join("real")).unwrap();
std::fs::write(temp.path().join("real/go.mod"), "").unwrap();
std::os::unix::fs::symlink(temp.path().join("real"), temp.path().join("alias")).unwrap();
assert_eq!(discover(temp.path(), &["go.mod"]), [temp.path().join("real")]);
}
#[test]
fn paths_keep_component_boundaries_and_external_roots() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("workspace");
assert_eq!(relative(&root, &root.join("apps/../api")), Path::new("api"));
assert_eq!(relative(&root, &temp.path().join("workspace-other")), temp.path().join("workspace-other"));
assert_eq!(resolve(&root, Path::new("./api/../web")), root.join("web"));
}
}
+3
Переглянути файл
@@ -268,6 +268,8 @@ pub struct GeneralSettings {
pub power_save_mode: bool,
/// File › Rename Project… (project layer): the name shown for the project; empty = its folder name.
pub project_name: String,
/// Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`.
pub update_source: String,
}
impl Default for GeneralSettings {
@@ -282,6 +284,7 @@ impl Default for GeneralSettings {
date_format: DateFormatSettings::default(),
power_save_mode: false,
project_name: String::new(),
update_source: "auto".into(),
}
}
}
+27 -1
Переглянути файл
@@ -196,10 +196,18 @@ fn managed_dirs(root: &Path) -> Vec<PathBuf> {
dirs
}
/// The `PATH` an adapter runs with, unless its launch sets one: the search path language servers
/// get, so what it starts in turn (js-debug's wrapper runs `node`, Delve runs `go build`) is
/// found like Run finds it, even when the login shell's `PATH` didn't reach the app.
fn adapter_path(env: &[(String, String)]) -> Option<std::ffi::OsString> {
let own = env.iter().any(|(k, _)| if cfg!(windows) { k.eq_ignore_ascii_case("PATH") } else { k == "PATH" });
(!own).then(ide_core::tool_path::search_path)
}
/// Directories searched for adapter binaries: managed tools first, then `PATH` and the usual install spots.
fn search_dirs() -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = tools_root().map(|r| managed_dirs(&r)).unwrap_or_default();
dirs.extend(std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect::<Vec<_>>()).unwrap_or_default());
dirs.extend(std::env::split_paths(&ide_core::tool_path::search_path()));
if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
for rel in [".cargo/bin", ".local/bin", "go/bin", ".dotnet/tools", ".bun/bin", ".npm-global/bin", ".volta/bin"]
{
@@ -464,6 +472,9 @@ impl AdapterLauncher for ProcessLauncher {
None => args,
};
let mut cmd = Command::new(&binary);
if let Some(path) = adapter_path(&spec.env) {
cmd.env("PATH", path);
}
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(&args)
.envs(spec.env.iter().map(|(k, v)| (k, v)))
@@ -592,6 +603,21 @@ async fn connect_with_retries(
mod tests {
use super::*;
#[test]
fn adapters_run_on_the_tool_search_path() {
let search = ide_core::tool_path::search_path();
assert_eq!(adapter_path(&[]), Some(search.clone()));
assert_eq!(adapter_path(&[("GOFLAGS".into(), "-mod=mod".into())]), Some(search));
// A launch that sets its own (a selected Go SDK's bin first) keeps it.
assert_eq!(adapter_path(&[("PATH".into(), "/sdk/go/bin:/usr/bin".into())]), None);
// The search path reaches the usual install spots even when this process's `PATH` doesn't.
#[cfg(unix)]
{
let dirs: Vec<PathBuf> = std::env::split_paths(&ide_core::tool_path::search_path()).collect();
assert!(dirs.contains(&PathBuf::from("/usr/local/bin")), "{dirs:?}");
}
}
#[tokio::test]
async fn program_output_is_forwarded_without_the_adapter_banner() {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
+32
Переглянути файл
@@ -530,6 +530,34 @@ fn unverified(enabled: impl Iterator<Item = bool>) -> Vec<BreakpointState> {
.collect()
}
/// Delve compiles the debuggee to `__debug_bin` in the session's cwd (on Windows
/// `__debug_bin.exe` plus `__debug_bin.exe<digits>` in DAP mode) and removes it on a
/// graceful exit — a shutdown it doesn't always reach, so the files pile up. Sweep
/// the leftovers once the session is down. Runs after `session_closed`, so Delve
/// has already exited or been killed and holds no file locks; a leftover of a
/// still-building run is removed on that run's own shutdown.
fn remove_delve_binaries(cwd: &Path) {
let Ok(entries) = std::fs::read_dir(cwd) else { return };
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
// Windows writes `__debug_bin.exe` (and `.exe<digits>` in DAP mode); other
// platforms keep the bare name. Suffixes like `.go` are user files.
let suffix = name.strip_prefix("__debug_bin");
let leftover = suffix.is_some_and(|s| {
s.is_empty()
|| s == ".exe"
|| (s.starts_with(".exe") && s[".exe".len()..].chars().all(|c| c.is_ascii_digit()))
});
if leftover
&& entry.file_type().is_ok_and(|t| t.is_file())
&& let Err(e) = std::fs::remove_file(entry.path())
{
tracing::debug!("could not remove Delve leftover {}: {e}", entry.path().display());
}
}
}
pub(crate) fn variable_from(v: &Value) -> Variable {
let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned);
Variable {
@@ -981,6 +1009,10 @@ impl DebugManager {
}
s.conn.close();
self.session_closed(s);
if s.adapter == "delve" && s.spec.server_host.is_none() {
let cwd = s.spec.cwd.clone();
tokio::task::spawn_blocking(move || remove_delve_binaries(&cwd));
}
}
/// Breakpoints are kept per file even without a session and sent on start.
+23
Переглянути файл
@@ -1347,3 +1347,26 @@ fn flutter_projects_are_found_from_the_program_or_the_working_directory() {
assert!(!is_flutter_project(&root, None));
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn delve_leftovers_are_removed_without_touching_other_files() {
let dir = std::env::temp_dir().join(format!("openidea-delve-bin-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
for name in ["__debug_bin", "__debug_bin.exe", "__debug_bin.exe3323301925"] {
std::fs::write(dir.join(name), b"bin").unwrap();
}
// Lookalikes that are not Delve's own binaries stay: sources, a future
// in-progress build, and a directory that happens to share the name.
for name in ["__debug_bin.go", "__debug_bin.go.exe", "main.go"] {
std::fs::write(dir.join(name), b"keep").unwrap();
}
std::fs::create_dir(dir.join("__debug_bin.dir")).unwrap();
remove_delve_binaries(&dir);
for name in ["__debug_bin", "__debug_bin.exe", "__debug_bin.exe3323301925"] {
assert!(!dir.join(name).exists(), "{name} should be gone");
}
for name in ["__debug_bin.go", "__debug_bin.go.exe", "main.go", "__debug_bin.dir"] {
assert!(dir.join(name).exists(), "{name} should stay");
}
std::fs::remove_dir_all(&dir).unwrap();
}
+57 -3
Переглянути файл
@@ -54,6 +54,10 @@ pub struct Manifest {
pub change_notes: Option<String>,
/// Marketplace categories as declared (see [`Manifest::categories`]).
pub declared_categories: Vec<String>,
/// SVG shown in Settings › Plugins and the marketplace.
pub icon: Option<PathBuf>,
/// Its variant for dark themes.
pub icon_dark: Option<PathBuf>,
/// `engines.openidea` (a semver requirement), or the legacy `openidea-api`.
pub engine: String,
/// Written in the 0.1 format.
@@ -175,6 +179,10 @@ struct Raw {
#[serde(default)]
categories: Vec<String>,
#[serde(default)]
icon: Option<PathBuf>,
#[serde(default)]
icon_dark: Option<PathBuf>,
#[serde(default)]
engines: Option<Engines>,
/// 0.1 format.
#[serde(default)]
@@ -253,6 +261,8 @@ impl Manifest {
license: raw.license,
change_notes: raw.change_notes,
declared_categories: raw.categories,
icon: raw.icon,
icon_dark: raw.icon_dark,
engine,
legacy,
wasm: raw.wasm,
@@ -270,6 +280,16 @@ impl Manifest {
Self::parse(&src).map_err(|e| format!("{}: {e}", path.display()))
}
/// Refuses `what`, new in plugin API 1.`minor`, while `engines.openidea`
/// still admits an older 1.x: those IDEs reject the manifest at install.
pub fn needs_api(&self, what: &str, minor: u64) -> Result<(), String> {
let older = |m| engine_compatible_with(&self.engine, &semver::Version::new(1, m, u64::MAX));
if self.legacy || (0..minor).any(older) {
return Err(format!("{what} is new in plugin API 1.{minor}: set engines.openidea to \"^1.{minor}\""));
}
Ok(())
}
fn validate(&self) -> Result<(), String> {
validate_plugin_id(&self.id)?;
if self.name.trim().is_empty() {
@@ -291,6 +311,16 @@ impl Manifest {
if let Some(wasm) = &self.wasm {
check_relative(wasm, "wasm")?;
}
if let Some(icon) = &self.icon {
self.needs_api("`icon`", 2)?;
check_relative(icon, "icon")?;
}
if let Some(dark) = &self.icon_dark {
if self.icon.is_none() {
return Err("`icon-dark` needs `icon`".into());
}
check_relative(dark, "icon-dark")?;
}
if self.wasm.is_none() && !self.activation.is_empty() {
return Err("`activation` needs `wasm`: there is no code to activate".into());
}
@@ -376,9 +406,11 @@ pub fn engine_compatible(engine: &str, legacy: bool) -> bool {
if legacy {
return engine == LEGACY_API || engine.strip_prefix(LEGACY_API).is_some_and(|rest| rest.starts_with('.'));
}
let Ok(req) = semver::VersionReq::parse(engine) else { return false };
let host = semver::Version::parse(ENGINE_VERSION).expect("valid engine version");
req.matches(&host)
engine_compatible_with(engine, &semver::Version::parse(ENGINE_VERSION).expect("valid engine version"))
}
fn engine_compatible_with(engine: &str, api: &semver::Version) -> bool {
semver::VersionReq::parse(engine).is_ok_and(|req| req.matches(api))
}
/// Segments of `[a-z0-9][a-z0-9_-]*` joined by `.` (an optional publisher
@@ -549,6 +581,28 @@ mod tests {
assert!(err("id = \"ok\"\nname = \"N\"\nversion = \"1.0\"\nengines.openidea = \"^1.0\"").contains("version"));
}
const BASE: &str = "id = \"ok\"\nname = \"N\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.2\"\n";
#[test]
fn parses_icons() {
let m = Manifest::parse(&format!("{BASE}icon = \"icon.svg\"\nicon-dark = \"icon_dark.svg\"\n")).unwrap();
assert_eq!(m.icon.as_deref(), Some(Path::new("icon.svg")));
assert_eq!(m.icon_dark.as_deref(), Some(Path::new("icon_dark.svg")));
assert_eq!(Manifest::parse(BASE).unwrap().icon, None);
}
#[test]
fn rejects_invalid_icons() {
assert!(err(&format!("{BASE}icon-dark = \"d.svg\"\n")).contains("`icon-dark` needs `icon`"));
assert!(err(&format!("{BASE}icon = \"../x.svg\"\n")).contains("icon"));
assert!(err(&format!("{BASE}icon = \"/abs.svg\"\n")).contains("icon"));
assert!(err(&format!("{BASE}icon = \"i.svg\"\nicon-dark = \"../d.svg\"\n")).contains("icon-dark"));
for engine in ["^1.0", ">=1.1, <2"] {
let old = BASE.replace("^1.2", engine);
assert!(err(&format!("{old}icon = \"i.svg\"\n")).contains("new in plugin API 1.2"), "{engine}");
}
}
#[test]
fn ids() {
assert!(validate_plugin_id("openidea.material-icons").is_ok());
+13
Переглянути файл
@@ -314,6 +314,14 @@ pub struct Endorsement {
pub signature: String,
}
/// A plugin's own icon (`icon`, `icon-dark` of its manifest): sanitised SVG markup.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginIcon {
pub light: String,
pub dark: Option<String>,
}
/// A published plugin version.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
@@ -340,6 +348,10 @@ pub struct IndexEntry {
/// Marketplace categories (`CATEGORIES`); an IDE ignores those it doesn't know.
#[serde(default)]
pub categories: Vec<String>,
/// The manifest's icon, sanitised by whoever wrote the index and again by
/// the IDE before showing it.
#[serde(default)]
pub icon: Option<PluginIcon>,
}
impl IndexEntry {
@@ -672,6 +684,7 @@ mod tests {
capabilities: Vec::new(),
engine: "^1.0".into(),
categories: Vec::new(),
icon: None,
}
}
+41 -3
Переглянути файл
@@ -22,7 +22,7 @@
mod templates;
use ide_extension::{Manifest, validate_plugin_id};
use ide_host::plugins::{PluginHost, read_market_url, resolve_market_href};
use ide_host::plugins::{PluginHost, plugin_icon, read_market_url, resolve_market_href};
use ide_plugin::{Limits, PluginEngine};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
@@ -650,6 +650,7 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
capabilities: m.capabilities.all().map(|c| c.to_string()).collect(),
engine: package::engine_requirement(&m.engine, built_for.as_ref()),
categories: m.categories(),
icon: plugin_icon(&ide_extension::Package::new(m.clone(), scratch.clone()))?,
})
})();
let entry = entry.map_err(|e| format!("{}: {e}", path.display()))?;
@@ -812,20 +813,24 @@ mod tests {
/// A theme package `id` signed by `publisher` with `key`, packed into `out`.
fn signed_theme(tmp: &Path, id: &str, publisher: &str, key: &str, out: &Path) {
signed_theme_version(tmp, id, "0.1.0", "^1.0", publisher, key, out);
signed_theme_version(tmp, id, "0.1.0", "^1.2", publisher, key, out);
}
fn signed_theme_version(tmp: &Path, id: &str, version: &str, engine: &str, publisher: &str, key: &str, out: &Path) {
let src = tmp.join("src").join(format!("{id}-{version}"));
let vars = templates::Vars { id, name: id, sdk: None };
// A manifest icon needs API 1.2.
let icon = if engine == "^1.2" { "\nicon = \"icon.svg\"" } else { "" };
for (rel, content) in templates::render(templates::Template::Theme, &vars) {
let path = src.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let content = content
.replace("version = \"0.1.0\"", &format!("version = \"{version}\""))
.replace("engines.openidea = \"^1.0\"", &format!("engines.openidea = \"{engine}\""));
.replace("engines.openidea = \"^1.0\"", &format!("engines.openidea = \"{engine}\"{icon}"));
std::fs::write(path, content).unwrap();
}
std::fs::write(src.join("icon.svg"), r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#)
.unwrap();
std::fs::create_dir_all(out).unwrap();
let args = [src.to_str().unwrap(), "--key", key, "--publisher", publisher, "--out"]
.into_iter()
@@ -921,6 +926,11 @@ mod tests {
let listed: Vec<_> = index.plugins.iter().map(|e| (e.id.as_str(), e.publisher.as_str())).collect();
assert_eq!(listed, [("alice.dawn", "alice"), ("openidea.night", "openidea")]);
assert_eq!(index.plugins[1].categories, ["themes"], "implied by the theme");
assert!(
index.plugins[1].icon.as_ref().is_some_and(|i| i.light.contains("<rect")),
"{:?}",
index.plugins[1].icon
);
assert_eq!(index.plugins[1].download, "openidea.night-0.1.0.oiplugin");
assert!(Path::new(&index.plugins[0].download).is_absolute(), "{}", index.plugins[0].download);
@@ -930,6 +940,34 @@ mod tests {
assert!(err.contains("unknown publisher"), "{err}");
}
#[test]
fn the_index_carries_plugin_icons() {
let tmp = tempfile::tempdir().unwrap();
let t = tmp.path();
let key = t.join("acme.key");
std::fs::write(&key, PublisherKey::from_seed([6; 32]).seed_base64()).unwrap();
let src = t.join("src");
let vars = templates::Vars { id: "acme.iconic", name: "Iconic", sdk: None };
for (rel, content) in templates::render(templates::Template::Theme, &vars) {
let path = src.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, content).unwrap();
}
let manifest = std::fs::read_to_string(src.join("plugin.toml")).unwrap();
let manifest = manifest.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.2\"");
std::fs::write(src.join("plugin.toml"), format!("icon = \"icon.svg\"\n{manifest}")).unwrap();
std::fs::write(src.join("icon.svg"), r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#)
.unwrap();
let out = t.join("out");
std::fs::create_dir_all(&out).unwrap();
let (src, key) = (src.to_string_lossy().into_owned(), key.to_string_lossy().into_owned());
let package = out.join("acme.iconic-0.1.0.oiplugin").to_string_lossy().into_owned();
cmd_pack(&strings(&[&src, "--key", &key, "--publisher", "acme", "--out", &package])).unwrap();
cmd_index(&strings(&[out.to_str().unwrap(), "--publisher", "acme", "--key", &key])).unwrap();
let index = Index::parse(&std::fs::read_to_string(out.join("index.json")).unwrap()).unwrap();
assert!(index.plugins[0].icon.as_ref().expect("icon").light.contains("<rect"));
}
/// `cargo test` of a new Rust plugin (its own tests against the mock host) with this SDK.
#[test]
fn the_command_template_builds_against_the_sdk() {
+1 -2
Переглянути файл
@@ -170,8 +170,7 @@ impl KotlinBridge {
let settings = self.settings.effective();
let has_sources = tokio::task::spawn_blocking(move || {
let model = crate::ops::build::load(&root, &cache, &settings);
let enabled =
model.maven.as_ref().is_some_and(|m| !m.projects.is_empty()) && kotlin_bridge::has_kotlin(&root);
let enabled = kotlin_bridge::has_kotlin(&root, &model);
(model, enabled)
})
.await;
+8
Переглянути файл
@@ -349,6 +349,14 @@ impl Host {
}
}
/// Called on desktop exit: kills the runs and terminal shells still alive. Closing a
/// window stops what it started, but a quit from the Dock, the app menu or a logout
/// exits without closing the windows, and the process trees would outlive the app.
pub fn stop_processes_on_exit(&self) {
self.processes.kill_all();
self.terminals.kill_all();
}
/// Called before desktop exit, which may bypass document destructors.
pub fn clear_workspace_edit_history_on_exit(&self) {
for project in self.projects() {
+92 -8
Переглянути файл
@@ -47,8 +47,8 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
}
}
for g in &mut model.gradle {
g.env = ide_sdk::apply::gradle_env(root, settings, java_env(jdk.as_ref(), g.java_version));
g.command = ide_sdk::apply::gradle_command(root, &root.join(&g.dir), settings).to_string_lossy().into_owned();
g.env = ide_sdk::apply::gradle_build_env(root, &root.join(&g.dir), &g.command, settings, g.java_version);
}
// A failed sync of a project no installed JDK can build says so first (with a Download JDK action).
let missing = |release: Option<u32>| match jdk {
@@ -76,6 +76,42 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
model
}
/// Build and Run use the same selected toolchain and module-local runtime discovery.
fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings) -> compile::BuildPlan {
let kind = match plan.system {
compile::BuildSystem::Cargo => "cargo",
compile::BuildSystem::Go => "go",
compile::BuildSystem::TypeScript => "npm",
_ => return plan,
};
for step in &mut plan.steps {
let mut config = ide_run::RunConfig {
id: String::new(),
name: String::new(),
kind: kind.into(),
command: step.program.clone(),
args: step.args.clone(),
cwd: Some(step.cwd.clone().into()),
env: step.env.clone(),
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
config.extras.module = Some(ide_core::ipc_path::to_ipc(&step.cwd));
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, settings);
if kind == "go" {
config.extras.params.insert("useTags".into(), "true".into());
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
}
step.program = config.command;
step.args = config.args;
step.env = config.env;
}
plan
}
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
/// the tool window do.
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
@@ -467,7 +503,11 @@ pub async fn build_run(
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache = cache.join(crate::project::project_key(member));
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
let plan = compile::plan(member, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?;
let plan = prepare_plan(
compile::plan(member, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?,
member,
&settings,
);
match &mut combined {
Some(combined) => combined.steps.extend(plan.steps),
None => combined = Some(plan),
@@ -477,13 +517,17 @@ pub async fn build_run(
plan.title = workspace.name;
plan
} else {
compile::plan(
prepare_plan(
compile::plan(
&root,
&with_profiles(load(&root, &cache, &settings), &cache),
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
)?,
&root,
&with_profiles(load(&root, &cache, &settings), &cache),
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
)?
&settings,
)
};
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
@@ -559,6 +603,46 @@ pub(crate) fn register(d: &mut Dispatcher) {
mod gradle_settings_tests {
use super::*;
#[test]
fn builds_apply_the_same_explicit_toolchains_as_runs() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let tool = |name: &str| format!("{name}{}", std::env::consts::EXE_SUFFIX);
for name in ["cargo", "go"] {
let path = root.join("sdk").join("bin").join(tool(name));
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let mut settings = Settings::default();
settings.languages.rust.toolchain = "sdk".into();
settings.languages.go.goroot = "sdk".into();
settings.languages.go.build_tags.custom = "integration".into();
settings.languages.node.package_manager = "yarn".into();
for (marker, source, program) in [
(
"Cargo.toml",
"[package]\nname='demo'\nversion='0.1.0'",
root.join("sdk").join("bin").join(tool("cargo")).to_string_lossy().into_owned(),
),
("go.mod", "module demo", root.join("sdk").join("bin").join(tool("go")).to_string_lossy().into_owned()),
("package.json", r#"{"scripts":{"build":"echo built"},"packageManager":"pnpm@10"}"#, "yarn".into()),
] {
let dir = root.join(marker.replace('.', "-"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(marker), source).unwrap();
let plan = prepare_plan(
compile::plan(&dir, &Default::default(), BuildKind::Artifacts, None, None).unwrap(),
root,
&settings,
);
assert_eq!(plan.steps[0].program, program);
assert_eq!(plan.steps[0].cwd, dir);
if marker == "go.mod" {
assert!(plan.steps[0].args.contains(&"-tags=integration".into()));
}
}
}
#[test]
fn linking_retains_the_implicit_build_and_unlinking_all_stays_empty() {
let tmp = tempfile::tempdir().unwrap();
+23 -2
Переглянути файл
@@ -307,7 +307,11 @@ pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::
/// References of the symbol at `pos`. `project_wide` also searches project files
/// outside the language server's analysis scope; bulk scans over many symbols
/// leave it off. Cancel with `cancel_request(request)`.
/// leave it off. Java, `project_wide`: without `libraries`, the dependencies and the JDK
/// are not searched; with it, those found in the sources arrive on `on_partial` before
/// the slower search for the rest, and the result has them all. Cancel with
/// `cancel_request(request)`.
#[allow(clippy::too_many_arguments)]
pub async fn lsp_references(
host: &Host,
window: &str,
@@ -316,10 +320,24 @@ pub async fn lsp_references(
pos: Pos,
include_declaration: bool,
project_wide: bool,
libraries: bool,
on_partial: super::Channel<References>,
) -> IdeResult<References> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = lsp.references(doc, pos, include_declaration, project_wide, cancel).await;
let result = lsp
.references_streaming(
doc,
pos,
include_declaration,
project_wide,
libraries,
cancel,
Some(&|refs| {
let _ = on_partial.send(refs);
}),
)
.await;
host.end_request(request);
result
}
@@ -789,6 +807,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
);
d.add("lsp_virtual_document", |c| async move { lsp_virtual_document(&c.host, &c.window, c.arg("uri")?).await });
d.add("lsp_references", |c| async move {
let on_partial = c.sender("onPartial")?;
lsp_references(
&c.host,
&c.window,
@@ -797,6 +816,8 @@ pub(crate) fn register(d: &mut Dispatcher) {
c.arg("pos")?,
c.arg("includeDeclaration")?,
c.arg("projectWide")?,
c.arg("libraries")?,
on_partial,
)
.await
});
+95 -10
Переглянути файл
@@ -28,9 +28,12 @@ pub fn configs(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
task.target = format!("workspace:{}:{}", key, task.target);
}
}
for id in &mut config.extras.compound {
*id = format!("workspace:{key}:{id}");
}
config.id = format!("workspace:{}:{}", key, config.id);
config.name = format!("{name} / {}", config.name);
config.cwd = Some(config.cwd.map(|p| member.join(&*p)).unwrap_or_else(|| member.clone()).into());
ide_run::scope::rebase(&mut config, &member, None);
config.detected = true;
if !user.iter().any(|u| u.id == config.id) && !root_suppressed.contains(&config.id) {
all.push(config);
@@ -51,10 +54,18 @@ fn detected_and_saved(
suppressed: &[String],
) -> Vec<RunConfig> {
let excluded_poms = crate::project::unlinked_maven_poms(root, settings);
let gradle = settings
.languages
.java
.gradle
.linked_projects
.as_ref()
.map(|_| ide_build::gradle::load_linked(root, &settings.languages.java.gradle));
let mut all: Vec<RunConfig> =
ide_run::detect_with_profiles(root, &excluded_poms, settings.cmake.profiles.as_deref())
.into_iter()
.filter(|d| !suppressed.contains(&d.id) && !saved.iter().any(|u| u.id == d.id))
.filter(|d| linked_config(root, gradle.as_deref(), &excluded_poms, d))
.collect();
all.extend(saved.iter().cloned());
for config in all.iter_mut().filter(|c| !matches!(c.kind.as_str(), "gradle" | "maven")) {
@@ -63,6 +74,41 @@ fn detected_and_saved(
all
}
fn linked_config(
root: &std::path::Path,
gradle: Option<&[ide_build::GradleModel]>,
excluded_poms: &[std::path::PathBuf],
config: &RunConfig,
) -> bool {
let module = config
.extras
.module
.as_deref()
.map(std::path::Path::new)
.or(config.cwd.as_deref())
.unwrap_or(std::path::Path::new(""));
let owner = ide_core::project_roots::resolve(root, module);
if matches!(config.kind.as_str(), "maven" | "application" | "spring-boot")
&& excluded_poms.iter().any(|pom| ide_core::project_roots::resolve(root, pom).parent() == Some(owner.as_path()))
{
return false;
}
if gradle.is_some()
&& (config.kind == "gradle"
|| (matches!(config.kind.as_str(), "application" | "spring-boot")
&& ["build.gradle", "build.gradle.kts"].iter().any(|name| owner.join(name).is_file())))
{
return gradle.unwrap_or_default().iter().any(|build| {
if config.kind == "gradle" {
root.join(&build.dir) == owner
} else {
build.projects.iter().any(|p| root.join(&p.dir) == owner)
}
});
}
true
}
/// Saves the user configurations. They come from [`configs`], toolchains applied, so what
/// settings derived is dropped again: only the user's own choices reach `run.toml`.
pub fn save_configs(
@@ -87,11 +133,22 @@ pub fn save_configs(
fn settings_for(
host: &Host,
project: &crate::project::Project,
config: &RunConfig,
config: &mut RunConfig,
) -> IdeResult<(std::path::PathBuf, ide_core::settings::Settings)> {
let member = ide_workspace::workspace::Workspace::load(&project.root)?.and_then(|workspace| {
let cwd = config.cwd.as_deref()?;
workspace.projects.into_iter().filter(|root| cwd.starts_with(root)).max_by_key(|root| root.components().count())
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
if workspace.is_some() {
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
}
ide_run::scope::rebase(config, &project.root, None);
}
let member = workspace.and_then(|workspace| {
let owner = ide_run::scope::owner(&project.root, config);
workspace
.projects
.into_iter()
.filter(|root| owner.starts_with(root))
.max_by_key(|root| root.components().count())
});
Ok(match member {
Some(root) => {
@@ -109,11 +166,11 @@ pub fn without_derived(host: &Host, window: &str, configs: Vec<RunConfig>) -> Id
let project = host.project(window)?;
configs
.into_iter()
.map(|c| {
.map(|mut c| {
if c.kind == "gradle" {
return Ok(c);
}
let (root, settings) = settings_for(host, &project, &c)?;
let (root, settings) = settings_for(host, &project, &mut c)?;
Ok(ide_sdk::apply::without_derived(&c, &root, &settings))
})
.collect()
@@ -127,7 +184,7 @@ pub fn apply_settings(host: &Host, window: &str, configs: Vec<RunConfig>) -> Ide
.into_iter()
.map(|mut c| {
if c.kind != "gradle" {
let (root, settings) = settings_for(host, &project, &c)?;
let (root, settings) = settings_for(host, &project, &mut c)?;
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut c), &root, &settings);
}
Ok(c)
@@ -174,13 +231,13 @@ pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit
.run(&settings, &project.root, &config, project.sink.clone(), Box::new(move |c| out(c)))
.await;
}
let (root, settings) = settings_for(host, &project, &config)?;
let mut config = config;
let (root, settings) = settings_for(host, &project, &mut config)?;
let root = &root;
// Configurations made in the UI name bare tools (`godot`) that may live outside PATH.
// Maven re-applies too: a config listed before a settings change (daemon toggle,
// Maven home) keeps the launcher that was current then; re-resolving at launch is
// what makes the setting take effect without reopening the project.
let mut config = config;
if config.kind == "maven" {
ide_sdk::apply::prepare_maven_run(&mut config, root, &settings);
} else if matches!(config.kind.as_str(), "gradle" | "tomcat") {
@@ -295,3 +352,31 @@ pub fn list(host: &Host) -> Vec<RunInfo> {
mod commands;
mod container;
pub use commands::*;
#[cfg(test)]
mod ownership_tests {
use super::*;
#[test]
fn unlinked_builds_do_not_reappear_as_detected_application_configs() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
for name in ["maven", "gradle"] {
let dir = root.join(name);
std::fs::create_dir_all(dir.join("src/main/java")).unwrap();
std::fs::write(
dir.join("src/main/java/App.java"),
"@SpringBootApplication class App { public static void main(String[] a) {} }",
)
.unwrap();
}
std::fs::write(root.join("maven/pom.xml"), "<project><build><plugins><plugin><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>").unwrap();
std::fs::write(root.join("gradle/build.gradle.kts"), "plugins { id(\"org.springframework.boot\") }").unwrap();
let defaults = detected_and_saved(root, &Default::default(), &[], &[]);
assert!(defaults.iter().any(|c| c.kind == "spring-boot"));
let mut settings = ide_core::settings::Settings::default();
settings.languages.java.maven.unlinked_projects = vec!["maven/pom.xml".into()];
settings.languages.java.gradle.linked_projects = Some(vec![]);
let configs = detected_and_saved(root, &settings, &[], &[]);
assert!(configs.is_empty(), "{configs:?}");
}
}
+14 -3
Переглянути файл
@@ -46,10 +46,21 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
}
/// The interpreter the project uses: the configured one, else its virtualenv.
pub fn sdk_python_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core::IpcPath>> {
pub fn sdk_python_effective(host: &Host, window: &str, near: Option<PathBuf>) -> IdeResult<Option<ide_core::IpcPath>> {
host.require_trust(window)?;
let project = host.project(window)?;
Ok(ide_sdk::apply::python_interpreter(&project.root, &project.settings.effective()).map(Into::into))
let member = ide_workspace::workspace::Workspace::load(&project.root)?.and_then(|w| {
let near = near.as_deref()?;
w.projects.into_iter().filter(|root| near.starts_with(root)).max_by_key(|root| root.components().count())
});
let (root, settings) = match member {
Some(root) => {
let settings = ide_workspace::SettingsStore::load(&host.config_dir, Some(&root)).effective();
(root, settings)
}
None => (project.root.clone(), project.settings.effective()),
};
Ok(ide_sdk::apply::python_interpreter_near(&root, near.as_deref(), &settings).map(Into::into))
}
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
@@ -232,7 +243,7 @@ pub async fn sdk_python_pip(
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("sdk_detect", |c| async move { sdk_detect(&c.host, &c.window, c.arg("kind")?).await });
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window) });
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window, c.arg("near")?) });
d.add("sdk_php_effective", |c| async move { sdk_php_effective(&c.host, &c.window) });
d.add(
"sdk_php_language_level",
+17 -6
Переглянути файл
@@ -26,6 +26,7 @@
use super::icon_extensions::{Choice, DARK_SUFFIX, Extensions, Group, IconDefinition, Pattern, check_icon_id};
use super::icon_settings::{self, SettingsSection};
use ide_extension::package::PluginIcon;
use ide_extension::{Package, UiDecl, check_relative, decode, validate_item_id};
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
@@ -33,8 +34,10 @@ use std::path::PathBuf;
pub const POINT_ID: &str = "iconThemes";
const MAX_ICONS: usize = 5000;
const MAX_SVG: usize = 64 << 10;
pub(super) const MAX_SVG: usize = 64 << 10;
const MAX_MAPPINGS: usize = 20_000;
/// A plugin's own icon is inline in every plugin listing and index entry.
pub const MAX_PLUGIN_ICON: usize = 16 << 10;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
@@ -90,16 +93,24 @@ pub fn svg_prefix(theme: &str) -> String {
format!("iconTheme/{theme}/svg/")
}
/// An SVG icon of the package, size-checked and sanitised.
pub(super) fn read_icon(pkg: &Package, path: &std::path::Path) -> Result<String, String> {
/// An SVG icon of the package, size-checked (`max` bytes) and sanitised.
pub(super) fn read_icon(pkg: &Package, path: &std::path::Path, max: usize) -> Result<String, String> {
check_relative(path, "icon")?;
let svg = pkg.read_text(path)?;
if svg.len() > MAX_SVG {
return Err(format!("{}: larger than {} KiB", path.display(), MAX_SVG >> 10));
if svg.len() > max {
return Err(format!("{}: larger than {} KiB", path.display(), max >> 10));
}
sanitize_svg(&svg).map_err(|e| format!("{}: {e}", path.display()))
}
/// The manifest's `icon` / `icon-dark`, read and sanitised.
pub fn plugin_icon(pkg: &Package) -> Result<Option<PluginIcon>, String> {
let read = |path: &std::path::Path| read_icon(pkg, path, MAX_PLUGIN_ICON);
let Some(light) = &pkg.manifest.icon else { return Ok(None) };
let dark = pkg.manifest.icon_dark.as_deref().map(read).transpose()?;
Ok(Some(PluginIcon { light: read(light)?, dark }))
}
pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: Decl = decode(POINT_ID, decl)?;
validate_item_id(&d.id, "icon theme id")?;
@@ -166,7 +177,7 @@ pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Str
for (icon, def) in &theme.icon_definitions {
let dark = def.dark().map(|path| (path, DARK_SUFFIX));
for (path, suffix) in std::iter::once((def.light(), "")).chain(dark) {
let clean = read_icon(pkg, path)?;
let clean = read_icon(pkg, path, MAX_SVG)?;
assets.push((format!("{}{icon}{suffix}", svg_prefix(&d.id)), clean));
files.push(path.clone());
}
+14 -3
Переглянути файл
@@ -6,9 +6,10 @@
//! Release builds pin the official publisher to the keys they were built
//! with, so no index can sign `openidea.*` plugins with another key.
use super::icons::{MAX_PLUGIN_ICON, sanitize_svg};
use super::{PackageFile, PluginEvent, PluginHost, PluginSource, PluginStatus, PluginUpdate, install};
use ide_core::{IdeError, IdeResult};
use ide_extension::package::{self, Index, IndexEntry, PackageSignature, SIGNATURE_FILE};
use ide_extension::package::{self, Index, IndexEntry, PackageSignature, PluginIcon, SIGNATURE_FILE};
use ide_extension::{MANIFEST_FILE, Manifest};
use semver::Version;
use serde::{Deserialize, Serialize};
@@ -67,6 +68,14 @@ fn pinned(mut index: Index, official_keys: &[String]) -> Index {
index
}
/// An index's icon as the UI may show it: sanitised again, as any index may
/// have written it; without a light variant that passes, none.
fn safe_icon(icon: PluginIcon) -> Option<PluginIcon> {
// Before sanitising too: an index may hold megabytes of it.
let clean = |svg: String| (svg.len() <= MAX_PLUGIN_ICON).then(|| sanitize_svg(&svg).ok()).flatten();
Some(PluginIcon { light: clean(icon.light)?, dark: icon.dark.and_then(clean) })
}
/// Reads `url`: `http(s)://…`, `file://…` or a local path.
pub fn read_url(url: &str, max: usize) -> Result<Vec<u8>, String> {
if url.starts_with("https://") || url.starts_with("http://") {
@@ -242,7 +251,9 @@ impl PluginHost {
.get(&entry.id)
.filter(|p| p.source == PluginSource::Installed)
.map(|p| p.manifest().version.clone());
MarketPlugin { entry: entry.clone(), installed, compatible }
let mut entry = entry.clone();
entry.icon = entry.icon.and_then(safe_icon);
MarketPlugin { entry, installed, compatible }
})
.collect()
}
@@ -350,7 +361,7 @@ impl PluginHost {
pub(super) fn package_files_in(&self, dir: &Path) -> IdeResult<Vec<PathBuf>> {
let manifest = Manifest::load(dir).map_err(IdeError::invalid)?;
let pkg = ide_extension::Package::new(manifest, dir.to_path_buf());
let set = self.registry.prepare(&pkg).map_err(IdeError::invalid)?;
let set = self.prepare(&pkg).map_err(IdeError::invalid)?;
Ok(set.files.into_iter().chain(pkg.manifest.wasm.clone()).collect())
}
+27 -5
Переглянути файл
@@ -37,7 +37,9 @@ pub mod views;
pub mod web;
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
pub use icons::{map_asset as icon_theme_map_asset, sanitize_svg, svg_prefix as icon_theme_svg_prefix};
pub use icons::{
MAX_PLUGIN_ICON, map_asset as icon_theme_map_asset, plugin_icon, sanitize_svg, svg_prefix as icon_theme_svg_prefix,
};
pub use market::{
INDEX_FILE as MARKET_INDEX_FILE, MarketPlugin, OFFICIAL_INDEX as OFFICIAL_MARKET_INDEX, OFFICIAL_PUBLISHER,
read_url as read_market_url, resolve as resolve_market_href,
@@ -184,6 +186,8 @@ const IDLE_BATCH: Duration = Duration::from_secs(2);
struct LoadedPlugin {
pkg: Package,
/// Read at load so disabled and failed plugins show it too.
icon: Option<ide_extension::package::PluginIcon>,
/// The manifest failed to parse: `pkg` is a placeholder.
invalid: bool,
source: PluginSource,
@@ -1528,7 +1532,7 @@ impl PluginHost {
continue;
}
let pkg = Package::new(m.clone(), dir.clone());
let problem = match self.registry.prepare(&pkg) {
let problem = match self.prepare(&pkg) {
Err(e) => Some(e),
Ok(_) => m
.wasm
@@ -1551,6 +1555,7 @@ impl PluginHost {
authors: m.authors,
homepage: m.homepage,
change_notes: m.change_notes,
icon: plugin_icon(&pkg).ok().flatten(),
path: dir.into(),
problem,
});
@@ -1645,11 +1650,24 @@ impl PluginHost {
self.plugins.read().values().any(|p| p.dir() == dir)
}
/// Validates the manifest's icon and every declaration of `pkg`; the
/// icon files join the package files the declarations reference.
fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> {
plugin_icon(pkg)?;
let mut set = self.registry.prepare(pkg)?;
for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() {
if !set.files.contains(icon) {
set.files.push(icon.clone());
}
}
Ok(set)
}
/// Parses and validates a package directory; nothing takes effect.
fn validate_package(&self, src: &Path) -> IdeResult<(Package, ide_extension::PreparedSet)> {
let manifest = Manifest::load(src).map_err(IdeError::invalid)?;
let pkg = Package::new(manifest, src.to_path_buf());
let set = self.registry.prepare(&pkg).map_err(IdeError::invalid)?;
let set = self.prepare(&pkg).map_err(IdeError::invalid)?;
if let Some(wasm) = &pkg.manifest.wasm {
if !src.join(wasm).is_file() {
return Err(IdeError::invalid(format!(
@@ -1682,6 +1700,7 @@ impl PluginHost {
pkg = pkg.with_digest(digest.trim());
}
let plugin = Arc::new(LoadedPlugin {
icon: plugin_icon(&pkg).ok().flatten(),
pkg,
invalid,
source,
@@ -1731,7 +1750,7 @@ impl PluginHost {
let publisher = self.verified_publisher(plugin.dir());
plugin.meta.lock().publisher = publisher;
}
let set = match self.registry.prepare(&plugin.pkg) {
let set = match self.prepare(&plugin.pkg) {
Ok(set) => set,
Err(e) => return self.set_failed(plugin, e),
};
@@ -2086,7 +2105,7 @@ impl PluginHost {
return h.trim().to_owned();
}
// Installed before hashes were recorded: hash once and remember.
let files = self.registry.prepare(&plugin.pkg).map(|s| s.files).unwrap_or_default();
let files = self.prepare(&plugin.pkg).map(|s| s.files).unwrap_or_default();
let files: Vec<PathBuf> = files.into_iter().chain(plugin.manifest().wasm.clone()).collect();
let hash = ledger::package_hash(plugin.dir(), &files).unwrap_or_default();
let _ = std::fs::write(&file, &hash);
@@ -2153,6 +2172,7 @@ impl PluginHost {
authors: m.authors.clone(),
homepage: m.homepage.clone(),
change_notes: m.change_notes.clone(),
icon: p.icon.clone(),
source: p.source,
path: p.dir().to_path_buf().into(),
enabled: !self.state.lock().disabled.contains(&m.id),
@@ -2262,6 +2282,8 @@ fn placeholder_manifest(dir: &Path) -> Manifest {
license: None,
change_notes: None,
declared_categories: Vec::new(),
icon: None,
icon_dark: None,
engine: ide_extension::ENGINE_VERSION.into(),
legacy: false,
wasm: None,
+1 -1
Переглянути файл
@@ -124,7 +124,7 @@ pub fn forwarded(event: &PluginEvent) -> bool {
impl PluginHost {
fn package_files(&self, plugin: &super::LoadedPlugin) -> IdeResult<Vec<PathBuf>> {
let set = self.registry.prepare(&plugin.pkg).map_err(IdeError::invalid)?;
let set = self.prepare(&plugin.pkg).map_err(IdeError::invalid)?;
Ok(set.files.into_iter().chain(plugin.manifest().wasm.clone()).collect())
}
+3
Переглянути файл
@@ -1,6 +1,7 @@
//! UI-facing plugin types and the event stream.
use super::theme::ThemeDef;
use ide_extension::package::PluginIcon;
use ide_extension::{CapabilityInfo, ContributionInfo, UiContribution};
pub use ide_plugin::{ActionPerformed, ActionSource, EventKind, NotificationLevel, StatusItem, WorkbenchEvent};
use serde::{Deserialize, Serialize};
@@ -50,6 +51,7 @@ pub struct PluginInfo {
pub authors: Vec<String>,
pub homepage: Option<String>,
pub change_notes: Option<String>,
pub icon: Option<PluginIcon>,
pub source: PluginSource,
/// Package directory.
pub path: ide_core::IpcPath,
@@ -113,6 +115,7 @@ pub struct CatalogPlugin {
pub authors: Vec<String>,
pub homepage: Option<String>,
pub change_notes: Option<String>,
pub icon: Option<PluginIcon>,
/// Package directory; install with `install_from_dir(path)`.
pub path: ide_core::IpcPath,
pub has_code: bool,
+30 -5
Переглянути файл
@@ -5,9 +5,10 @@
//!
//! ```toml
//! [[contributes.menus]]
//! menu = "editor.context" # projectView.context, editorTab.context, tools
//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context
//! command = "check"
//! when = "editorLang == java"
//! # view = "<view id>" # required for (only allowed on) viewItem.context
//!
//! [[contributes.keymaps]]
//! command = "check"
@@ -63,7 +64,8 @@ pub const CUSTOM_EDITORS: &str = "customEditors";
pub const FILE_ICONS: &str = "fileIcons";
pub const FILE_TEMPLATES: &str = "fileTemplates";
const MENU_IDS: [&str; 4] = ["editor.context", "projectView.context", "editorTab.context", "tools"];
const VIEW_ITEM_MENU: &str = "viewItem.context";
const MENU_IDS: [&str; 5] = ["editor.context", "projectView.context", "editorTab.context", "tools", VIEW_ITEM_MENU];
const MAX_TITLE: usize = 256;
const MAX_SETTINGS: usize = 200;
const MAX_PATTERNS: usize = 16;
@@ -77,6 +79,10 @@ fn commands(pkg: &Package) -> BTreeSet<String> {
.collect()
}
fn declared_view(pkg: &Package, id: &str) -> Option<toml::Value> {
pkg.manifest.declarations(VIEWS).into_iter().find(|d| d.get("id").and_then(|v| v.as_str()) == Some(id))
}
fn declared_command(pkg: &Package, point: &str, command: &str) -> Result<(), String> {
if commands(pkg).contains(command) {
Ok(())
@@ -103,6 +109,8 @@ struct MenuDecl {
command: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
view: Option<String>,
}
pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
@@ -114,7 +122,24 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
if let Some(w) = &d.when {
validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?;
}
Ok(UiDecl::new(format!("{}/{}", d.menu, d.command), d.command.clone(), json(&d)?))
let key = match (d.menu == VIEW_ITEM_MENU, &d.view) {
(true, None) => return Err(format!("contributes.menus: {VIEW_ITEM_MENU} needs `view`")),
(true, Some(v)) => {
pkg.manifest.needs_api(&format!("contributes.menus: {VIEW_ITEM_MENU}"), 2)?;
let Some(view) = declared_view(pkg, v) else {
return Err(format!("contributes.menus: view {v:?} is not declared under [[contributes.views]]"));
};
if view.get("web").is_some() {
return Err(format!(
"contributes.menus: view {v:?} is a web view (viewItem.context needs a tree or list the plugin renders)"
));
}
format!("{VIEW_ITEM_MENU}/{v}/{}", d.command)
}
(false, Some(_)) => return Err(format!("contributes.menus: `view` is only for {VIEW_ITEM_MENU}")),
(false, None) => format!("{}/{}", d.menu, d.command),
};
Ok(UiDecl::new(key, d.command.clone(), json(&d)?))
}
#[derive(Debug, Deserialize, Serialize)]
@@ -380,7 +405,7 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
out.files = files;
if let Some(icon) = d.icon.as_deref().filter(|i| i.ends_with(".svg")) {
let path = std::path::PathBuf::from(icon);
let svg = super::icons::read_icon(pkg, &path)?;
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
out.assets.push((view_icon_asset(&d.id), svg));
out.files.push(path);
}
@@ -473,7 +498,7 @@ pub(super) fn file_icon(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Stri
let mut assets = Vec::new();
for (path, dark) in [(Some(&d.icon), false), (d.icon_dark.as_ref(), true)] {
let Some(path) = path else { continue };
let svg = super::icons::read_icon(pkg, path)?;
let svg = super::icons::read_icon(pkg, path, super::icons::MAX_SVG)?;
assets.push((file_icon_asset(&d.id, dark), svg));
files.push(path.clone());
}
+15
Переглянути файл
@@ -74,6 +74,21 @@ impl TrustStore {
Ok(())
}
pub fn add_location(&self, path: &Path) -> IdeResult<()> {
let root = dunce::canonicalize(path)?;
if !root.is_dir() {
return Err(IdeError::invalid("trusted location must be an existing directory"));
}
let mut state = self.state.lock();
let mut next = state.clone()?;
if !next.locations.contains(&root) {
next.locations.push(root);
persist(&self.file, &next)?;
*state = Ok(next);
}
Ok(())
}
pub fn remove_location(&self, path: &Path) -> IdeResult<()> {
let mut state = self.state.lock();
let mut next = state.clone()?;
+24 -1
Переглянути файл
@@ -1,7 +1,7 @@
//! Versioned installs with automatic rollback, signed packages from
//! a static marketplace index, and revocation.
use ide_extension::package::{self, Index, IndexEntry, KeyEntry, Publisher, PublisherKey, Revocation};
use ide_extension::package::{self, Index, IndexEntry, KeyEntry, PluginIcon, Publisher, PublisherKey, Revocation};
use ide_host::plugins::*;
use ide_plugin::{Invocation, Limits};
use parking_lot::Mutex;
@@ -169,6 +169,7 @@ fn signed(
capabilities: vec![],
engine: "^1.0".into(),
categories: vec!["tools".into()],
icon: None,
};
(out, entry)
}
@@ -509,3 +510,25 @@ fn official_plugins_need_the_key_this_ide_was_built_with() {
let dir = f.host.download_market_plugin("openidea.hello").unwrap();
assert_eq!(f.host.preview_install(&dir).unwrap().publisher.as_deref(), Some(OFFICIAL_PUBLISHER));
}
#[test]
fn marketplace_icons_are_sanitised_or_dropped() {
let f = fixture();
let market = f.work.join("market");
std::fs::create_dir_all(&market).unwrap();
let key = PublisherKey::from_seed([3; 32]);
let (_, entry) = signed_hello(&market, "1.0.0", &key, &f.host);
let icon = |light: &str| Some(PluginIcon { light: light.into(), dark: None });
let good =
IndexEntry { icon: icon(r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#), ..entry.clone() };
let hostile = IndexEntry { id: "acme.hostile".into(), icon: icon(r#"<svg onload="x()"><rect/></svg>"#), ..entry };
let padded = format!("<svg viewBox=\"0 0 16 16\"><!--{}--><rect/></svg>", " ".repeat(20 << 10));
let padded = IndexEntry { id: "acme.padded".into(), icon: icon(&padded), ..hostile.clone() };
f.host.set_market_url(Some(write_index(&market, &key, vec![good, hostile, padded], vec![], false)));
let listed = f.host.refresh_market().unwrap();
let by_id = |id: &str| listed.iter().find(|p| p.entry.id == id).unwrap_or_else(|| panic!("{id} not listed"));
assert!(by_id("acme.hello").entry.icon.as_ref().unwrap().light.contains("<rect"));
assert!(by_id("acme.hostile").entry.icon.is_none(), "an unsafe icon is dropped, the entry stays");
assert!(by_id("acme.padded").entry.icon.is_none(), "an icon over 16 KiB is dropped before it is sanitised");
}
+12 -1
Переглянути файл
@@ -303,7 +303,18 @@ impl Smoke {
let (doc, pos) = self.locate(of).await;
let want: BTreeSet<String> = files.iter().map(|f| f.to_string()).collect();
self.retry("find usages", self.warm_up, || async {
let found = ops::lsp::lsp_references(&self.host, WINDOW, RequestId(1), doc, pos, true, true).await;
let found = ops::lsp::lsp_references(
&self.host,
WINDOW,
RequestId(1),
doc,
pos,
true,
true,
false,
ops::Channel::new(|_| {}),
)
.await;
match &found {
Ok(r) if want.is_subset(&self.files(r.locations.iter().map(|l| l.path.clone()))) => Ok(()),
_ => Err(found.map(|r| self.files(r.locations.into_iter().map(|l| l.path)))),
+1 -1
Переглянути файл
@@ -160,7 +160,7 @@ async fn light_notebooks_open_without_interpreter_detection_or_execution() {
assert!(ops::notebook::save(&host, "main", notebook.id.clone()).await.is_ok());
let error = ops::sdk::sdk_detect(&host, "main", ide_sdk::SdkKind::Python).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"));
assert!(ops::sdk::sdk_python_effective(&host, "main").is_err());
assert!(ops::sdk::sdk_python_effective(&host, "main", None).is_err());
assert!(ops::sdk::sdk_locate_tools(&host, "main", vec!["prettier".into()], Some(root)).await.is_err());
let error = ops::notebook::restart(&host, "main", notebook.id.clone()).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"));
+122
Переглянути файл
@@ -668,6 +668,7 @@ fn contribution_only_plugins() {
let theme = f.install(&theme_template());
assert_eq!(theme.status, PluginStatus::Static);
assert!(!theme.has_code);
assert!(theme.icon.is_none());
assert_eq!(f.theme_kinds("openidea.harbor-night")[0].0, "harbor-night");
let lang = f.install(&sample("language-toy"));
assert_eq!(lang.status, PluginStatus::Static);
@@ -1934,6 +1935,69 @@ fn official_csv_editor_edits_the_shared_document() {
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
}
#[test]
fn view_item_menus_name_a_declared_view() {
/// The menu is new in API 1.2.
fn api_1_2(m: &str) -> String {
m.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.2\"")
}
fn with_menu(extra: &str) -> impl Fn(&str) -> String + '_ {
move |m: &str| format!("{}\n[[contributes.menus]]\ncommand = \"word-count\"\n{extra}\n", api_1_2(m))
}
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let second_view =
"[[contributes.views]]\nid = \"more\"\ntitle = \"More\"\nicon = \"plugin\"\nlocation = \"right\"\n";
let ok = hello_variant(tmp.path(), |m| {
let on_greetings =
with_menu("menu = \"viewItem.context\"\nview = \"greetings\"\nwhen = \"viewItemKind == English\"")(m);
let on_more = with_menu("menu = \"viewItem.context\"\nview = \"more\"")("");
format!("{on_greetings}\n{second_view}\n{on_more}")
});
assert_eq!(f.install(&ok).status, PluginStatus::Inactive);
let item = f.host.ui_items("menus").into_iter().find(|i| i.decl["menu"] == "viewItem.context").unwrap();
assert_eq!(
(item.key.as_str(), item.decl["view"].as_str()),
("viewItem.context/greetings/word-count", Some("greetings"))
);
let keys: Vec<String> = f.host.ui_items("menus").into_iter().map(|i| i.key).collect();
for view in ["greetings", "more"] {
assert!(keys.contains(&format!("viewItem.context/{view}/word-count")), "{keys:?}");
}
f.host.uninstall("hello").unwrap();
for (extra, message) in [
("menu = \"viewItem.context\"", "needs `view`"),
("menu = \"viewItem.context\"\nview = \"nope\"", "view \"nope\" is not declared"),
("menu = \"projectView.context\"\nview = \"greetings\"", "`view` is only for viewItem.context"),
] {
let dir = tempfile::tempdir().unwrap();
let err = f.host.install_from_dir(&hello_variant(dir.path(), with_menu(extra)), &Consent::all()).unwrap_err();
assert!(err.message.contains(message), "{extra}: {}", err.message);
}
let dir = tempfile::tempdir().unwrap();
let web_view = "[[contributes.views]]\nid = \"page\"\ntitle = \"Page\"\nicon = \"plugin\"\nlocation = \"right\"\nweb = \"web/index.html\"\n";
let pkg = hello_variant(dir.path(), |m| {
let on_page = with_menu("menu = \"viewItem.context\"\nview = \"page\"")("");
format!("{}\n{web_view}\n{on_page}", api_1_2(m))
});
std::fs::create_dir_all(pkg.join("web")).unwrap();
std::fs::write(pkg.join("web/index.html"), "<p>hi</p>").unwrap();
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
assert!(err.message.contains("is a web view"), "{}", err.message);
let dir = tempfile::tempdir().unwrap();
let old = hello_variant(dir.path(), |m| {
format!(
"{m}\n[[contributes.menus]]\nmenu = \"viewItem.context\"\nview = \"greetings\"\ncommand = \"word-count\"\n"
)
});
let err = f.host.install_from_dir(&old, &Consent::all()).unwrap_err();
assert!(err.message.contains("new in plugin API 1.2"), "{}", err.message);
}
/// The sample plugin makes a tool window with a tree view.
/// Its menus, shortcut and status bar item are declarations, listed before
/// any code runs; the tree is rendered by the code, which loads on first show.
@@ -2610,3 +2674,61 @@ fn completion_quick_fixes_problems_and_event_kinds_of_api_1() {
let d = f.workspace.diagnostics.lock().get(&("misbehave".into(), path)).cloned().unwrap();
assert_eq!((d[0].unnecessary, d[0].deprecated, d[0].source.as_deref()), (true, false, Some("lint")));
}
/// A data-only package `id` in `dir` whose manifest ends with `extra`, plus `files`.
fn icon_package(dir: &Path, id: &str, extra: &str, files: &[(&str, &str)]) -> PathBuf {
let pkg = dir.join(id);
std::fs::create_dir_all(&pkg).unwrap();
std::fs::write(
pkg.join("plugin.toml"),
format!("id = \"{id}\"\nname = \"Iconic\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.2\"\n{extra}"),
)
.unwrap();
for (name, text) in files {
std::fs::write(pkg.join(name), text).unwrap();
}
pkg
}
const RECT: &str = r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#;
const CIRCLE: &str = r#"<svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/></svg>"#;
#[test]
fn plugin_icons_install_with_the_package() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let pkg = icon_package(
tmp.path(),
"iconic",
"icon = \"icon.svg\"\nicon-dark = \"icon_dark.svg\"\n",
&[("icon.svg", RECT), ("icon_dark.svg", CIRCLE)],
);
let info = f.install(&pkg);
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
let icon = info.icon.expect("icon");
assert!(icon.light.contains("<rect"), "{}", icon.light);
assert!(icon.dark.unwrap().contains("<circle"));
assert!(f.installed("iconic").join("icon_dark.svg").is_file());
f.host.set_enabled("iconic", false).unwrap();
assert!(f.host.info_of("iconic").unwrap().icon.is_some(), "disabled plugins keep their icon");
}
#[test]
fn invalid_plugin_icons_refuse_the_package() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let big = format!("<svg>{}</svg>", "<path d=\"M0 0h1v1z\"/>".repeat(1000));
let padded = format!("<svg><!--{}--><rect/></svg>", " ".repeat(20 << 10));
let cases = [
("scripted", "icon = \"icon.svg\"\n", "<svg><script>alert(1)</script></svg>".to_owned(), "icon.svg"),
("oversized", "icon = \"icon.svg\"\n", big, "16 KiB"),
("padded", "icon = \"icon.svg\"\n", padded, "16 KiB"),
("missing", "icon = \"missing.svg\"\n", RECT.to_owned(), "missing.svg"),
];
for (id, extra, svg, expected) in cases {
let pkg = icon_package(tmp.path(), id, extra, &[("icon.svg", &svg)]);
let err = f.host.preview_install(&pkg).map(|_| ()).unwrap_err().message;
assert!(err.contains(expected), "{id}: {err}");
}
}
+1 -1
Переглянути файл
@@ -276,7 +276,7 @@ async fn python_venv() {
// The project's virtualenv: listed first, and the interpreter the project uses.
let found = ops::sdk::sdk_detect(&p.host, WINDOW, ide_sdk::SdkKind::Python).await.unwrap();
assert_eq!(found.first().map(|s| s.source.as_str()), Some("venv"), "{found:?}");
let effective = ops::sdk::sdk_python_effective(&p.host, WINDOW).unwrap().expect("an interpreter");
let effective = ops::sdk::sdk_python_effective(&p.host, WINDOW, None).unwrap().expect("an interpreter");
assert!(effective.starts_with(p.root.join(".venv")), "{effective:?}");
}
+23
Переглянути файл
@@ -349,6 +349,29 @@ fn trusted_locations_use_canonical_directory_boundaries() {
assert_eq!(trust.status(&alias).unwrap().root.as_ref(), dunce::canonicalize(&other).unwrap());
}
#[test]
fn add_location_trusts_every_project_under_it() {
let tmp = tempfile::tempdir().unwrap();
let location = tmp.path().join("projects");
let inside = location.join("nested/deep/app");
let outside = tmp.path().join("projects-other/app");
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let file = tmp.path().join("not-a-dir");
std::fs::write(&file, "x").unwrap();
let trust = TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
trust.add_location(&location).unwrap();
assert!(trust.trusted(&inside).unwrap());
assert!(!trust.trusted(&outside).unwrap());
assert_eq!(trust.decisions().unwrap().locations.len(), 1);
trust.add_location(&location).unwrap();
assert_eq!(trust.decisions().unwrap().locations.len(), 1, "re-adding is a no-op");
assert!(trust.add_location(&file).is_err(), "a file is not a location");
assert!(trust.add_location(&tmp.path().join("missing")).is_err(), "a missing path is not a location");
let reloaded = TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
assert!(reloaded.trusted(&inside).unwrap());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn restricted_git_views_ignore_project_executables_and_mutations_cannot_run_hooks() {
+24 -1
Переглянути файл
@@ -87,12 +87,19 @@ pub fn prepare(
} else {
with_scheme(&url)
};
// Multipart bodies delimit parts with CRLF per RFC 2046 §5.1; joining
// with bare LF leaves servers (e.g. Tomcat) unable to find the boundary.
let is_multipart = headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
.is_some_and(|(_, v)| v.to_ascii_lowercase().starts_with("multipart/"));
let eol = if is_multipart { "\r\n" } else { "\n" };
Ok(PreparedRequest {
name: raw.block.name.clone(),
method: raw.block.method.clone(),
url,
headers,
body: (!body_lines.is_empty()).then(|| body_lines.join("\n")),
body: (!body_lines.is_empty()).then(|| body_lines.join(eol)),
})
}
@@ -205,6 +212,22 @@ mod tests {
assert!(err.message.contains("host"), "{}", err.message);
}
#[test]
fn multipart_bodies_join_lines_with_crlf() {
let f = parse(
"POST https://api.test/upload\nContent-Type: multipart/form-data; boundary=xyz\n\n--xyz\nfield\n--xyz--\n",
);
let p = prepare(&f.requests[0], &f.variables, &Environments::default(), None, None).unwrap();
assert_eq!(p.body.as_deref(), Some("--xyz\r\nfield\r\n--xyz--"));
}
#[test]
fn non_multipart_bodies_join_lines_with_lf() {
let f = parse("POST https://api.test/x\nContent-Type: application/json\n\n{\n\"a\": 1\n}\n");
let p = prepare(&f.requests[0], &f.variables, &Environments::default(), None, None).unwrap();
assert_eq!(p.body.as_deref(), Some("{\n\"a\": 1\n}"));
}
#[test]
fn relative_urls_use_the_host_header() {
let f = parse("GET /status\nHost: localhost:9000\n");
+91 -20
Переглянути файл
@@ -328,6 +328,9 @@ struct SourceImplementations {
/// Receives the implementations found so far, before a slower search for the rest.
type Partial<'a> = Option<&'a (dyn Fn(Vec<Location>) + Send + Sync)>;
/// Receives the references found so far, before a slower search for the rest.
pub type PartialReferences<'a> = Option<&'a (dyn Fn(References) + Send + Sync)>;
/// `first`, then those of `more` not in it (same file and start).
fn merge_locations(first: Vec<Location>, more: Vec<Location>) -> Vec<Location> {
let mut seen: HashSet<(PathBuf, Pos)> = first.iter().map(|l| (l.path.to_path_buf(), l.range.start)).collect();
@@ -1405,21 +1408,44 @@ impl LspManager {
include_declaration: bool,
project_wide: bool,
cancel: CancellationToken,
) -> IdeResult<References> {
self.references_streaming(doc, pos, include_declaration, project_wide, true, cancel, None).await
}
/// [`Self::references`]. Java, `project_wide`: without `libraries`, only the
/// workspace's sources are searched (`libraries_skipped`); with it, those found
/// there arrive on `partial` before the dependencies and the JDK are searched.
#[allow(clippy::too_many_arguments)]
pub async fn references_streaming(
&self,
doc: DocId,
pos: Pos,
include_declaration: bool,
project_wide: bool,
libraries: bool,
cancel: CancellationToken,
partial: PartialReferences<'_>,
) -> IdeResult<References> {
let snap = self.snapshot(doc)?;
// Scoped probes back code lenses and bulk analysis. Keep their native cost;
// configuration indexing is reserved for explicit, project-wide usages.
let configuration = if project_wide || snap.language.as_str() != "java" {
self.configuration_navigation(&snap, pos, true, include_declaration, &cancel).await?
} else {
None
};
if snap.language.as_str() != "java"
&& let Some(result) = configuration
&& let Some(result) = self.configuration_navigation(&snap, pos, true, include_declaration, &cancel).await?
{
return Ok(result);
}
let mut result = self.native_references(doc, pos, include_declaration, project_wide, cancel).await?;
// Scoped probes back code lenses and bulk analysis. Keep their native cost;
// configuration indexing is reserved for explicit, project-wide usages.
let configuration = async {
if project_wide && snap.language.as_str() == "java" {
self.configuration_navigation(&snap, pos, true, include_declaration, &cancel).await
} else {
Ok(None)
}
};
let native =
self.native_references(doc, pos, include_declaration, project_wide, libraries, cancel.clone(), partial);
let (configuration, result) = futures::join!(configuration, native);
let configuration = configuration?;
let mut result = result?;
if let Some(configuration) = configuration {
result.locations.extend(configuration.locations);
result.incomplete = result.incomplete.or(configuration.incomplete);
@@ -1428,13 +1454,16 @@ impl LspManager {
Ok(result)
}
#[allow(clippy::too_many_arguments)]
async fn native_references(
&self,
doc: DocId,
pos: Pos,
include_declaration: bool,
project_wide: bool,
libraries: bool,
cancel: CancellationToken,
partial: PartialReferences<'_>,
) -> IdeResult<References> {
let (snap, targets) = self.doc_targets(doc, "find references", |c| c.has("referencesProvider")).await?;
// The extension preserves method identity before JDT collapses references to locations.
@@ -1446,28 +1475,37 @@ impl LspManager {
let classified = async {
let t = &targets[0];
let extension_error = Mutex::new(None);
let query = || async {
let (snap, cancel, extension_error) = (&snap, &cancel, &extension_error);
// `sources`: the workspace's source folders only, without dependency jars and the JDK.
let query = |sources: bool| async move {
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
return Err(IdeError::cancelled());
}
let params = snap.pos_params(t, pos);
let mut arguments = json!([
params["textDocument"]["uri"],
params["position"]["line"],
params["position"]["character"],
include_declaration
]);
if sources {
arguments.as_array_mut().expect("arguments").push(json!("sources"));
}
#[derive(serde::Deserialize)]
struct JavaReference {
#[serde(default)]
access: Option<ReferenceAccess>,
location: lsp::Location,
kind: ReferenceKind,
#[serde(default)]
text: Option<String>,
}
let result: IdeResult<Vec<JavaReference>> = self
.call(
t,
"workspace/executeCommand",
json!({
"command": "openidea.java.usages",
"arguments": [params["textDocument"]["uri"], params["position"]["line"],
params["position"]["character"], include_declaration]
}),
Some(&cancel),
json!({ "command": "openidea.java.usages", "arguments": arguments }),
Some(cancel),
LONG_TIMEOUT,
)
.await;
@@ -1486,6 +1524,7 @@ impl LspManager {
location,
kind: r.kind,
access: r.access,
text: r.text,
})
})
.collect::<Vec<_>>())
@@ -1493,10 +1532,42 @@ impl LspManager {
let files = |v: &Vec<ClassifiedReference>| {
v.iter().filter(|r| r.location.uri.is_none()).map(|r| r.location.path.to_path_buf()).collect()
};
let mut libraries_skipped = false;
let widened = if project_wide {
self.widened(&snap, t, pos, &cancel, query, files).await?
// A library method has thousands of usages in the dependencies and the JDK,
// which take seconds to search: those in the sources (where scope widening
// searches again) are shown first, then the rest are searched once.
let sources = self.widened(snap, t, pos, cancel, || query(true), files).await?;
if let Some(e) = extension_error.lock().take() {
return Err(e);
}
let mut seen = std::collections::HashSet::new();
let found: Vec<_> = sources
.second
.into_iter()
.flatten()
.chain(sources.first)
.filter(|r| seen.insert(r.location.clone()))
.collect();
let all = if !libraries {
libraries_skipped = true;
Vec::new()
} else {
if let Some(partial) = partial
&& !found.is_empty()
{
partial(References {
locations: found.iter().map(|r| r.location.clone()).collect(),
classified: found.clone(),
incomplete: sources.incomplete,
libraries_skipped: false,
});
}
query(false).await?
};
scope::Widened { first: all, second: Some(found), incomplete: sources.incomplete }
} else {
let first = query().await?;
let first = query(false).await?;
let empty = first.is_empty();
scope::Widened::only(first, empty, &t.server)
};
@@ -1505,7 +1576,7 @@ impl LspManager {
return Err(IdeError::cancelled());
}
// Scope widening can retain the first answer after a failed second query.
if let Some(e) = extension_error.into_inner() {
if let Some(e) = extension_error.lock().take() {
return Err(e);
}
let mut seen = std::collections::HashSet::new();
@@ -1519,7 +1590,7 @@ impl LspManager {
.collect();
let locations: Vec<Location> = classified.iter().map(|r| r.location.clone()).collect();
self.note_virtual(&t.server, locations.iter().map(|l| l.uri.as_deref()));
Ok(References { locations, classified, incomplete: widened.incomplete })
Ok(References { locations, classified, incomplete: widened.incomplete, libraries_skipped })
}
.await;
match classified {
+8
Переглянути файл
@@ -380,6 +380,10 @@ pub struct References {
pub classified: Vec<ClassifiedReference>,
pub locations: Vec<Location>,
pub incomplete: Option<ReferencesIncomplete>,
/// The dependencies and the JDK were not searched (asked for without `libraries`).
#[serde(default)]
#[specta(optional)]
pub libraries_skipped: bool,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
@@ -503,4 +507,8 @@ pub struct ClassifiedReference {
pub access: Option<ReferenceAccess>,
pub location: Location,
pub kind: ReferenceKind,
/// The usage's line, when the server has it at hand (a library class's).
#[serde(default)]
#[specta(optional)]
pub text: Option<String>,
}
+93 -1
Переглянути файл
@@ -2882,7 +2882,8 @@ async fn classified_java_references_widen_without_losing_metadata() {
assert!(refs.classified.iter().all(|r| matches!(r.access, Some(ReferenceAccess::ReadWrite))));
assert!(refs.classified.iter().all(|r| matches!(r.kind, ReferenceKind::Field)));
assert_eq!(refs.incomplete, None);
assert_eq!(s.requested("workspace/executeCommand").len(), 3);
// Scoped; then the sources, widened; then the dependencies too.
assert_eq!(s.requested("workspace/executeCommand").len(), 4);
assert!(s.requested("textDocument/references").is_empty());
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
for limit_hit in [true, false] {
@@ -2900,6 +2901,97 @@ async fn classified_java_references_widen_without_losing_metadata() {
}
}
/// A library method's usages in the sources are shown before the dependencies and the JDK
/// are searched, which takes seconds; scope widening searches the sources alone again.
#[tokio::test(flavor = "multi_thread")]
async fn java_usages_in_the_sources_arrive_before_the_dependencies() {
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
let s = h.launcher.state("jdtls");
let library = json!({"uri": "jdt://contents/lib.jar/lib/Lib.class", "range": {
"start": {"line": 3, "character": 4}, "end": {"line": 3, "character": 10}}});
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
(method == "workspace/executeCommand").then(|| {
let sources = params["arguments"].get(4) == Some(&json!("sources"));
let mut rows: Vec<Value> = s
.docs
.lock()
.iter()
.flat_map(|(uri, text)| occurrences(uri, text))
.map(|location| json!({"location": location, "kind": "unknown"}))
.chain((!sources).then(|| json!({"location": library, "kind": "unknown", "text": " target();"})))
.collect();
rows.reverse();
Value::Array(rows)
})
}));
let b = h.root.join("b.java");
std::fs::write(&b, "target();").unwrap();
grep_candidates(&h);
let (doc, a) = h.open("a.java", "int target;");
h.wait_status("jdtls", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let partials = Mutex::new(Vec::new());
let refs = h
.mgr
.references_streaming(
doc,
Pos::new(0, 5),
true,
true,
true,
Default::default(),
Some(&|r| partials.lock().push(r)),
)
.await
.unwrap();
let partials = partials.into_inner();
assert_eq!(partials.len(), 1);
let paths =
|r: &References| r.locations.iter().map(|l| (l.path.to_path_buf(), l.uri.is_some())).collect::<Vec<_>>();
let mut shown = paths(&partials[0]);
shown.sort();
assert_eq!(shown, [(a.clone(), false), (b.clone(), false)]);
assert_eq!(partials[0].classified.len(), 2);
// All of them, those in the sources first.
assert_eq!(refs.locations.len(), 3);
assert!(refs.locations[..2].iter().all(|l| l.uri.is_none()));
assert!(refs.locations[2].uri.is_some());
// The server gives a library class's line along.
let line = |r: &References| r.classified.iter().find(|c| c.location.uri.is_some()).and_then(|c| c.text.clone());
assert_eq!(line(&refs).as_deref(), Some(" target();"));
assert!(!refs.libraries_skipped);
let scopes: Vec<_> =
s.requested("workspace/executeCommand").iter().map(|p| p["arguments"].get(4).cloned()).collect();
assert_eq!(scopes, [Some(json!("sources")), Some(json!("sources")), None]);
// Without the libraries: the sources alone, widened, and no partial answer.
let partials = Mutex::new(Vec::new());
let project = h
.mgr
.references_streaming(
doc,
Pos::new(0, 5),
true,
true,
false,
Default::default(),
Some(&|r| partials.lock().push(r)),
)
.await
.unwrap();
assert!(partials.into_inner().is_empty());
assert!(project.libraries_skipped);
assert_eq!(project.locations.len(), 2);
assert!(project.locations.iter().all(|l| l.uri.is_none()));
let scopes: Vec<_> =
s.requested("workspace/executeCommand")[3..].iter().map(|p| p["arguments"].get(4).cloned()).collect();
assert_eq!(scopes, [Some(json!("sources")), Some(json!("sources"))]);
// Scoped probes (code lenses) search everything at once.
let scoped = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(scoped.locations.len(), 2);
}
#[tokio::test(flavor = "multi_thread")]
async fn failed_java_command_falls_back_to_unclassified_native_references() {
for project_wide in [false, true] {
+182 -100
Переглянути файл
@@ -27,18 +27,51 @@ pub(crate) fn detect_with_profiles(
) -> Vec<RunConfig> {
let mut out = Vec::new();
detect_node(root, &mut out);
detect_deno(root, &mut out);
detect_cargo(root, &mut out);
detect_projects(root, &["deno.json", "deno.jsonc"], detect_deno, &mut out);
detect_projects(root, &["Cargo.toml"], detect_cargo, &mut out);
detect_gradle(root, &mut out);
detect_maven(root, excluded_poms, &mut out);
detect_go(root, &mut out);
detect_python(root, &mut out);
detect_php(root, &mut out);
detect_ruby(root, &mut out);
cmake::detect(root, profiles, &mut out);
detect_projects_matching(
root,
|dir| {
["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini", "manage.py"]
.iter()
.any(|name| dir.join(name).is_file())
|| [".venv", "venv"]
.iter()
.any(|name| dir.join(name).join(PyEnv::bin_dir()).join(PyEnv::python_exe()).is_file())
},
detect_python,
&mut out,
);
detect_projects(
root,
&["composer.json", "phpunit.xml", "phpunit.xml.dist", "phpunit.dist.xml"],
detect_php,
&mut out,
);
detect_projects_matching(root, ruby_project, detect_ruby, &mut out);
for dir in ide_core::project_roots::discover(root, &["CMakeLists.txt"]) {
let start = out.len();
cmake::detect(&dir, if dir == root { profiles } else { None }, &mut out);
if dir != root {
let scope = Scope::new(root, &dir);
for config in &mut out[start..] {
config.id = scope.id(&config.id);
config.name = scope.name(&config.name);
for task in &mut config.extras.before_launch {
if task.kind == "run" {
task.target = scope.id(&task.target);
}
}
crate::scope::rebase(config, &dir, Some(root));
}
}
}
dotnet::detect(root, &mut out);
detect_make(root, &mut out);
detect_just(root, &mut out);
detect_projects(root, &["Makefile", "makefile", "GNUmakefile"], detect_make, &mut out);
detect_projects(root, &["justfile", "Justfile", ".justfile"], detect_just, &mut out);
detect_godot(root, &mut out);
crate::external::detect(root, &mut out);
@@ -47,6 +80,80 @@ pub(crate) fn detect_with_profiles(
out
}
fn detect_projects(
root: &Path,
markers: &[&str],
detect: impl Fn(&Path, &mut Vec<RunConfig>),
out: &mut Vec<RunConfig>,
) {
detect_projects_matching(
root,
|dir| {
markers.iter().any(|marker| dir.join(marker).is_file())
&& (markers != ["Cargo.toml"] || !cargo_workspace_owns(root, dir))
},
detect,
out,
);
}
fn detect_projects_matching(
root: &Path,
marked: impl Fn(&Path) -> bool,
detect: impl Fn(&Path, &mut Vec<RunConfig>),
out: &mut Vec<RunConfig>,
) {
let mut covered = HashSet::new();
for dir in ide_core::project_roots::discover_matching(root, ide_core::project_roots::SEARCH_DEPTH, false, marked) {
if covered.contains(&dir) {
continue;
}
let mut configs = Vec::new();
detect(&dir, &mut configs);
for config in &configs {
if let Some(module) = &config.extras.module {
covered.insert(ide_core::project_roots::resolve(&dir, Path::new(module)));
}
}
if dir != root {
let scope = Scope::new(root, &dir);
for config in &mut configs {
config.id = scope.id(&config.id);
config.name = scope.name(&config.name);
for task in &mut config.extras.before_launch {
if task.kind == "run" {
task.target = scope.id(&task.target);
}
}
crate::scope::rebase(config, &dir, Some(root));
}
}
out.extend(configs);
}
}
fn cargo_workspace_owns(root: &Path, dir: &Path) -> bool {
let Some(manifest) = read_toml(&dir.join("Cargo.toml")) else { return false };
if manifest.contains_key("workspace") {
return false;
}
dir.ancestors()
.skip(1)
.take_while(|parent| parent.starts_with(root))
.find_map(|parent| {
let manifest = read_toml(&parent.join("Cargo.toml"))?;
let workspace = manifest.get("workspace")?;
let excluded = string_list(workspace.get("exclude"));
Some(
!excluded.iter().any(|excluded| dir.starts_with(parent.join(excluded)))
&& !expand_members(parent, &excluded, "Cargo.toml")
.iter()
.any(|excluded| dir.starts_with(excluded)),
)
})
.unwrap_or(false)
}
fn config(id: impl Into<String>, name: impl Into<String>, kind: &str, command: &str, args: &[&str]) -> RunConfig {
RunConfig {
id: id.into(),
@@ -103,19 +210,7 @@ fn first_existing(root: &Path, names: &[&str]) -> Option<PathBuf> {
/// Sorted immediate subdirectories, skipping hidden and vendored ones.
fn subdirs(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = fs::read_dir(dir) else { return Vec::new() };
let mut dirs: Vec<PathBuf> = entries
.filter_map(Result::ok)
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.filter(|e| {
let name = e.file_name();
let name = name.to_string_lossy();
!name.starts_with('.') && !matches!(name.as_ref(), "node_modules" | "target" | "build" | "dist" | "vendor")
})
.map(|e| e.path())
.collect();
dirs.sort();
dirs
ide_core::project_roots::children(dir)
}
/// Expands workspace member patterns one level deep: `dir`, `dir/*`, `dir/**`.
@@ -151,25 +246,8 @@ fn relative(root: &Path, dir: &Path) -> PathBuf {
// ---------------------------------------------------------------- node
pub(crate) fn package_manager(root: &Path, pkg: &Json) -> &'static str {
if let Some(pm) = pkg.get("packageManager").and_then(Json::as_str) {
match pm.split('@').next().unwrap_or_default() {
"pnpm" => return "pnpm",
"yarn" => return "yarn",
"bun" => return "bun",
"npm" => return "npm",
_ => {}
}
}
if root.join("pnpm-lock.yaml").is_file() {
"pnpm"
} else if root.join("yarn.lock").is_file() {
"yarn"
} else if root.join("bun.lock").is_file() || root.join("bun.lockb").is_file() {
"bun"
} else {
"npm"
}
pub(crate) fn package_manager(root: &Path, _pkg: &Json) -> &'static str {
ide_core::project_roots::package_manager(root)
}
pub(crate) fn is_test_script(name: &str) -> bool {
@@ -186,6 +264,7 @@ fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option<PathBuf>
None => (format!("npm:{script}"), format!("{pm} run {script}")),
};
let mut c = config(id, name, "npm", pm, &["run", script]).in_dir(cwd.clone()).debug("js-debug");
c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc);
if is_test_script(script) {
c = c.test();
}
@@ -221,27 +300,34 @@ fn node_workspace_patterns(root: &Path, pkg: &Json) -> Vec<String> {
}
fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
let Some(pkg) = read_json(&root.join("package.json")) else {
// A polyglot repository: front-end packages one level down (`web/`, `frontend/`).
for dir in subdirs(root) {
let Some(member) = read_json(&dir.join("package.json")) else { continue };
let rel = relative(root, &dir);
let label = rel.to_string_lossy().replace('\\', "/");
push_scripts(&member, package_manager(&dir, &member), Some(&label), Some(rel), out);
let mut covered = HashSet::new();
let projects =
ide_core::project_roots::discover_matching(root, ide_core::project_roots::SEARCH_DEPTH, false, |dir| {
dir.join("package.json").is_file()
});
for dir in projects {
if !covered.insert(dir.clone()) {
continue;
}
return;
};
let pm = package_manager(root, &pkg);
push_scripts(&pkg, pm, None, None, out);
for dir in expand_members(root, &node_workspace_patterns(root, &pkg), "package.json") {
let Some(member) = read_json(&dir.join("package.json")) else { continue };
let Some(pkg) = read_json(&dir.join("package.json")) else { continue };
let pm = package_manager(&dir, &pkg);
let rel = relative(root, &dir);
let label = member
.get("name")
.and_then(Json::as_str)
.map(str::to_owned)
.unwrap_or_else(|| rel.to_string_lossy().replace('\\', "/"));
push_scripts(&member, pm, Some(&label), Some(rel), out);
let label = ide_core::ipc_path::to_ipc(&rel);
push_scripts(&pkg, pm, (dir != root).then_some(label.as_str()), (dir != root).then_some(rel), out);
for member_dir in expand_members(&dir, &node_workspace_patterns(&dir, &pkg), "package.json") {
if !covered.insert(member_dir.clone()) {
continue;
}
let Some(member) = read_json(&member_dir.join("package.json")) else { continue };
let rel = relative(root, &member_dir);
let name = member
.get("name")
.and_then(Json::as_str)
.map(str::to_owned)
.unwrap_or_else(|| ide_core::ipc_path::to_ipc(&rel));
let name = if dir == root { name } else { format!("{label}:{name}") };
push_scripts(&member, pm, Some(&name), Some(rel), out);
}
}
}
@@ -355,12 +441,31 @@ fn detect_cargo(root: &Path, out: &mut Vec<RunConfig>) {
} else {
format!("cargo:run:{pkg}:{bin}")
};
out.push(config(id, format!("cargo run {bin}"), "cargo", "cargo", &args).debug("codelldb"));
let mut run = config(id, format!("cargo run {bin}"), "cargo", "cargo", &args).debug("codelldb");
if dir != root {
run.extras.module = Some(ide_core::ipc_path::to_ipc(&relative(root, dir)));
}
out.push(run);
}
}
if packages.is_empty() && !is_workspace {
return;
}
if is_workspace {
for (pkg, dir, _) in &packages {
let mut test = config(
format!("cargo:test:{pkg}"),
format!("cargo test {pkg}"),
"cargo",
"cargo",
&["test", "-p", pkg],
)
.test()
.debug("codelldb");
test.extras.module = Some(ide_core::ipc_path::to_ipc(&relative(root, dir)));
out.push(test);
}
}
let ws_flag: &[&str] = if is_workspace { &["--workspace"] } else { &[] };
let test_args: Vec<&str> = ["test"].iter().chain(ws_flag).copied().collect();
let build_args: Vec<&str> = ["build"].iter().chain(ws_flag).copied().collect();
@@ -410,32 +515,8 @@ fn applies_application_plugin(text: &str) -> bool {
})
}
/// How deep a build is looked for when the project root has none (a folder holding
/// several repositories: `backend/pom.xml`, `apps/server/settings.gradle`).
const NESTED_BUILD_DEPTH: usize = 3;
/// The builds marked by any of `markers`: the root itself, else the shallowest marked
/// folder of each branch, up to [`NESTED_BUILD_DEPTH`] levels down.
fn build_dirs(root: &Path, markers: &[&str]) -> Vec<PathBuf> {
let marked = |d: &Path| markers.iter().any(|m| d.join(m).is_file());
if marked(root) {
return vec![root.to_path_buf()];
}
let mut out = Vec::new();
let mut level = vec![root.to_path_buf()];
for _ in 0..NESTED_BUILD_DEPTH {
let mut next = Vec::new();
for sub in level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src") && !d.ends_with("out")) {
if marked(&sub) {
out.push(sub);
} else {
next.push(sub);
}
}
level = next;
}
out.sort();
out
ide_core::project_roots::discover(root, markers)
}
/// Ids, names and working directory of the configurations of a build nested in
@@ -546,7 +627,7 @@ fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
let mut budget = SPRING_SCAN_FILES;
let mut modules = vec![build.to_path_buf()];
let mut level = vec![build.to_path_buf()];
for _ in 0..NESTED_BUILD_DEPTH {
for _ in 0..ide_core::project_roots::SEARCH_DEPTH {
level = level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src")).collect();
modules.extend(level.iter().cloned());
}
@@ -708,16 +789,11 @@ fn detect_go(root: &Path, out: &mut Vec<RunConfig>) {
}
return;
}
if root.join("go.mod").is_file() {
detect_go_module(root, None, out);
return;
}
// A polyglot repository: Go modules one level down (`api/go.mod`).
for dir in subdirs(root) {
if dir.join("go.mod").is_file() {
let rel = relative(root, &dir);
detect_go_module(&dir, Some(rel), out);
}
for dir in ide_core::project_roots::discover_matching(root, ide_core::project_roots::SEARCH_DEPTH, false, |dir| {
dir.join("go.mod").is_file()
}) {
let rel = relative(root, &dir);
detect_go_module(&dir, (!rel.as_os_str().is_empty()).then_some(rel), out);
}
}
@@ -1069,14 +1145,18 @@ fn uses_rspec(root: &Path) -> bool {
|| read(&root.join("Gemfile")).is_some_and(|g| g.contains("rspec"))
}
fn detect_ruby(root: &Path, out: &mut Vec<RunConfig>) {
fn ruby_project(root: &Path) -> bool {
let markers = ["Gemfile", "Rakefile", "rakefile", "Rakefile.rb", ".ruby-version", "config.ru"];
let gemspec = fs::read_dir(root)
.into_iter()
.flatten()
.flatten()
.any(|e| e.path().extension().is_some_and(|x| x == "gemspec"));
if !gemspec && !markers.iter().any(|m| root.join(m).is_file()) {
gemspec || markers.iter().any(|m| root.join(m).is_file())
}
fn detect_ruby(root: &Path, out: &mut Vec<RunConfig>) {
if !ruby_project(root) {
return;
}
if root.join("bin/rails").is_file() {
@@ -1217,8 +1297,10 @@ pub(crate) fn just_recipes(src: &str) -> Vec<String> {
/// Godot projects (`project.godot`) at the root or one level down: "Godot Project"
/// runs the main scene (`godot --path .`), debuggable through the editor's adapter.
fn detect_godot(root: &Path, out: &mut Vec<RunConfig>) {
let dirs = std::iter::once(root.to_path_buf()).chain(subdirs(root));
for dir in dirs.filter(|d| d.join("project.godot").is_file()) {
let dirs = ide_core::project_roots::discover_matching(root, ide_core::project_roots::SEARCH_DEPTH, false, |dir| {
dir.join("project.godot").is_file()
});
for dir in dirs {
let rel = relative(root, &dir);
let (id, name, cwd) = if rel.as_os_str().is_empty() {
("godot:project".to_owned(), "Godot Project".to_owned(), None)
+3 -1
Переглянути файл
@@ -14,6 +14,7 @@ mod process;
pub mod python_path;
pub mod ruby_preload;
pub mod ruby_reporter;
pub mod scope;
pub mod tomcat;
mod utf8;
pub mod which;
@@ -76,7 +77,8 @@ fn is_true(b: &bool) -> bool {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RunExtras {
/// Module supplying a JVM application's classpath; empty means the project root.
/// Owning module, independent of the working directory; also supplies a JVM application's classpath.
/// Empty means the project root.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub module: Option<String>,
+125
Переглянути файл
@@ -0,0 +1,125 @@
//! A configuration's module and relative paths move together when projects are nested.
use crate::RunConfig;
use ide_core::{ipc_path::to_ipc, project_roots};
use std::path::{Path, PathBuf};
pub fn owner(root: &Path, config: &RunConfig) -> PathBuf {
if matches!(config.kind.as_str(), "dotnet" | "dotnet-test")
&& let Some(project) = config.extras.params.get("project").filter(|p| !p.is_empty())
{
return project_roots::resolve(root, Path::new(project)).parent().unwrap_or(root).to_path_buf();
}
let module = (config.kind == "go")
.then(|| config.extras.params.get("module"))
.flatten()
.map(String::as_str)
.or(config.extras.module.as_deref())
.map(Path::new)
.or(config.cwd.as_deref())
.unwrap_or(Path::new(""));
project_roots::resolve(root, module)
}
pub fn rebase(config: &mut RunConfig, from: &Path, relative_to: Option<&Path>) {
let path = |value: &str| {
let absolute = project_roots::resolve(from, Path::new(value));
to_ipc(&relative_to.map_or(absolute.clone(), |root| project_roots::relative(root, &absolute)))
};
let cwd = config.cwd.as_deref().unwrap_or(Path::new("")).to_path_buf();
config.cwd = Some(path(&to_ipc(&cwd)).into());
if config.extras.module.is_some() || !matches!(config.kind.as_str(), "application" | "spring-boot") {
config.extras.module = Some(path(config.extras.module.as_deref().unwrap_or("")));
}
if config.kind == "go" && config.extras.params.contains_key("goKind") {
config.extras.params.entry("module".into()).or_default();
}
for file in &mut config.extras.env_files {
*file = path(file);
}
for file in [&mut config.extras.stdin_file, &mut config.extras.output_file].into_iter().flatten() {
*file = path(file);
}
let keys: &[&str] = match config.kind.as_str() {
"go" => &["module", "outputDir"],
"dotnet" | "dotnet-test" => &["project", "targetPath"],
_ => &[],
};
for key in keys {
if let Some(value) = config.extras.params.get_mut(*key)
&& (*key == "module" || !value.is_empty())
{
*value = path(value);
}
}
if !matches!(config.kind.as_str(), "shell" | "compound") && Path::new(&config.command).components().count() > 1 {
// Executables are relative to the old cwd, unlike env/input/output files.
let cwd = project_roots::resolve(from, &cwd);
config.command = to_ipc(&project_roots::resolve(&cwd, Path::new(&config.command)));
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn default_go_module_moves_with_member_but_unknown_jvm_module_stays_inferred() {
let temp = tempfile::tempdir().unwrap();
for (kind, params) in
[("go", serde_json::json!({"goKind":"build", "target":"."})), ("application", serde_json::json!({}))]
{
let mut config: RunConfig = serde_json::from_value(serde_json::json!({
"id":"run", "name":"run", "kind":kind, "command":"tool", "args":[], "cwd":null,
"env":{}, "detected":false, "isTest":false, "debugAdapter":null, "params":params
}))
.unwrap();
rebase(&mut config, temp.path(), None);
if kind == "go" {
assert_eq!(config.extras.params["module"], to_ipc(temp.path()));
} else {
assert_eq!(config.extras.module, None);
}
}
}
#[test]
fn workspace_members_rebase_every_typed_root_without_changing_targets() {
let temp = tempfile::tempdir().unwrap();
let member = temp.path().join("member with spaces");
for (kind, params) in [
("application", BTreeMap::<String, String>::new()),
(
"go",
BTreeMap::from([
("module".into(), "api".into()),
("target".into(), "./cmd/server".into()),
("outputDir".into(), "bin".into()),
]),
),
("dotnet", BTreeMap::from([("project".into(), "src/App.csproj".into())])),
] {
let mut config: RunConfig = serde_json::from_value(serde_json::json!({
"id":"run", "name":"run", "kind":kind, "command":"tool", "args":["unchanged"], "cwd":null,
"env":{}, "detected":true, "isTest":false, "debugAdapter":null,
"module":"app", "params":params, "envFiles":[".env"], "stdinFile":"input.txt", "outputFile":"out/result.txt"
})).unwrap();
rebase(&mut config, &member, None);
assert_eq!(config.cwd.as_deref(), Some(member.as_path()));
assert_eq!(config.extras.module.as_deref(), Some(to_ipc(&member.join("app")).as_str()));
assert_eq!(config.extras.env_files, [to_ipc(&member.join(".env"))]);
assert_eq!(config.extras.stdin_file, Some(to_ipc(&member.join("input.txt"))));
assert_eq!(config.extras.output_file, Some(to_ipc(&member.join("out/result.txt"))));
assert_eq!(config.args, ["unchanged"]);
if kind == "go" {
assert_eq!(config.extras.params["module"], to_ipc(&member.join("api")));
assert_eq!(config.extras.params["outputDir"], to_ipc(&member.join("bin")));
assert_eq!(config.extras.params["target"], "./cmd/server");
}
if kind == "dotnet" {
assert_eq!(config.extras.params["project"], to_ipc(&member.join("src/App.csproj")));
}
}
}
}
+125 -5
Переглянути файл
@@ -131,9 +131,25 @@ fn cargo_workspace() {
("cli/src/main.rs", ""),
]);
let c = detect(dir.path());
assert_eq!(ids(&c), ["cargo:run:openidea-cli", "cargo:test", "cargo:build"]);
assert_eq!(
ids(&c),
[
"cargo:run:openidea-cli",
"cargo:test:core",
"cargo:test:openidea-cli",
"cargo:test",
"cargo:build",
"cargo:run:skip:crates/skip",
"cargo:test:crates/skip",
"cargo:build:crates/skip"
]
);
assert_eq!(cmdline(&c[0]), "cargo run -p openidea-cli --bin openidea-cli");
assert_eq!(cmdline(find(&c, "cargo:test")), "cargo test --workspace");
let test = find(&c, "cargo:test:core");
assert_eq!(test.extras.module.as_deref(), Some("crates/core"));
assert_eq!(cmdline(test), "cargo test -p core");
assert_eq!(find(&c, "cargo:run:skip:crates/skip").cwd.as_deref(), Some(Path::new("crates/skip")));
}
#[test]
@@ -300,7 +316,22 @@ fn nested_builds_of_every_kind_and_depth() {
assert_eq!((billing.cwd.as_deref(), billing.extras.module.as_deref()), (None, Some("billing")));
let builds: Vec<&str> =
ids(&c).into_iter().filter(|id| id.starts_with("maven:package") || id.starts_with("gradle:build")).collect();
assert_eq!(builds, ["gradle:build:services/api", "maven:package:billing"]);
assert_eq!(builds, ["gradle:build:services/api", "maven:package:billing", "maven:package:tool/src"]);
let model = ide_build::load(dir.path(), &dir.path().join("cache"), None);
for config in c.iter().filter(|c| c.kind == "gradle") {
let cwd = config.cwd.as_deref().unwrap();
assert!(model.gradle.iter().any(|g| Path::new(&g.dir) == cwd), "{} has no build model", config.id);
}
let plan = ide_build::compile::plan(
dir.path(),
&model,
ide_build::compile::BuildKind::Build,
Some(&dir.path().join("services/api/app/src/main/kotlin/com/acme/Api.kt")),
None,
)
.unwrap();
assert_eq!(plan.steps[0].cwd, dir.path().join("services/api"));
assert_eq!(plan.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
}
#[test]
@@ -362,6 +393,49 @@ fn go_projects() {
assert_eq!(ids(&detect(dir.path())), ["go:test"]);
}
#[test]
fn nested_go_modules_keep_their_working_directories() {
let dir = project(&[
("Cargo.toml", "[package]\nname = 'workspace'\n"),
("fixtures/go-app/go.mod", "module example.com/openidea/notes\n"),
("fixtures/go-app/cmd/server/main.go", "package main\nfunc main() {}\n"),
("services/backend/api/go.mod", "module example.com/api\n"),
("services/backend/api/main.go", "package main\nfunc main() {}\n"),
("fixtures/go-app/nested/go.mod", "module ignored\n"),
("vendor/ignored/go.mod", "module ignored\n"),
("node_modules/ignored/go.mod", "module ignored\n"),
("target/ignored/go.mod", "module ignored\n"),
("build/ignored/go.mod", "module ignored\n"),
("dist/ignored/go.mod", "module ignored\n"),
(".hidden/ignored/go.mod", "module ignored\n"),
]);
let configs = detect(dir.path());
let go: Vec<_> = configs.iter().filter(|c| c.kind == "go").map(|c| c.id.as_str()).collect();
assert_eq!(
go,
[
"go:run:server:fixtures/go-app",
"go:test:fixtures/go-app",
"go:test:fixtures/go-app/nested",
"go:run:services/backend/api",
"go:test:services/backend/api",
]
);
let run = find(&configs, "go:run:server:fixtures/go-app");
assert_eq!(cmdline(run), "go run ./cmd/server");
assert_eq!(run.cwd.as_deref(), Some(Path::new("fixtures/go-app")));
let test = find(&configs, "go:test:services/backend/api");
assert_eq!(test.cwd.as_deref(), Some(Path::new("services/backend/api")));
}
#[cfg(unix)]
#[test]
fn nested_go_discovery_does_not_follow_symlinks() {
let dir = project(&[("real/go.mod", "module real\n")]);
std::os::unix::fs::symlink(dir.path().join("real"), dir.path().join("alias")).unwrap();
assert_eq!(ids(&detect(dir.path())), ["go:test:real"]);
}
#[test]
fn python_projects() {
let dir = project(&[
@@ -545,7 +619,7 @@ fn nested_packages_in_polyglot_repo() {
}
#[test]
fn root_package_disables_nested_scan() {
fn independent_packages_remain_visible_under_a_root_package() {
let dir = project(&[
("package.json", r#"{"scripts":{"build":"tsc"}}"#),
("tools/package.json", r#"{"scripts":{"gen":"x"}}"#),
@@ -553,9 +627,9 @@ fn root_package_disables_nested_scan() {
("svc/go.mod", "module y\n"),
]);
let c = detect(dir.path());
assert!(!ids(&c).contains(&"npm:tools:gen"));
assert!(ids(&c).contains(&"npm:tools:gen"));
assert!(ids(&c).contains(&"go:test"));
assert!(!ids(&c).contains(&"go:test:svc"));
assert!(ids(&c).contains(&"go:test:svc"));
}
#[test]
@@ -847,3 +921,49 @@ fn ruby_without_bundler_runs_bare_tools() {
assert_eq!(cmdline(&c[0]), "rake test");
assert!(detect(project(&[("a.rb", "puts 1\n")]).path()).is_empty());
}
#[test]
fn all_builtin_families_find_independent_nested_projects_and_keep_owners() {
let cases = [
("package.json", r#"{"scripts":{"test":"vitest"}}"#, "npm"),
("deno.json", r#"{"tasks":{"test":"deno test"}}"#, "deno"),
("Cargo.toml", "[package]\nname='demo'\nversion='0.1.0'\n[workspace]", "cargo"),
("go.mod", "module demo", "go"),
("pom.xml", "<project/>", "maven"),
("build.gradle.kts", "plugins { application }", "gradle"),
("pyproject.toml", "[tool.pytest.ini_options]", "pytest"),
("phpunit.xml", "<phpunit/>", "phpunit"),
("Rakefile.rb", "task :test do\nend", "rake"),
("CMakeLists.txt", "project(demo)", "cmake"),
("Makefile", "test:\n\techo ok", "make"),
("justfile", "test:\n echo ok", "just"),
("project.godot", "[application]\nrun/main_scene=\"res://main.tscn\"", "godot"),
];
for (marker, text, kind) in cases {
let dir = project(&[
("package.json", r#"{"scripts":{"build":"echo root"}}"#),
(&format!("packages/apps/demo/{marker}"), text),
]);
let configs = detect(dir.path());
let found: Vec<_> = configs
.iter()
.filter(|c| c.kind == kind && c.cwd.as_deref() == Some(Path::new("packages/apps/demo")))
.collect();
assert!(!found.is_empty(), "{kind}: {configs:?}");
for c in found {
// JVM and Go configs already identify ownership through cwd / their typed model.
if !matches!(kind, "gradle" | "maven" | "go" | "godot") {
assert_eq!(c.extras.module.as_deref(), Some("packages/apps/demo"));
}
}
}
}
#[test]
fn cmake_subdirectories_are_not_independent_builds() {
let dir = project(&[
("CMakeLists.txt", "project(demo)\nadd_subdirectory(lib)"),
("lib/CMakeLists.txt", "add_library(lib lib.cpp)"),
]);
assert!(detect(dir.path()).iter().filter(|c| c.kind == "cmake").all(|c| c.cwd.is_none()));
}
+24
Переглянути файл
@@ -529,6 +529,30 @@ fn revoking_one_project_stops_only_its_runs() {
h.pm.stop(theirs.id).unwrap();
}
/// Quitting the app kills what every project's runs started, forked children included (#1691).
#[test]
fn kill_all_stops_every_projects_process_trees() {
let h = harness();
let other = tempfile::tempdir().unwrap();
let (mine, chunks) = start(&h, &cfg("mine", "/bin/sh", &["-c", "sleep 30 & echo $!; wait"]));
let grandchild: i32 = wait_for(&chunks, "\n").trim().parse().expect("pid");
let theirs =
h.pm.start(
other.path(),
&cfg("theirs", "/bin/sh", &["-c", "sleep 30"]),
&StartOptions::default(),
h.sink.clone(),
Box::new(|_| {}),
)
.unwrap();
h.pm.kill_all();
let deadline = Instant::now() + Duration::from_secs(8);
while alive(grandchild) || h.pm.list().iter().any(|r| (r.id == mine || r.id == theirs.id) && r.running) {
assert!(Instant::now() < deadline, "a run survived kill_all");
std::thread::sleep(Duration::from_millis(50));
}
}
#[test]
#[ignore = "requires CMake, CTest and a C++ compiler"]
fn cmake_configure_discovers_builds_and_runs_a_multifile_target() {
+221 -15
Переглянути файл
@@ -11,6 +11,7 @@ use ide_core::{IdeError, IdeResult};
use ide_language::{LanguageConfig, LanguageServerConfig};
use ide_run::RunConfig;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
@@ -70,6 +71,18 @@ pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_python(root))
}
/// An explicit project interpreter wins; otherwise use the closest virtualenv to the file.
pub fn python_interpreter_near(root: &Path, near: Option<&Path>, s: &Settings) -> Option<PathBuf> {
if let Some(python) = setting_path(root, &s.languages.python.interpreter) {
return Some(python);
}
let near = near.filter(|dir| dir.starts_with(root)).unwrap_or(root);
near.ancestors()
.take_while(|dir| dir.starts_with(root))
.find_map(project_venv_python)
.or_else(|| pinned::pinned_python(near))
}
/// The project Ruby: the configured one, else the `.ruby-version` / mise / asdf
/// install, else `ruby` on PATH.
pub fn ruby_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
@@ -245,6 +258,103 @@ fn resolve_gradle_command(root: &Path, build_dir: &Path, s: &Settings, use_wrapp
.unwrap_or_else(|| name.into())
}
fn gradle_run_jdk<'a>(
release: Option<u32>,
configured: Option<&'a crate::java::Jdk>,
installed: &'a [crate::java::Jdk],
gradle: Option<(u32, u32)>,
) -> Option<&'a crate::java::Jdk> {
configured.or_else(|| {
let release = release?;
// An unknown Gradle version cannot narrow the choice: the release alone decides.
let Some(gradle) = gradle else { return crate::java::pick_jdk(installed, Some(release)) };
let compatible: Vec<_> = installed.iter().filter(|jdk| gradle_supports_java(gradle, jdk.major)).collect();
compatible
.iter()
.copied()
.find(|jdk| jdk.major == release)
.or_else(|| compatible.iter().copied().filter(|jdk| jdk.major > release).min_by_key(|jdk| jdk.major))
.or_else(|| compatible.iter().copied().max_by_key(|jdk| jdk.major))
})
}
/// Default environment shared by Gradle model builds and Run configurations.
pub fn gradle_build_env(
root: &Path,
build_dir: &Path,
command: &str,
settings: &Settings,
release: Option<u32>,
) -> std::collections::BTreeMap<String, String> {
let configured = project_jdk(root, settings);
let installed = crate::java::installed_jdks();
let jdk = gradle_run_jdk(
release.or_else(|| crate::java::project_java_version(build_dir)),
configured.as_ref(),
&installed,
gradle_distribution_version(build_dir, command),
);
let env = jdk
.map(|jdk| std::collections::BTreeMap::from([("JAVA_HOME".into(), jdk.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
gradle_env(root, settings, env)
}
fn gradle_supports_java(gradle: (u32, u32), java: u32) -> bool {
// https://docs.gradle.org/current/userguide/compatibility.html#java_runtime
let minimum = match java {
8 => (2, 0),
9 => (4, 3),
10 => (4, 7),
11 => (5, 0),
12 => (5, 4),
13 => (6, 0),
14 => (6, 3),
15 => (6, 7),
16 => (7, 0),
17 => (7, 3),
18 => (7, 5),
19 => (7, 6),
20 => (8, 3),
21 => (8, 5),
22 => (8, 8),
23 => (8, 10),
24 => (8, 14),
25 => (9, 1),
26 => (9, 4),
27 => (9, 8),
_ => return false,
};
gradle >= minimum && (java >= 17 || gradle < (9, 0))
}
fn gradle_distribution_version(build_dir: &Path, command: &str) -> Option<(u32, u32)> {
let version = |text: &str| {
let mut parts = text.split('.');
Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?))
};
if Path::new(command).file_stem().is_some_and(|name| name == "gradlew") {
let properties = std::fs::read_to_string(build_dir.join("gradle/wrapper/gradle-wrapper.properties")).ok()?;
let url = properties.lines().find_map(|line| line.trim().strip_prefix("distributionUrl="))?;
return version(url.rsplit_once("gradle-")?.1.split('-').next()?);
}
let path = Path::new(command);
let path = if path.is_absolute() { path.to_path_buf() } else { crate::exec::which(command)? };
let path = dunce::canonicalize(path).ok()?;
let home = path.parent()?.parent()?;
for lib in [home.join("lib"), home.join("libexec/lib")] {
let Ok(entries) = std::fs::read_dir(lib) else { continue };
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if let Some(v) = name.strip_prefix("gradle-launcher-").and_then(|name| name.strip_suffix(".jar")) {
return version(v);
}
}
}
None
}
/// Gradle JVM overrides Project JDK; model callers supply the module's fallback environment.
pub fn gradle_env(
root: &Path,
@@ -688,6 +798,22 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
json!({ "settings": { "java": { "configuration": { "maven": { "userSettings": file } } } } }),
);
}
// m2e resolves and downloads into `maven.repo.local`; without it the
// embedded Maven falls back to ~/.m2 even when the IDE's own `mvn`
// runs honor the configured local repository. A `-Dmaven.repo.local`
// the user put in their own jdtls VM options wins.
if let Some(repo) = maven_local_repository(root, s) {
let arg = format!("-Dmaven.repo.local={}", repo.to_string_lossy());
let taken = cfg.args.iter().enumerate().any(|(i, a)| {
let value = a
.strip_prefix("--jvm-arg=")
.or_else(|| (i > 0 && cfg.args[i - 1] == "--jvm-arg").then_some(a.as_str()));
value.is_some_and(|a| a.split('=').next() == Some("-Dmaven.repo.local"))
});
if !taken {
cfg.args.push(format!("--jvm-arg={arg}"));
}
}
}
if let Some(lib) = tsdk(server_root, s).or_else(|| tsdk(root, s)) {
@@ -948,19 +1074,38 @@ fn add_maven_options(args: &mut Vec<String>, options: &[String]) {
/// (and Maven the configured home and options).
pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings) {
let explicit_python = setting_path(root, &s.languages.python.interpreter);
let python = python_interpreter(root, s);
let pm = non_empty(&s.languages.node.package_manager);
let node = node_dir(root, s);
let php = setting_path(root, &s.languages.php.interpreter);
let rust = rust_bin(root, s);
let go = goroot(root, s);
let gopath = setting_path(root, &s.languages.go.gopath);
let jdk = project_jdk(root, s);
let mvn = maven_command(root, s);
let mvn_options = maven_options(root, s);
let ruby = ruby_interpreter(root, s);
// Module-local toolchains, looked up once per owning module and only for the kinds using them.
let mut toolchains: HashMap<(&'static str, PathBuf), Option<PathBuf>> = HashMap::new();
let mut toolchain = |tool: &'static str, owner: &Path| {
toolchains
.entry((tool, owner.to_path_buf()))
.or_insert_with(|| {
// A module outside the project (an external linked build) keeps the project's choices.
let near = if owner.starts_with(root) { owner } else { root };
match tool {
"python" => python_interpreter_near(root, Some(near), s),
"node" if non_empty(&s.languages.node.interpreter).is_none() => {
node_dir(near, s).or_else(|| node_dir(root, s))
}
"node" => node_dir(root, s),
"go" if non_empty(&s.languages.go.goroot).is_none() => goroot(near, s).or_else(|| goroot(root, s)),
"go" => goroot(root, s),
_ => setting_path(root, &s.languages.ruby.interpreter).or_else(|| ruby_interpreter(near, s)),
}
})
.clone()
};
for c in configs.iter_mut() {
let owner = ide_run::scope::owner(root, c);
resolve_run_command(c, root, s);
let mut path_dirs: Vec<PathBuf> = Vec::new();
match c.kind.as_str() {
@@ -984,6 +1129,7 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
c.args = ["-m".to_owned(), "pytest".to_owned()].into_iter().chain(rest).collect();
}
}
let python = toolchain("python", &owner);
if let Some(venv) = python.as_deref().and_then(venv_of)
&& !c.env.contains_key("VIRTUAL_ENV")
{
@@ -991,8 +1137,9 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
path_dirs.push(venv.join(bin_dir()));
}
}
"npm" => {
"npm" | "node" | "deno" | "bun" => {
if let Some(pm) = pm
&& c.kind == "npm"
&& c.detected
&& matches!(c.command.as_str(), "npm" | "pnpm" | "yarn" | "bun")
{
@@ -1000,7 +1147,9 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
}
// The configuration's own Node interpreter, else the project's.
let own = c.extras.params.get("nodeInterpreter").and_then(|p| setting_path(root, p));
if let Some(dir) = own.and_then(|p| p.parent().map(Path::to_path_buf)).or_else(|| node.clone()) {
if let Some(dir) =
own.and_then(|p| p.parent().map(Path::to_path_buf)).or_else(|| toolchain("node", &owner))
{
path_dirs.push(dir);
}
}
@@ -1027,7 +1176,7 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
for (key, value) in crate::go::module_environment(root, &s.languages.go.modules) {
c.env.entry(key).or_insert(value);
}
if let Some(goroot) = &go {
if let Some(goroot) = &toolchain("go", &owner) {
let bin = goroot.join("bin");
if c.command == "go" && bin.join(exe("go")).is_file() {
c.command = bin.join(exe("go")).to_string_lossy().into_owned();
@@ -1044,18 +1193,12 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
if matches!(c.command.as_str(), "gradle" | "gradle.bat") {
c.command = resolve_gradle_command(root, &build_dir, s, false).to_string_lossy().into_owned();
}
let defaults = jdk
.as_ref()
.map(|j| {
std::collections::BTreeMap::from([("JAVA_HOME".into(), j.home.to_string_lossy().into_owned())])
})
.unwrap_or_default();
for (key, value) in gradle_env(root, s, defaults) {
for (key, value) in gradle_build_env(root, &build_dir, &c.command, s, None) {
c.env.entry(key).or_insert(value);
}
}
"ruby" | "rake" | "rspec" => {
if let Some(ruby) = &ruby
if let Some(ruby) = &toolchain("ruby", &owner)
&& let Some(bin) = crate::ruby::bin_dir_of(ruby)
{
// `ruby`, `bundle`, `rake`, `rspec` of the chosen interpreter when installed
@@ -1302,6 +1445,69 @@ mod java_compiler_tests {
}
}
#[cfg(test)]
mod gradle_runtime_tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn gradle_runs_use_the_builds_toolchain_without_overriding_user_choices() {
let temp = tempfile::tempdir().unwrap();
let installed =
[25, 21, 17, 11, 8].map(|major| crate::java::Jdk { major, home: temp.path().join(format!("jdk{major}")) });
for (name, script, expected) in [
("kotlin", "kotlin { jvmToolchain(21) }", Some(21)),
("java", "java { toolchain { languageVersion = JavaLanguageVersion.of(17) } }", Some(17)),
("unspecified", "plugins { id 'java' }", None),
] {
let dir = temp.path().join(name);
std::fs::create_dir(&dir).unwrap();
std::fs::write(dir.join("build.gradle.kts"), script).unwrap();
let picked = gradle_run_jdk(crate::java::project_java_version(&dir), None, &installed, Some((9, 0)));
assert_eq!(picked.map(|jdk| jdk.major), expected);
assert_eq!(gradle_run_jdk(expected, Some(&installed[0]), &installed, Some((9, 0))), Some(&installed[0]));
let mut settings = Settings::default();
settings.languages.java.gradle.jvm = "custom-gradle-jdk".into();
let env = gradle_env(temp.path(), &settings, BTreeMap::from([("JAVA_HOME".into(), "/fallback".into())]));
assert_eq!(env["JAVA_HOME"], temp.path().join("custom-gradle-jdk").to_string_lossy());
}
let dir = temp.path().join("kotlin");
for (gradle, target, expected) in
[((9, 0), 8, 17), ((8, 4), 21, 17), ((8, 5), 21, 21), ((7, 2), 21, 11), ((9, 0), 25, 21), ((9, 1), 25, 25)]
{
std::fs::write(dir.join("build.gradle.kts"), format!("kotlin {{ jvmToolchain({target}) }}")).unwrap();
assert_eq!(gradle_run_jdk(Some(target), None, &installed, Some(gradle)).unwrap().major, expected);
}
assert_eq!(gradle_run_jdk(Some(21), None, &installed, None).unwrap().major, 21);
assert_eq!(gradle_run_jdk(Some(19), None, &installed, None).unwrap().major, 21);
assert!(gradle_run_jdk(None, None, &installed, None).is_none());
}
#[test]
fn reads_wrapper_and_local_gradle_versions_without_running_them() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::create_dir_all(root.join("gradle/wrapper")).unwrap();
std::fs::write(
root.join("gradle/wrapper/gradle-wrapper.properties"),
"distributionUrl=https\\://services.gradle.org/distributions/gradle-8.4.0-bin.zip\n",
)
.unwrap();
for command in ["./gradlew", "gradlew.bat"] {
assert_eq!(gradle_distribution_version(root, command), Some((8, 4)));
}
for layout in ["lib", "libexec/lib"] {
let home = root.join(layout.replace('/', "-"));
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::create_dir_all(home.join(layout)).unwrap();
let command = home.join("bin/gradle");
std::fs::write(&command, "").unwrap();
std::fs::write(home.join(layout).join("gradle-launcher-9.0.0.jar"), "").unwrap();
assert_eq!(gradle_distribution_version(root, &command.to_string_lossy()), Some((9, 0)));
}
}
}
#[cfg(test)]
mod maven_linkage_tests {
use super::*;
+15 -5
Переглянути файл
@@ -540,10 +540,12 @@ pub fn project_java_version(module_dir: &Path) -> Option<u32> {
}
for name in ["build.gradle.kts", "build.gradle"] {
let Some(text) = read(name) else { continue };
if let Some(i) = text.find("JavaLanguageVersion.of(") {
let rest = &text[i + "JavaLanguageVersion.of(".len()..];
if let Some(v) = parse_java_version(rest.split(')').next().unwrap_or_default()) {
return Some(v);
for key in ["JavaLanguageVersion.of(", "jvmToolchain("] {
if let Some(i) = text.find(key) {
let rest = &text[i + key.len()..];
if let Some(v) = parse_java_version(rest.split(')').next().unwrap_or_default()) {
return Some(v);
}
}
}
for key in ["sourceCompatibility", "targetCompatibility"] {
@@ -1138,6 +1140,14 @@ mod tests {
assert_eq!(project_java_version(dir), Some(11));
std::fs::write(dir.join("build.gradle.kts"), "sourceCompatibility = '1.8'").unwrap();
assert_eq!(project_java_version(dir), Some(8));
for (script, version) in [
("kotlin { jvmToolchain(21) }", Some(21)),
("kotlin { jvmToolchain(17) }", Some(17)),
("kotlin { jvmToolchain(projectVersion) }", None),
] {
std::fs::write(dir.join("build.gradle.kts"), script).unwrap();
assert_eq!(project_java_version(dir), version);
}
}
}
@@ -1186,7 +1196,7 @@ mod kotlin_bridge_bundle_tests {
/// Installs the app-owned JDT LS command bundle, falling back to ordinary LSP on IO failure.
pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
let extension = data_dir.join("java-usages-1.6.0.jar");
let extension = data_dir.join("java-usages-1.7.0.jar");
let bytes = include_bytes!("../../../java/java-usages/openidea-java-usages.jar");
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
clean_usages_bundles(data_dir, &extension);
+57
Переглянути файл
@@ -115,6 +115,26 @@ fn jdtls_vm_args() {
assert_eq!(cfg.args, ["--jvm-arg=-Xmx2g", "--jvm-arg=-javaagent:/opt/lombok.jar"]);
}
#[test]
fn jdtls_honors_the_configured_maven_local_repository() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("m2-repo");
let mut s = Settings::default();
s.languages.java.maven.local_repository = repo.to_string_lossy().into_owned();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(cfg.args, [format!("--jvm-arg=-Dmaven.repo.local={}", repo.to_string_lossy())]);
// A `-Dmaven.repo.local` the user put in their own jdtls VM options wins.
s.languages.java.jdtls_vm_args = "-Xmx2g -Dmaven.repo.local=/user/repo".into();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(cfg.args, ["--jvm-arg=-Xmx2g", "--jvm-arg=-Dmaven.repo.local=/user/repo"]);
// Unset: jdtls keeps m2e's own default (no arg at all).
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &Settings::default());
assert!(cfg.args.iter().all(|a| !a.contains("maven.repo.local")));
}
#[test]
fn rust_analyzer_check_command_and_toolchain() {
if cfg!(windows) {
@@ -1615,3 +1635,40 @@ fn saving_a_loaded_run_configuration_drops_what_settings_derived() {
assert_eq!(next[1].args, ["-Dmaven.repo.local=/m3/repo", "-s", "/mine.xml", "test"]);
}
}
#[test]
fn nested_python_configs_get_their_own_virtualenv_but_explicit_settings_stay_project_relative() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let outer = fake_venv(root, ".venv");
let nested = fake_venv(&root.join("apps").join("python"), ".venv");
let mut config = run("python", "python3", &["main.py"]);
config.extras.module = Some("apps/python".into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &Settings::default());
assert_eq!(config.env["VIRTUAL_ENV"], nested.parent().unwrap().parent().unwrap().to_string_lossy());
// A workspace member without its own virtualenv uses the one at the project root (uv workspaces).
let mut member = run("pytest", "python3", &["-m", "pytest"]);
member.extras.module = Some("packages/lib".into());
apply_to_run_configs(std::slice::from_mut(&mut member), root, &Settings::default());
assert_eq!(member.env["VIRTUAL_ENV"], outer.parent().unwrap().parent().unwrap().to_string_lossy());
let mut settings = Settings::default();
settings.languages.python.interpreter = "custom/bin/python".into();
let mut config = run("python", "python3", &["main.py"]);
config.extras.module = Some("apps/python".into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert_eq!(config.command, root.join("custom/bin/python").to_string_lossy());
}
#[test]
fn file_runtime_uses_nearest_virtualenv_and_explicit_project_settings_win() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let outer = fake_venv(root, ".venv");
let inner = fake_venv(&root.join("apps/api"), ".venv");
let near = root.join("apps/api/src/package");
let mut settings = Settings::default();
assert_eq!(crate::apply::python_interpreter_near(root, Some(&near), &settings), Some(inner));
assert_eq!(crate::apply::python_interpreter_near(root, Some(&root.join("apps/other")), &settings), Some(outer));
settings.languages.python.interpreter = "selected/python".into();
assert_eq!(crate::apply::python_interpreter_near(root, Some(&near), &settings), Some(root.join("selected/python")));
}
+41 -4
Переглянути файл
@@ -1221,10 +1221,26 @@ impl Tools {
cancel: &CancellationToken,
) -> IdeResult<sources::Download> {
match source {
ReleaseSource::GitHub { repo } => {
let json = http.get_text(&sources::github_latest_url(repo), cancel)?;
sources::github_pick(&json, assets, self.platform)
}
ReleaseSource::GitHub { repo } => match http.get_text(&sources::github_latest_url(repo), cancel) {
Ok(json) => sources::github_pick(&json, assets, self.platform),
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
// Without a token the API allows 60 requests an hour per IP address, often used
// up behind a shared one (403/429); the release's web pages have no such limit.
Err(api) => self.resolve_github_web(http, repo, assets, cancel).map_err(|web| {
if web.kind == ErrorKind::Cancelled {
return web;
}
tracing::warn!("GitHub release lookup for {repo} failed: {api}; web pages: {web}");
IdeError::new(
api.kind,
format!(
"{}\nDownload it from {} and set its Path in Settings › Languages & Frameworks › Language Servers.",
api.message,
sources::github_latest_page(repo)
),
)
}),
},
ReleaseSource::HashiCorp { product } => {
let json = http.get_text(&sources::hashicorp_latest_url(product), cancel)?;
sources::hashicorp_pick(&json, assets, self.platform)
@@ -1251,6 +1267,27 @@ impl Tools {
}
}
/// [`resolve_release`](Self::resolve_release) for a GitHub release, from its web pages.
fn resolve_github_web(
&self,
http: &Http,
repo: &str,
assets: &[platform::AssetRule],
cancel: &CancellationToken,
) -> IdeResult<sources::Download> {
let page = http.effective_url(&sources::github_latest_page(repo), cancel)?;
let tag = sources::github_tag_from_url(&page)
.ok_or_else(|| IdeError::unavailable(format!("{repo} has no published release")))?;
let list = http.get_text(&sources::github_assets_page(repo, &tag), cancel)?;
match sources::github_pick_web(repo, &tag, &list, None, assets, self.platform) {
Err(e) if e.kind == ErrorKind::Unavailable => {
let notes = http.get_text(&sources::github_tag_page(repo, &tag), cancel)?;
sources::github_pick_web(repo, &tag, &list, Some(&notes), assets, self.platform)
}
result => result,
}
}
fn install_release(
&self,
spec: &ToolSpec,
+27 -5
Переглянути файл
@@ -263,6 +263,15 @@ fn curl_takes_revoke_best_effort(version: &str) -> bool {
(major, minor) >= (7, 70) && first.split_whitespace().any(|w| w.eq_ignore_ascii_case("schannel"))
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Request {
Get,
/// Adoptium uses 404 as well as an empty array for absent platform builds.
GetOrEmptyOn404,
/// Headers, then the URL redirects ended at.
Head,
}
/// HTTP via the system `curl` (shipped with macOS, Windows 10+ and every
/// mainstream Linux), so the IDE carries no TLS stack of its own.
pub struct Http {
@@ -336,26 +345,39 @@ impl Http {
self.get_text_limited(url, None, cancel)
}
/// Where `url` ends up after redirects (a HEAD request).
pub fn effective_url(&self, url: &str, cancel: &CancellationToken) -> IdeResult<String> {
let out = self.get_text_response(url, None, Request::Head, cancel)?;
Ok(out.trim_end().rsplit('\n').next().unwrap_or_default().trim().to_owned())
}
/// GETs `url` as text, failing when the response is larger than `max_bytes`.
pub fn get_text_limited(&self, url: &str, max_bytes: Option<u64>, cancel: &CancellationToken) -> IdeResult<String> {
self.get_text_response(url, max_bytes, false, cancel)
self.get_text_response(url, max_bytes, Request::Get, cancel)
}
/// Adoptium uses 404 as well as an empty array for absent platform builds.
pub fn get_text_or_empty_on_404(&self, url: &str, cancel: &CancellationToken) -> IdeResult<String> {
self.get_text_response(url, None, true, cancel)
self.get_text_response(url, None, Request::GetOrEmptyOn404, cancel)
}
fn get_text_response(
&self,
url: &str,
max_bytes: Option<u64>,
empty_on_404: bool,
request: Request,
cancel: &CancellationToken,
) -> IdeResult<String> {
let (mut cmd, token) = self.base(url, cancel)?;
if empty_on_404 {
cmd.args(["--write-out", "\n%{http_code}"]);
let empty_on_404 = request == Request::GetOrEmptyOn404;
match request {
Request::Get => {}
Request::GetOrEmptyOn404 => {
cmd.args(["--write-out", "\n%{http_code}"]);
}
Request::Head => {
cmd.args(["--head", "--write-out", "\n%{url_effective}"]);
}
}
if let Some(max) = max_bytes {
cmd.arg("--max-filesize").arg(max.to_string());
+184 -11
Переглянути файл
@@ -47,38 +47,146 @@ pub fn github_latest_url(repo: &str) -> String {
format!("https://api.github.com/repos/{repo}/releases/latest")
}
/// The latest release's web page; it redirects to `…/releases/tag/<tag>`. Web pages don't
/// count against the API's rate limit for unauthenticated clients (60 requests an hour).
pub fn github_latest_page(repo: &str) -> String {
format!("https://github.com/{repo}/releases/latest")
}
/// The tag `github_latest_page` redirected to.
pub fn github_tag_from_url(url: &str) -> Option<String> {
let (_, tag) = url.split_once("/releases/tag/")?;
let tag = tag.split(['?', '#']).next().unwrap_or(tag).trim_end_matches('/');
(!tag.is_empty()).then(|| percent_decode(tag))
}
pub fn github_tag_page(repo: &str, tag: &str) -> String {
format!("https://github.com/{repo}/releases/tag/{tag}")
}
/// The asset list the release page loads (HTML).
pub fn github_assets_page(repo: &str, tag: &str) -> String {
format!("https://github.com/{repo}/releases/expanded_assets/{tag}")
}
/// One file of a release, from the API or its web page.
struct ReleaseAsset {
name: String,
url: String,
size: Option<u64>,
sha256: Option<String>,
}
/// Picks the platform asset from a GitHub `releases/latest` response. Links
/// in the release notes count as assets too (some projects host binaries on
/// a CDN and only link them).
pub fn github_pick(json: &str, rules: &[AssetRule], platform: Platform) -> IdeResult<Download> {
let rel: GhRelease = serde_json::from_str(json).map_err(|e| proto(format!("unexpected GitHub response: {e}")))?;
let version = rel.tag_name.trim_start_matches('v').to_string();
let names: Vec<&str> = rel.assets.iter().map(|a| a.name.as_str()).collect();
let assets: Vec<ReleaseAsset> = rel
.assets
.into_iter()
.map(|a| ReleaseAsset {
sha256: a.digest.as_deref().and_then(|d| d.strip_prefix("sha256:")).map(str::to_ascii_lowercase),
name: a.name,
url: a.browser_download_url,
size: a.size,
})
.collect();
pick_release(&rel.tag_name, &assets, rel.body.as_deref().unwrap_or(""), rules, platform)
}
/// [`github_pick`] from the release's web pages: `assets_html` from [`github_assets_page`] and,
/// for projects that only link their builds, `notes_html` from [`github_tag_page`].
pub fn github_pick_web(
repo: &str,
tag: &str,
assets_html: &str,
notes_html: Option<&str>,
rules: &[AssetRule],
platform: Platform,
) -> IdeResult<Download> {
let prefix = format!("href=\"/{repo}/releases/download/");
let mut assets: Vec<ReleaseAsset> = Vec::new();
let mut rest = assets_html;
while let Some(i) = rest.find(&prefix) {
let tail = &rest[i + "href=\"".len()..];
let Some(end) = tail.find('"') else { break };
let path = html_unescape(&tail[..end]);
rest = &tail[end..];
let name = percent_decode(file_name(&path));
if name.is_empty() || assets.iter().any(|a| a.name == name) {
continue;
}
// `<clipboard-copy aria-label="Copy to clipboard digest for <name>" … value="sha256:<hex>">`
let sha256 = assets_html.find(&format!("digest for {}\"", html_escape(&name))).and_then(|at| {
let tag_end = assets_html[at..].find('>').map_or(assets_html.len(), |e| at + e);
let value = assets_html[at..tag_end].split_once("value=\"sha256:")?.1;
let hex: String = value.chars().take_while(char::is_ascii_hexdigit).collect();
(hex.len() == 64).then(|| hex.to_ascii_lowercase())
});
assets.push(ReleaseAsset { url: format!("https://github.com{path}"), name, size: None, sha256 });
}
pick_release(tag, &assets, &html_unescape(notes_html.unwrap_or("")), rules, platform)
}
fn pick_release(
tag: &str,
assets: &[ReleaseAsset],
notes: &str,
rules: &[AssetRule],
platform: Platform,
) -> IdeResult<Download> {
let version = tag.trim_start_matches('v').to_string();
let names: Vec<&str> = assets.iter().map(|a| a.name.as_str()).collect();
if let Some(name) = select_asset(&names, rules, platform) {
let a = rel.assets.iter().find(|a| a.name == name).expect("selected from list");
let sha256 = a.digest.as_deref().and_then(|d| d.strip_prefix("sha256:")).map(str::to_ascii_lowercase);
let checksum_url = rel
.assets
let a = assets.iter().find(|a| a.name == name).expect("selected from list");
let checksum_url = assets
.iter()
.find(|c| c.name == format!("{name}.sha256") || c.name == format!("{name}.sha256sum"))
.map(|c| c.browser_download_url.clone());
.map(|c| c.url.clone());
return Ok(Download {
version,
name: a.name.clone(),
url: a.browser_download_url.clone(),
url: a.url.clone(),
size: a.size,
sha256,
sha256: a.sha256.clone(),
checksum_url,
});
}
let links = extract_links(rel.body.as_deref().unwrap_or(""));
let links = extract_links(notes);
let link_names: Vec<&str> = links.iter().map(|u| file_name(u)).collect();
if let Some(name) = select_asset(&link_names, rules, platform) {
let url = links.iter().find(|u| file_name(u) == name).expect("selected from list").clone();
let checksum_url = links.iter().find(|u| *u == &format!("{url}.sha256")).cloned();
return Ok(Download { version, name: name.to_string(), url, size: None, sha256: None, checksum_url });
}
Err(IdeError::unavailable(format!("release {} has no build for this platform", rel.tag_name)))
Err(IdeError::unavailable(format!("release {tag} has no build for this platform")))
}
fn html_unescape(s: &str) -> String {
s.replace("&quot;", "\"").replace("&#39;", "'").replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&")
}
fn html_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('"', "&quot;").replace('<', "&lt;").replace('>', "&gt;")
}
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = s.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).unwrap_or_else(|_| s.to_owned())
}
fn file_name(url: &str) -> &str {
@@ -336,6 +444,71 @@ mod tests {
assert_eq!(d.name, "kotlin-lsp-0.253.10629-linux-x64.zip");
}
#[test]
fn github_tag_from_redirect() {
let url = "https://github.com/Kotlin/kotlin-lsp/releases/tag/kotlin-lsp/v263.7084.0";
assert_eq!(github_tag_from_url(url).as_deref(), Some("kotlin-lsp/v263.7084.0"));
let url = "https://github.com/o/r/releases/tag/v1.0%2Bbuild";
assert_eq!(github_tag_from_url(url).as_deref(), Some("v1.0+build"));
// A repository without releases stays on the list.
assert_eq!(github_tag_from_url("https://github.com/o/r/releases"), None);
}
/// Trimmed from `github.com/<repo>/releases/expanded_assets/<tag>`.
const ASSETS_HTML: &str = r#"<li><div><a href="/LuaLS/lua-language-server/releases/download/3.13.5/lua-language-server-3.13.5-darwin-arm64.tar.gz" rel="nofollow" data-turbo="false" class="wb-break-all">
<span class="text-bold">lua-language-server-3.13.5-darwin-arm64.tar.gz</span></a></div>
<span class="Truncate-text">sha256:ABCDEF0123456789abcdef0123456789abcdef0123456789abcdef0123456789</span>
<clipboard-copy id="clipboard-button-sha256:abc" aria-label="Copy to clipboard digest for lua-language-server-3.13.5-darwin-arm64.tar.gz" type="button" value="sha256:ABCDEF0123456789abcdef0123456789abcdef0123456789abcdef0123456789" class="Button"></clipboard-copy></li>
<li><a href="/LuaLS/lua-language-server/releases/download/3.13.5/lua-language-server-3.13.5-linux-x64.tar.gz" rel="nofollow">lua-language-server-3.13.5-linux-x64.tar.gz</a></li>
<li><a href="/LuaLS/lua-language-server/archive/refs/tags/3.13.5.zip" rel="nofollow">Source code (zip)</a></li>"#;
#[test]
fn github_web_assets_with_digest() {
let rules = find("lua-language-server").unwrap().asset_rules();
let d = github_pick_web("LuaLS/lua-language-server", "3.13.5", ASSETS_HTML, None, rules, MAC_ARM).unwrap();
assert_eq!(d.version, "3.13.5");
assert_eq!(d.name, "lua-language-server-3.13.5-darwin-arm64.tar.gz");
assert_eq!(
d.url,
"https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/lua-language-server-3.13.5-darwin-arm64.tar.gz"
);
assert_eq!(d.sha256.as_deref(), Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"));
let d = github_pick_web("LuaLS/lua-language-server", "3.13.5", ASSETS_HTML, None, rules, LINUX).unwrap();
assert_eq!(d.sha256, None);
let win = Platform { os: Os::Windows, arch: Arch::X64 };
let err = github_pick_web("LuaLS/lua-language-server", "3.13.5", ASSETS_HTML, None, rules, win).unwrap_err();
assert_eq!(err.kind, ErrorKind::Unavailable);
}
#[test]
fn github_web_sibling_checksum_and_notes_links() {
let html = r#"<a href="/artempyanykh/marksman/releases/download/2024-12-18/marksman-macos" rel="nofollow">
<a href="/artempyanykh/marksman/releases/download/2024-12-18/marksman-macos.sha256" rel="nofollow">"#;
let d = github_pick_web(
"artempyanykh/marksman",
"2024-12-18",
html,
None,
find("marksman").unwrap().asset_rules(),
MAC_ARM,
)
.unwrap();
assert_eq!(
d.checksum_url.as_deref(),
Some("https://github.com/artempyanykh/marksman/releases/download/2024-12-18/marksman-macos.sha256")
);
let notes = r#"<li><a href="https://download-cdn.jetbrains.com/kotlin-lsp/0.253.10629/kotlin-lsp-0.253.10629-mac-aarch64.zip?a=1&amp;b=2" rel="nofollow">macOS arm</a></li>"#;
let rules = find("kotlin-lsp").unwrap().asset_rules();
let d =
github_pick_web("Kotlin/kotlin-lsp", "kotlin-lsp/v0.253.10629", "", Some(notes), rules, MAC_ARM).unwrap();
assert_eq!(d.name, "kotlin-lsp-0.253.10629-mac-aarch64.zip");
assert_eq!(
d.url,
"https://download-cdn.jetbrains.com/kotlin-lsp/0.253.10629/kotlin-lsp-0.253.10629-mac-aarch64.zip?a=1&b=2"
);
}
#[test]
fn hashicorp() {
let json = r#"{"version":"0.36.4","url_shasums":"https://r/terraform-ls_0.36.4_SHA256SUMS","builds":[
+4 -6
Переглянути файл
@@ -948,13 +948,11 @@ pub(crate) fn decorations(repo: &gix::Repository) -> IdeResult<HashMap<ObjectId,
let platform = repo.references().map_err(gx)?;
for reference in platform.all().map_err(gx)? {
let Ok(mut reference) = reference else { continue };
if reference.target().try_name().is_some() {
continue;
}
let full = reference.name().as_bstr().to_owned();
let label = if let Some(n) = full.strip_prefix(b"refs/heads/") {
to_string(n.as_bstr())
} else if let Some(n) = full.strip_prefix(b"refs/remotes/") {
if n.ends_with(b"/HEAD") {
continue;
}
let label = if let Some(n) = full.strip_prefix(b"refs/heads/").or_else(|| full.strip_prefix(b"refs/remotes/")) {
to_string(n.as_bstr())
} else if let Some(n) = full.strip_prefix(b"refs/tags/") {
format!("tag: {}", to_string(n.as_bstr()))
+41 -1
Переглянути файл
@@ -260,6 +260,22 @@ fn snapshot(file: &Path) -> IdeResult<Option<Snapshot>> {
}
}
/// `sync_all` failures that mean "this filesystem cannot fsync at all", not that
/// the data was lost: ENOTTY (`os error 25`, virtio-fs on macOS VMs answering
/// F_FULLFSYNC/fsync with "Inappropriate ioctl for device") and EINVAL (some
/// network filesystems). Mirrors `sync_error_is_tolerable` in ide-vfs atomic
/// writes; other errors keep failing the update.
fn sync_error_is_tolerable(e: &std::io::Error) -> bool {
if e.kind() == std::io::ErrorKind::InvalidInput {
return true;
}
// EINVAL is already covered by InvalidInput; ENOTTY has no ErrorKind of its own.
#[cfg(unix)]
return e.raw_os_error() == Some(25);
#[cfg(not(unix))]
false
}
fn append(file: &Path, rules: &[IgnoreRule]) -> IdeResult<()> {
no_symlinks(file.parent().unwrap())?;
fs::create_dir_all(file.parent().unwrap())?;
@@ -316,7 +332,16 @@ fn append(file: &Path, rules: &[IgnoreRule]) -> IdeResult<()> {
};
temp.as_file().set_permissions(permissions)?;
temp.write_all(&updated)?;
temp.as_file().sync_all()?;
if let Err(e) = temp.as_file().sync_all() {
// Filesystems without fsync (virtio-fs on macOS VMs, some network mounts):
// the write itself already went through, so keep the updated ignore file
// instead of failing the whole update.
if sync_error_is_tolerable(&e) {
tracing::debug!("fsync unsupported for {}: {e}; continuing", file.display());
} else {
return Err(e.into());
}
}
replace_if_unchanged(file, before, temp)
}
@@ -356,4 +381,19 @@ mod tests {
assert!(replace_if_unchanged(&file, before, temp).unwrap_err().message.contains("changed"));
assert_eq!(fs::read_to_string(file).unwrap(), "external writer\n");
}
#[test]
fn sync_errors_without_fsync_support_are_tolerable() {
// Some network filesystems report EINVAL for fsync.
assert!(sync_error_is_tolerable(&std::io::Error::new(std::io::ErrorKind::InvalidInput, "EINVAL")));
#[cfg(unix)]
{
// virtio-fs on macOS VMs answers fsync with "Inappropriate ioctl for device".
assert!(sync_error_is_tolerable(&std::io::Error::from_raw_os_error(25)));
assert!(sync_error_is_tolerable(&std::io::Error::from_raw_os_error(22)));
}
// Real write failures still fail the update.
assert!(!sync_error_is_tolerable(&std::io::Error::from_raw_os_error(28)));
assert!(!sync_error_is_tolerable(&std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied")));
}
}
+2 -2
Переглянути файл
@@ -910,7 +910,7 @@ impl Repo {
let id = commit_id.to_string();
let contains = format!("--contains={id}");
let branches =
cli::run_cancellable(self.root(), &["branch", "-a", &contains, "--format=%(refname:short)"], cancel)?;
cli::run_cancellable(self.root(), &["branch", "-a", &contains, refs::DIRECT_BRANCH_FORMAT], cancel)?;
let cache_key = format!("{allowed}:{id}");
let cached = self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()).get(&cache_key).cloned();
let mut details = if let Some(details) = cached {
@@ -952,7 +952,7 @@ impl Repo {
details
};
details.containing_branches =
branches.stdout_str().lines().filter(|s| !s.ends_with("/HEAD")).map(str::to_string).collect();
branches.stdout_str().lines().filter(|s| !s.is_empty()).map(str::to_string).collect();
Ok(details)
}
+3 -3
Переглянути файл
@@ -95,9 +95,9 @@ fn branch_at(r: &Repo, commit: &str) -> Option<String> {
}
["refs/heads", "refs/remotes"].into_iter().find_map(|refs| {
let out =
run(r.root(), &["for-each-ref", "--points-at", commit, "--format=%(refname:short)", refs], None).ok()?;
let names: Vec<String> =
out.stdout_str().lines().filter(|l| !l.is_empty() && !l.ends_with("/HEAD")).map(str::to_string).collect();
run(r.root(), &["for-each-ref", "--points-at", commit, crate::refs::DIRECT_BRANCH_FORMAT, refs], None)
.ok()?;
let names: Vec<String> = out.stdout_str().lines().filter(|l| !l.is_empty()).map(str::to_string).collect();
match names.as_slice() {
[one] => Some(one.clone()),
_ => None,
+9 -3
Переглянути файл
@@ -4,6 +4,9 @@ use crate::repo::{gx, to_string};
use crate::{Branch, BranchInfo, Repo, Stash};
use ide_core::IdeResult;
// Filter symbolic refs before shortening; `refname:short` also strips remote `/HEAD` suffixes.
pub(crate) const DIRECT_BRANCH_FORMAT: &str = "--format=%(if)%(symref)%(then)%(else)%(refname:lstrip=2)%(end)";
pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
let repo = r.gix()?;
let head_ref = repo.head_name().map_err(gx)?;
@@ -93,6 +96,9 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
for reference in platform.local_branches().map_err(gx)? {
let mut reference = reference.map_err(gx)?;
if reference.target().try_name().is_some() {
continue;
}
let full = reference.name().to_owned();
let Ok(id) = reference.peel_to_id().map(|id| id.detach()) else { continue };
let current = head_name.as_ref().is_some_and(|h| h == &full);
@@ -118,11 +124,11 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
}
for reference in platform.remote_branches().map_err(gx)? {
let mut reference = reference.map_err(gx)?;
let full = reference.name().to_owned();
// Skip `refs/remotes/<remote>/HEAD` symbolic pointers.
if full.as_bstr().ends_with(b"/HEAD") {
// Skip symbolic aliases such as `refs/remotes/<remote>/HEAD`.
if reference.target().try_name().is_some() {
continue;
}
let full = reference.name().to_owned();
let Ok(id) = reference.peel_to_id().map(|id| id.detach()) else { continue };
out.push(Branch {
name: to_string(full.as_ref().shorten()),
+15
Переглянути файл
@@ -149,6 +149,21 @@ fn merge_versions_put_the_users_work_on_the_left() {
assert_eq!(repo.merge_sides().unwrap(), MergeSides { branch: Some("topic".into()), ..Default::default() });
}
#[test]
fn rebase_conflict_names_the_remote_branch_without_its_symbolic_aliases() {
let fx = diverged();
let main = fx.git(&["rev-parse", "main"]);
fx.git(&["update-ref", "refs/remotes/origin/main", &main]);
fx.git(&["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
fx.git(&["symbolic-ref", "refs/remotes/origin/alias", "refs/remotes/origin/main"]);
fx.git(&["branch", "-D", "main"]);
let repo = fx.repo();
assert!(repo.rebase("origin/main").is_err());
assert_eq!(repo.merge_sides().unwrap().other_branch.as_deref(), Some("origin/main"));
let (cancel, out) = quiet();
repo.abort_operation(&cancel, &out).unwrap();
}
#[test]
fn rebase_conflict_then_abort_and_skip() {
let fx = diverged();
+37
Переглянути файл
@@ -113,6 +113,43 @@ fn lazy_summaries_seek_and_index_survive_refresh_and_restart() {
assert_eq!(repo.log_details(&ids[69]).unwrap().signature, "N");
}
#[test]
fn containing_branches_exclude_symbolic_aliases_but_keep_direct_head_names() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let tip = commit(dir, "a", "tip");
git(dir, &["branch", "topic/HEAD"]);
for remote in ["origin", "contributor-742", "issue-739", "issue-765"] {
let main = format!("refs/remotes/{remote}/main");
git(dir, &["update-ref", &main, &tip]);
git(dir, &["symbolic-ref", &format!("refs/remotes/{remote}/HEAD"), &main]);
git(dir, &["symbolic-ref", &format!("refs/remotes/{remote}/alias"), &main]);
}
git(dir, &["update-ref", "refs/remotes/origin/topic/HEAD", &tip]);
git(dir, &["symbolic-ref", "refs/heads/local-alias", "refs/heads/main"]);
let repo = Repo::discover(dir).unwrap().unwrap();
let expected = [
"contributor-742/main",
"issue-739/main",
"issue-765/main",
"main",
"origin/main",
"origin/topic/HEAD",
"topic/HEAD",
];
let mut branches = repo.log_details(&tip).unwrap().containing_branches;
branches.sort();
assert_eq!(branches, expected);
let mut listed: Vec<_> = repo.branches().unwrap().into_iter().map(|b| b.name).collect();
listed.sort();
assert_eq!(listed, expected);
let log = repo.log(&LogQuery::default()).unwrap();
let mut labels: Vec<_> = log[0].refs.iter().filter(|r| *r != "HEAD").cloned().collect();
labels.sort();
assert_eq!(labels, expected);
}
#[test]
fn followed_history_carries_the_filename_at_each_revision() {
let tmp = tempfile::tempdir().unwrap();
+41 -1
Переглянути файл
@@ -301,6 +301,21 @@ pub(crate) fn is_atomic_temp(path: &Path) -> bool {
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.') && n.contains(TMP_MARKER))
}
/// `sync_all` failures that mean "this filesystem cannot fsync at all", not that
/// the data was lost: ENOTTY (`os error 25`, virtio-fs on macOS VMs answering
/// F_FULLFSYNC/fsync with "Inappropriate ioctl for device") and EINVAL (some
/// network filesystems). Other errors keep failing the write.
fn sync_error_is_tolerable(e: &std::io::Error) -> bool {
if e.kind() == std::io::ErrorKind::InvalidInput {
return true;
}
// EINVAL is already covered by InvalidInput; ENOTTY has no ErrorKind of its own.
#[cfg(unix)]
return e.raw_os_error() == Some(25);
#[cfg(not(unix))]
false
}
/// Writes `bytes` to `path` atomically: temp file in the same directory, fsync,
/// rename over the target. Preserves the permissions of an existing file and
/// writes through symlinks. Falls back to an in-place write when the directory
@@ -347,7 +362,17 @@ fn write_atomic_impl(path: &Path, bytes: &[u8], allow_in_place: bool) -> IdeResu
};
let result = (|| -> std::io::Result<()> {
file.write_all(bytes)?;
file.sync_all()?;
if let Err(e) = file.sync_all() {
// virtio-fs (macOS VMs) and similar filesystems have no fsync/F_FULLFSYNC
// (ENOTTY, EINVAL): the write itself already went through, so the rename is
// still the best durability the filesystem offers — degrade like SQLite
// instead of failing the whole atomic write.
if sync_error_is_tolerable(&e) {
tracing::debug!("fsync unsupported for {}: {e}; continuing", target.display());
} else {
return Err(e);
}
}
if let Some(meta) = &existing {
fs::set_permissions(&tmp, meta.permissions())?;
}
@@ -526,4 +551,19 @@ mod tests {
assert_eq!(encode("x", "nope", false).unwrap_err().kind, ide_core::error::ErrorKind::InvalidInput);
assert_eq!(encode("中", "windows-1252", false).unwrap_err().kind, ide_core::error::ErrorKind::InvalidInput);
}
#[test]
fn sync_errors_without_fsync_support_are_tolerable() {
// Some network filesystems report EINVAL for fsync.
assert!(sync_error_is_tolerable(&std::io::Error::new(std::io::ErrorKind::InvalidInput, "EINVAL")));
#[cfg(unix)]
{
// virtio-fs on macOS VMs answers fsync with "Inappropriate ioctl for device".
assert!(sync_error_is_tolerable(&std::io::Error::from_raw_os_error(25)));
assert!(sync_error_is_tolerable(&std::io::Error::from_raw_os_error(22)));
}
// Real write failures still fail the atomic write.
assert!(!sync_error_is_tolerable(&std::io::Error::from_raw_os_error(28)));
assert!(!sync_error_is_tolerable(&std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied")));
}
}
+122 -32
Переглянути файл
@@ -81,6 +81,14 @@ fn exclude_path(root: &Path) -> PathBuf {
.unwrap_or_else(|| root.join(".git/info/exclude"))
}
#[derive(Default)]
struct NestedRepos {
/// Directory -> enclosing repository root when different from `GitignoreStack::repo_root`.
by_dir: HashMap<PathBuf, Option<PathBuf>>,
/// Repository root -> shared `GitignoreStack` for that nested repository.
by_root: HashMap<PathBuf, Arc<GitignoreStack>>,
}
/// Layered gitignore matching: per-directory `.gitignore` / `.ignore` from the
/// path's directory up to the repository root (or the file system root when
/// not in a repository), then `.git/info/exclude` and the global excludes file.
@@ -89,7 +97,7 @@ pub(crate) struct GitignoreStack {
/// `.git/info/exclude` and the global excludes file, rooted at the repo root.
repo_level: RwLock<Vec<Gitignore>>,
cache: Mutex<HashMap<PathBuf, Option<Arc<Gitignore>>>>,
nested: Mutex<HashMap<PathBuf, Option<Arc<GitignoreStack>>>>,
nested: Mutex<NestedRepos>,
}
/// How long [`GitignoreStack::cached`] reuses the repository lookup of a directory.
@@ -191,13 +199,23 @@ impl GitignoreStack {
if let (Some(root), Some(map)) = (&self.repo_root, REPO_LEVEL.lock().as_mut()) {
map.retain(|dir, _| !dir.starts_with(root));
}
self.nested.lock().clear();
self.nested.lock().by_root.values().for_each(|s| s.reload_repo_level());
*self.repo_level.write() = Self::load_repo_level(self.repo_root.as_deref());
}
/// Forgets the cached rules of `dir` and every directory below it.
pub fn invalidate_tree(&self, dir: &Path) {
self.nested.lock().clear();
{
let mut nested = self.nested.lock();
let target = if dir.file_name().is_some_and(|n| n == ".git") { dir.parent().unwrap_or(dir) } else { dir };
if nested.by_dir.contains_key(target) || nested.by_root.contains_key(target) {
nested.by_dir.retain(|k, _| !k.starts_with(target));
nested.by_root.retain(|k, _| !k.starts_with(target));
}
for stack in nested.by_root.values() {
stack.invalidate_tree(dir);
}
}
let mut cache = self.cache.lock();
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
if cache.contains_key(dir) {
@@ -211,10 +229,57 @@ impl GitignoreStack {
/// Forgets the cached rules of `dir` (after its `.gitignore` changed).
pub fn invalidate(&self, dir: &Path) {
self.nested.lock().clear();
for stack in self.nested.lock().by_root.values() {
stack.invalidate(dir);
}
self.cache.lock().remove(dir);
}
/// Returns the shared `GitignoreStack` of the nested repository enclosing `dir`, if any.
fn nested_for(&self, dir: &Path) -> Option<Arc<GitignoreStack>> {
let mut nested = self.nested.lock();
let root = if let Some(cached) = nested.by_dir.get(dir) {
cached.clone()
} else {
let mut chain = Vec::new();
let mut found = None;
for anc in dir.ancestors() {
if let Some(cached) = nested.by_dir.get(anc) {
found = cached.clone();
break;
}
chain.push(anc.to_path_buf());
if self.repo_root.as_deref() == Some(anc) {
found = None;
break;
}
if anc.join(".git").exists() {
found = Some(anc.to_path_buf());
break;
}
}
for p in chain {
nested.by_dir.insert(p, found.clone());
}
found
}?;
Some(
nested
.by_root
.entry(root.clone())
.or_insert_with(|| {
let repo_level = RwLock::new(Self::load_repo_level(Some(&root)));
Arc::new(Self {
repo_root: Some(root),
repo_level,
cache: Mutex::default(),
nested: Mutex::default(),
})
})
.clone(),
)
}
fn matcher_for(&self, dir: &Path) -> Option<Arc<Gitignore>> {
if let Some(cached) = self.cache.lock().get(dir) {
return cached.clone();
@@ -250,20 +315,10 @@ impl GitignoreStack {
pub fn is_ignored(&self, path: &Path, is_dir: bool) -> bool {
// A project's watcher can span independent nested repositories. Their local
// excludes and ignore ancestry must stop at their own repository boundary.
if let Some(parent) = path.parent() {
let nested = self
.nested
.lock()
.entry(parent.to_path_buf())
.or_insert_with(|| {
find_repo_root(parent)
.filter(|root| self.repo_root.as_ref() != Some(root))
.map(|_| Arc::new(Self::new(parent)))
})
.clone();
if let Some(nested) = nested {
return nested.is_ignored(path, is_dir);
}
if let Some(parent) = path.parent()
&& let Some(nested) = self.nested_for(parent)
{
return nested.is_ignored(path, is_dir);
}
if self.repo_root.as_deref() == Some(path) {
return false;
@@ -302,20 +357,10 @@ impl GitignoreStack {
/// ignored) still emit its own create/remove so the tree can show it
/// appearing marked as ignored, while files inside it stay filtered out.
pub fn is_ignored_self(&self, path: &Path, is_dir: bool) -> bool {
if let Some(parent) = path.parent() {
let nested = self
.nested
.lock()
.entry(parent.to_path_buf())
.or_insert_with(|| {
find_repo_root(parent)
.filter(|root| self.repo_root.as_ref() != Some(root))
.map(|_| Arc::new(Self::new(parent)))
})
.clone();
if let Some(nested) = nested {
return nested.is_ignored_self(path, is_dir);
}
if let Some(parent) = path.parent()
&& let Some(nested) = self.nested_for(parent)
{
return nested.is_ignored_self(path, is_dir);
}
if self.repo_root.as_deref() == Some(path) {
return false;
@@ -405,4 +450,49 @@ mod tests {
assert_eq!(first.repo_root(), again.repo_root());
assert_eq!(again.repo_root(), Some(tmp.path()));
}
#[test]
fn nested_repository_shares_one_gitignore_stack_across_subdirectories() {
let tmp = tempfile::tempdir().unwrap();
let workspace = tmp.path();
let repo = workspace.join("yolo");
std::fs::create_dir_all(repo.join(".git")).unwrap();
std::fs::create_dir_all(repo.join("a/b/c")).unwrap();
std::fs::create_dir_all(repo.join("x/y/z")).unwrap();
std::fs::write(repo.join(".gitignore"), "*.ignored\n").unwrap();
let stack = GitignoreStack::new(workspace);
assert!(stack.is_ignored(&repo.join("a/b/c/file.ignored"), false));
assert!(stack.is_ignored(&repo.join("x/y/z/other.ignored"), false));
assert!(!stack.is_ignored(&repo.join("x/y/z/keep.rs"), false));
assert_eq!(stack.nested.lock().by_root.len(), 1);
let nested = stack.nested.lock().by_root.get(&repo).unwrap().clone();
assert!(nested.cache.lock().contains_key(&repo));
// Invalidating a leaf file or directory inside the nested repo keeps its shared stack.
stack.invalidate_tree(&repo.join("a/b/c/new.rs"));
assert_eq!(stack.nested.lock().by_root.len(), 1);
assert!(Arc::ptr_eq(&nested, stack.nested.lock().by_root.get(&repo).unwrap()));
}
#[test]
fn a_repository_created_inside_the_workspace_becomes_a_boundary() {
let tmp = tempfile::tempdir().unwrap();
let workspace = tmp.path();
std::fs::create_dir_all(workspace.join(".git")).unwrap();
std::fs::create_dir_all(workspace.join("sub/deep")).unwrap();
std::fs::write(workspace.join(".gitignore"), "*.tmp\n").unwrap();
let stack = GitignoreStack::new(workspace);
assert!(stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
std::fs::create_dir(workspace.join("sub/.git")).unwrap();
stack.invalidate_tree(&workspace.join("sub/.git"));
assert!(!stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
std::fs::remove_dir(workspace.join("sub/.git")).unwrap();
stack.invalidate_tree(&workspace.join("sub/.git"));
assert!(stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
}
}
+144 -13
Переглянути файл
@@ -13,7 +13,7 @@ use crate::FsBatch;
use crate::rules::{ExcludeMatcher, GitignoreStack};
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink};
use notify::event::{ModifyKind, RenameMode};
use notify::{Event, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, WatcherKind};
use notify::{ErrorKind, Event, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, WatcherKind};
use parking_lot::{Condvar, Mutex, RwLock};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Component, Path, PathBuf};
@@ -27,6 +27,9 @@ const DEBOUNCE: Duration = Duration::from_millis(100);
const MAX_DELAY: Duration = Duration::from_millis(1000);
/// How often the polling fallback rescans the watched directories.
const POLL_INTERVAL: Duration = Duration::from_secs(2);
/// Directories watched synchronously in [`Watcher::start`] before handing the
/// remainder of a large tree to the watcher thread.
const SYNC_WATCH_BUDGET: usize = 256;
/// How directories are registered with the OS.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -176,13 +179,14 @@ impl Watcher {
},
config,
)
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
.map_err(|e| watcher_error("cannot start file watcher", e))?;
*state.watcher.lock() = Some(Box::new(watcher));
if mode == WatchMode::PerDirectory {
state.watch_tree(root, false, &mut Vec::new());
let deferred = if mode == WatchMode::PerDirectory {
state.watch_tree_bounded(root, SYNC_WATCH_BUDGET)
} else {
state.add_watch(root);
}
Vec::new()
};
if state.watched.lock().is_empty() {
return Err(io_error(format!("cannot watch {}", root.display())));
}
@@ -190,7 +194,7 @@ impl Watcher {
let state = state.clone();
std::thread::Builder::new()
.name("openidea-fs-watch".into())
.spawn(move || state.run(&*emit))
.spawn(move || state.run(deferred, &*emit))
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?
};
Ok(Inner { state, thread: Some(thread) })
@@ -223,6 +227,29 @@ fn is_dir_touch(event: &notify::Event) -> bool {
matches!(event.kind, EventKind::Modify(_)) && event.paths.iter().all(|p| p.is_dir())
}
const MAX_WATCHES_HINT: &str = "the inotify watch limit is exhausted (fs.inotify.max_user_watches); raise it, e.g. \
`sudo sysctl -w fs.inotify.max_user_watches=524288`";
/// `io_error` with a fix hint when Linux's inotify limits are exhausted: one
/// instance per watcher (`EMFILE`, os error 24) or one watch per directory
/// (`ENOSPC`, mapped by notify to [`ErrorKind::MaxFilesWatch`]). A bare OS
/// error sends users off to search engines otherwise (issue #788).
fn watcher_error(what: &str, error: notify::Error) -> IdeError {
let hint = match error.kind {
ErrorKind::MaxFilesWatch => Some(MAX_WATCHES_HINT),
ErrorKind::Io(ref e) if cfg!(target_os = "linux") && e.raw_os_error() == Some(24) => Some(
"the inotify instance limit is exhausted (fs.inotify.max_user_instances); raise it, e.g. \
`sudo sysctl -w fs.inotify.max_user_instances=1024`",
),
ErrorKind::Io(ref e) if cfg!(target_os = "linux") && e.raw_os_error() == Some(28) => Some(MAX_WATCHES_HINT),
_ => None,
};
match hint {
Some(hint) => io_error(format!("{what}: {error}; {hint}")),
None => io_error(format!("{what}: {error}")),
}
}
/// Shared with the notify callback (weakly) and the debounce thread.
struct DirState {
filter: EventFilter,
@@ -239,8 +266,12 @@ impl DirState {
self.stop.load(Ordering::SeqCst)
}
/// Debounce loop: waits for a quiet period, then processes the batch.
fn run(&self, emit: impl Fn(&FsBatch)) {
/// Debounce loop: finishes any deferred startup watches, then waits for a
/// quiet period and processes each batch.
fn run(&self, deferred: Vec<(PathBuf, bool)>, emit: impl Fn(&FsBatch)) {
if !deferred.is_empty() {
self.watch_stack(deferred, false, &mut Vec::new(), None);
}
loop {
let events = {
let mut q = self.queue.lock();
@@ -298,6 +329,7 @@ impl DirState {
// during this batch would otherwise never be seen.
for path in &batch.vcs {
if !self.watched.lock().contains(path) && path.symlink_metadata().is_ok_and(|m| m.is_dir()) {
self.filter.gitignore.invalidate_tree(path);
self.watch_tree(path, false, &mut discovered);
}
}
@@ -349,11 +381,33 @@ impl DirState {
/// files and directories found inside (created before the watch was in
/// place) are appended to `found`.
fn watch_tree(&self, dir: &Path, report: bool, found: &mut Vec<PathBuf>) {
let mut stack = vec![dir.to_path_buf()];
while let Some(dir) = stack.pop() {
if self.stopped() || !self.filter.should_watch_dir(&dir) || !self.add_watch(&dir) {
self.watch_stack(vec![(dir.to_path_buf(), false)], report, found, None);
}
/// Watches up to `budget` directories synchronously and returns any
/// remaining `(dir, parent_verified)` entries for background registration.
fn watch_tree_bounded(&self, dir: &Path, budget: usize) -> Vec<(PathBuf, bool)> {
self.watch_stack(vec![(dir.to_path_buf(), false)], false, &mut Vec::new(), Some(budget))
}
fn watch_stack(
&self,
mut stack: Vec<(PathBuf, bool)>,
report: bool,
found: &mut Vec<PathBuf>,
budget: Option<usize>,
) -> Vec<(PathBuf, bool)> {
let mut watched_now = 0;
while let Some((dir, parent_ok)) = stack.pop() {
if self.stopped() {
break;
}
let should_watch =
if parent_ok { self.filter.should_watch_child_dir(&dir) } else { self.filter.should_watch_dir(&dir) };
if !should_watch || !self.add_watch(&dir) {
continue;
}
watched_now += 1;
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
@@ -362,10 +416,14 @@ impl DirState {
found.push(path.clone());
}
if is_dir {
stack.push(path);
stack.push((path, true));
}
}
if budget.is_some_and(|max| watched_now >= max) {
break;
}
}
stack
}
fn unwatch_tree(&self, dir: &Path) {
@@ -469,6 +527,15 @@ impl EventFilter {
/// and `worktrees/` (HEAD, index, refs and worktree metadata are what VCS
/// refresh needs).
pub fn should_watch_dir(&self, dir: &Path) -> bool {
self.should_watch_dir_inner(dir, false)
}
/// Fast path when `dir`'s parent directory is already known to be watchable.
fn should_watch_child_dir(&self, dir: &Path) -> bool {
self.should_watch_dir_inner(dir, true)
}
fn should_watch_dir_inner(&self, dir: &Path, parent_ok: bool) -> bool {
let Ok(rel) = dir.strip_prefix(&self.root) else { return false };
if rel.as_os_str().is_empty() {
return true;
@@ -484,7 +551,11 @@ impl EventFilter {
_ => false,
};
}
!self.excludes.read().is_excluded(rel) && !self.gitignore.is_ignored(dir, true)
if parent_ok {
!self.excludes.read().is_match(rel) && !self.gitignore.is_ignored_self(dir, true)
} else {
!self.excludes.read().is_excluded(rel) && !self.gitignore.is_ignored(dir, true)
}
}
/// Whether a path found by scanning a new directory would be reported.
@@ -1075,6 +1146,42 @@ mod tests {
assert_eq!(batches.lock().len(), n, "no events after drop");
}
#[test]
fn per_directory_mode_watches_the_rest_of_a_large_tree_after_start() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let dirs = SYNC_WATCH_BUDGET + 40;
for i in 0..dirs {
std::fs::create_dir_all(root.join(format!("d{i:03}"))).unwrap();
}
std::fs::create_dir_all(root.join("node_modules/x")).unwrap();
let batches: Arc<Mutex<Vec<FsBatch>>> = Arc::default();
let sink: SharedSink = Arc::new(|_e: IdeEvent| {});
let watcher = {
let batches = batches.clone();
Watcher::start_with(
&root,
vec!["**/node_modules".into()],
sink,
Box::new(move |b| batches.lock().push(b.clone())),
WatchMode::PerDirectory,
)
.unwrap()
};
let deadline = Instant::now() + Duration::from_secs(10);
while watcher.watch_count() < dirs + 1 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
// root and every d*, but not node_modules
assert_eq!(watcher.watch_count(), dirs + 1);
std::thread::sleep(Duration::from_millis(200));
for i in [0, dirs - 1] {
let file = root.join(format!("d{i:03}/f.rs"));
std::fs::write(&file, "x").unwrap();
assert!(wait_for(&batches, |b| all_paths(b).contains(&file)), "{file:?}");
}
}
#[test]
fn per_directory_mode_follows_worktree_registrations() {
let tmp = tempfile::tempdir().unwrap();
@@ -1189,4 +1296,28 @@ mod tests {
std::fs::write(root.join("src/new/inner/h.rs"), "x").unwrap();
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("src/new/inner/h.rs"))));
}
#[test]
fn ordinary_watcher_errors_keep_the_bare_message() {
let other = notify::Error::io(std::io::Error::other("no space left"));
assert_eq!(
watcher_error("cannot start file watcher", other).message,
"cannot start file watcher: no space left"
);
}
#[cfg(target_os = "linux")]
#[test]
fn inotify_limits_get_a_sysctl_hint() {
let emfile = notify::Error::io(std::io::Error::from_raw_os_error(24));
let msg = watcher_error("cannot start file watcher", emfile).message;
assert!(msg.contains("os error 24"), "{msg}");
assert!(msg.contains("max_user_instances"), "{msg}");
let enospc = notify::Error::io(std::io::Error::from_raw_os_error(28));
assert!(watcher_error("cannot watch /proj", enospc).message.contains("max_user_watches"));
let max_files = notify::Error::new(ErrorKind::MaxFilesWatch);
assert!(watcher_error("cannot watch /proj", max_files).message.contains("max_user_watches"));
let other = notify::Error::io(std::io::Error::from_raw_os_error(13));
assert!(!watcher_error("cannot start file watcher", other).message.contains("inotify"));
}
}
+3 -2
Переглянути файл
@@ -69,7 +69,8 @@ test("⌘K commits the checked changes with the typed message", async ({ workben
await expect(page.getByText(/1 file committed: Return order DTOs from create/)).toBeVisible();
const [committed] = await ipcCalls(page, "vcs_commit");
expect(committed).toMatchObject({ repo: ROOT, message: "Return order DTOs from create" });
const staged = (await ipcCalls(page, "vcs_stage")).flatMap((a) => a.paths as string[]);
expect(staged).toEqual([`${ROOT}/build.gradle.kts`]);
// The commit takes the checked file itself; the index isn't staged beforehand.
expect((committed!.options as { stage: string[] }).stage).toEqual([`${ROOT}/build.gradle.kts`]);
expect(await ipcCalls(page, "vcs_stage")).toHaveLength(0);
await expect(changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
});
+6 -10
Переглянути файл
@@ -8,12 +8,11 @@ import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const NAMES = Array.from({ length: 20 }, (_, i) => `src/f${i}.ts`);
/** Twenty modified tracked files; `vcs_stage` + `vcs_commit` take the staged ones out of the status. */
/** Twenty modified tracked files; `vcs_commit` takes the files it commits out of the status. */
async function stubTwentyChanges(page: Page) {
await stubDesktop(page);
await page.evaluate(
async ({ root, names }) => {
const staged = new Set<string>();
const committed = new Set<string>();
const all = names.map((rel) => ({
path: `${root}/${rel}`,
@@ -33,14 +32,10 @@ async function stubTwentyChanges(page: Page) {
operation: null,
});
h.vcs_status = () => all.filter((f) => !committed.has(f.path));
h.vcs_stage = (args) => {
for (const path of args.paths as string[]) staged.add(path);
return null;
};
h.vcs_stage = () => null;
h.vcs_unstage = () => null;
h.vcs_commit = () => {
for (const path of staged) committed.add(path);
staged.clear();
h.vcs_commit = (args) => {
for (const path of (args.options as { stage: string[] }).stage) committed.add(path);
return "2222222";
};
const vcsModule = "/src/features/vcs/store.ts";
@@ -71,7 +66,8 @@ test("changes left out of a commit stay unchecked (#1539)", async ({ workbench:
await panel.getByRole("textbox", { name: "Commit message" }).fill("Commit 5 of 20");
await panel.getByRole("button", { name: "Commit", exact: true }).click();
await expect(page.getByText(/5 files committed: Commit 5 of 20/)).toBeVisible();
expect((await ipcCalls(page, "vcs_stage")).flatMap((a) => a.paths as string[]).sort()).toEqual(
const [commit] = await ipcCalls(page, "vcs_commit");
expect([...(commit!.options as { stage: string[] }).stage].sort()).toEqual(
NAMES.slice(0, 5)
.map((rel) => `${ROOT}/${rel}`)
.sort(),
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.6.0
Bundle-Version: 1.7.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+21 -5
Переглянути файл
@@ -12,6 +12,14 @@ The Rust bridge logs the failure once per project session. Cancelled requests an
changed source documents remain cancelled and do not start a fallback search.
No global `includeAccessors` preference is changed.
An optional fifth argument `"sources"` restricts the search to the workspace's
source folders (no dependency jars, no JDK). A library method can have thousands of
usages in those, which take seconds to search. Find Usages searches the sources alone
(Project Files) unless asked for Project and Libraries; then it shows the sources' usages
first and runs the full search after it. Rows in library classes (`jdt:` URIs) carry their
line as `text`, from the contents the client would request for the class, so the client
need not fetch thousands of class files to show them.
## Search plan and access semantics
For source fields on the verified JDT LS implementation, a single plan merges
@@ -20,10 +28,14 @@ Targets are deduplicated by JDT element identity before search, retaining native
search scope and ranges. Builder results remain unknown. The optimized native
plan is guarded by SHA-256 of ReferencesHandler.class:
`31ff5a10c7d69d58c6a9b619ef17e3ec41b11b545751ba428618a76cc1341064`
(JDT LS 1.63.0.202610191322). Different implementations, non-field selections and
library/decompiled selections retain native discovery plus deduplicated category
searches. This conservative fallback preserves coverage when the server changes;
it does not promise the same speedup on unverified versions.
(JDT LS 1.63.0.202610191322). On that version, non-field and library/decompiled
selections resolve their target as `ReferencesHandler.findReferences` does, and every
search replicates `ReferencesHandler.search` with one difference: a class file whose
decompiled source fails to parse loses only its own matches (logged), where the server
throws and fails the whole search after searching most dependencies. Different
implementations retain native discovery plus deduplicated category searches. This
conservative fallback preserves coverage when the server changes; it does not promise
the same speedup or fault isolation on unverified versions.
SearchEngine resolves exact targets. A query-local syntax AST per referenced source
file supplies expression context without another reference search: simple field
@@ -57,7 +69,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.6.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.7.0.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
@@ -87,6 +99,10 @@ Version 1.6.0 adds `openidea.java.configuration.warmup`, which builds configurat
low-priority background job after import, and builds them under cancellable per-project locks
instead of one global lock; its reproducible SHA-256 is
`33cfa1bb8489247ffeb6fc8249966c8a2955b7b2858c8169a70486eb70ade696`.
Version 1.7.0 adds the `"sources"` scope to `openidea.java.usages`, searches each class
file's decompiled source on its own and returns the line (`text`) of each usage in a library
class; its reproducible SHA-256 is
`56d35619d5be937b028ac143ba748365a66a74c803bc112e4788a7dce98b44fc`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
Бінарний файл не відображається.
+168 -22
Переглянути файл
@@ -4,13 +4,25 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchMatch;
import org.eclipse.jdt.core.search.SearchParticipant;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JDTUtils;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.SearchUtils;
import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers;
import org.eclipse.jdt.ls.core.internal.handlers.ReferencesHandler;
import org.eclipse.jdt.ls.core.internal.preferences.Preferences.SearchScope;
import org.eclipse.lsp4j.*;
/** Classifies search results using JDT method identities, never reference text. */
@@ -21,8 +33,14 @@ public final class UsagesCommand implements IDelegateCommandHandler {
int line = ((Number) arguments.get(1)).intValue();
int column = ((Number) arguments.get(2)).intValue();
boolean declarations = Boolean.TRUE.equals(arguments.get(3));
// "sources": the workspace's source folders only, without dependency jars or the JDK. A
// library method's usages there are found long before the full search ends.
boolean sources = arguments.size() > 4 && "sources".equals(arguments.get(4));
var preferences = JavaLanguageServerPlugin.getPreferencesManager();
var handler = new ReferencesHandler(preferences);
// The verified server's search is replicated (see `search`); others keep their own.
boolean replicated = sources || NATIVE_PLAN_SUPPORTED;
Search search = replicated ? (element, locations, m, d) -> search(element, locations, m, d, sources) : handler::search;
var params = new ReferenceParams(new TextDocumentIdentifier(uri), new Position(line, column), new ReferenceContext(declarations));
Map<Location, String> results = new LinkedHashMap<>();
ITypeRoot root = JDTUtils.resolveTypeRoot(uri);
@@ -31,40 +49,95 @@ public final class UsagesCommand implements IDelegateCommandHandler {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
boolean accessors = preferences.getPreferences().isIncludeAccessors();
SearchPlan plan = new SearchPlan();
// Only replace native target discovery for the exact implementation verified by
// integration tests. New server implementations retain their full native behavior.
if (selected instanceof IField field && root instanceof ICompilationUnit &&
root.getResource() != null && NATIVE_PLAN_SUPPORTED) {
plan.add(field, "field", declarations);
if (accessors) {
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
addNativeBuilderTargets(handler, field, plan);
addConfiguredAccessors(field, plan);
}
} else {
// Includes non-fields, library/decompiled roots, and unverified JDT LS builds.
for (var location : handler.findReferences(params, monitor)) results.put(location, "unknown");
if (selected instanceof IField field) {
ITypeRoot targetRoot = null;
try {
// Only replace native target discovery for the exact implementation verified by
// integration tests. New server implementations retain their full native behavior.
if (selected instanceof IField field && root instanceof ICompilationUnit &&
root.getResource() != null && NATIVE_PLAN_SUPPORTED) {
plan.add(field, "field", declarations);
if (accessors) {
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
addNativeBuilderTargets(handler, field, plan);
addConfiguredAccessors(field, plan);
}
} else if (replicated) {
// Non-fields and library/decompiled roots: the target ReferencesHandler.findReferences
// resolves (a class file without source through its decompiled working copy), widened
// as it widens a field.
boolean decompiled = preferences.isClientSupportsClassFileContent() && preferences.getPreferences().isIncludeDecompiledSources();
targetRoot = JDTUtils.resolveTypeRoot(uri, decompiled, monitor);
IJavaElement target = targetRoot == null ? null :
JDTUtils.findElementAtSelection(targetRoot, line, column, preferences, monitor);
if (target == null && targetRoot != null) {
target = targetRoot.getElementAt(JsonRpcHelpers.toOffset(targetRoot.getBuffer(), line, column));
}
plan.add(target, target instanceof IField ? "field" : "unknown", declarations);
if (accessors && target instanceof IField field) {
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
if (NATIVE_PLAN_SUPPORTED) addNativeBuilderTargets(handler, field, plan);
addConfiguredAccessors(field, plan);
}
} else {
// Unverified JDT LS builds.
for (var location : handler.findReferences(params, monitor)) results.put(location, "unknown");
if (selected instanceof IField field) {
plan.add(field, "field", declarations);
if (accessors) {
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
addConfiguredAccessors(field, plan);
}
}
}
}
for (var target : plan.targets.values()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
add(handler, target.element, target.kind(), target.declarations, results, monitor);
for (var target : plan.targets.values()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
add(search, target.element, target.kind(), target.declarations, results, monitor);
}
} finally {
if (targetRoot != null) JDTUtils.discardClassFileWorkingCopy(targetRoot);
}
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
List<Map<String, Object>> response = new ArrayList<>();
UsageAccess access = new UsageAccess(monitor, results);
results.forEach((location, kind) -> response.add(Map.of("location", location, "kind", kind, "access", access.classify(location, kind))));
Map<String, String[]> libraryLines = new java.util.HashMap<>();
for (var entry : results.entrySet()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
Location location = entry.getKey();
Map<String, Object> row = new LinkedHashMap<>();
row.put("location", location);
row.put("kind", entry.getValue());
row.put("access", access.classify(location, entry.getValue()));
String text = libraryLine(location, libraryLines, monitor);
if (text != null) row.put("text", text);
response.add(row);
}
return response;
}
/**
* The line of a usage in a library class (`jdt:` URI), from the contents the client would
* request for it: so the client need not fetch thousands of class files to show the lines.
*/
private static String libraryLine(Location location, Map<String, String[]> cache, IProgressMonitor monitor) {
String uri = location.getUri();
if (uri == null || !uri.startsWith("jdt:")) return null;
if (!cache.containsKey(uri)) {
String contents = null;
try {
contents = JavaLanguageServerPlugin.getContentProviderManager().getContent(JDTUtils.toURI(uri), monitor);
} catch (RuntimeException e) {
if (e instanceof org.eclipse.core.runtime.OperationCanceledException) throw e;
}
cache.put(uri, contents == null ? null : contents.split("\\r\\n?|\\n", -1));
}
String[] lines = cache.get(uri);
int line = location.getRange().getStart().getLine();
return lines != null && line >= 0 && line < lines.length ? lines[line] : null;
}
/** Resolve explicit Lombok @Accessors naming, then search exact JDT method identities.
* Configuration-file-only naming is deliberately not guessed.
*/
@@ -191,11 +264,84 @@ public final class UsagesCommand implements IDelegateCommandHandler {
(resolved[0][0].isEmpty() ? resolved[0][1] : resolved[0][0] + "." + resolved[0][1]).equals(owner.getFullyQualifiedName());
}
private static void add(ReferencesHandler handler, IJavaElement element, String kind, boolean declarations,
private interface Search {
void run(IJavaElement element, List<Location> locations, IProgressMonitor monitor, boolean declarations) throws Exception;
}
/**
* ReferencesHandler.search of the verified server, except that a class file whose decompiled
* source fails to parse loses only its own matches: there the server throws and fails the
* whole search, after searching most of the dependencies. `sources`: the workspace's source
* folders only, without dependency jars and the JDK.
*/
private static void search(IJavaElement element, List<Location> locations, IProgressMonitor monitor,
boolean declarations, boolean sources) throws CoreException {
SearchPattern pattern = SearchPattern.createPattern(element, IJavaSearchConstants.REFERENCES);
if (pattern == null) return;
if (declarations) {
SearchPattern declaration = SearchPattern.createPattern(element, IJavaSearchConstants.DECLARATIONS);
if (declaration != null) pattern = SearchPattern.createOrPattern(pattern, declaration);
}
var preferences = JavaLanguageServerPlugin.getPreferencesManager();
SearchScope setting = preferences.getPreferences().getSearchScope();
int mask = IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS;
if (!sources && setting != SearchScope.projectOnly) {
mask |= IJavaSearchScope.APPLICATION_LIBRARIES;
if (insideJre(element)) mask |= IJavaSearchScope.SYSTEM_LIBRARIES;
}
IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
IJavaSearchScope scope = SearchEngine.createJavaSearchScope(setting == SearchScope.main, projects, mask);
boolean classFiles = preferences.isClientSupportsClassFileContent();
boolean decompiled = preferences.getPreferences().isIncludeDecompiledSources();
new SearchEngine().search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (match.getAccuracy() == SearchMatch.A_INACCURATE || !(match.getElement() instanceof IJavaElement found)) return;
if (found.getAncestor(IJavaElement.COMPILATION_UNIT) instanceof ICompilationUnit unit) {
locations.add(JDTUtils.toLocation(unit, match.getOffset(), match.getLength()));
return;
}
if (!classFiles || !(found.getAncestor(IJavaElement.CLASS_FILE) instanceof IClassFile classFile)) return;
if (classFile.getSourceRange() != null) {
locations.add(JDTUtils.toLocation(classFile, match.getOffset(), match.getLength()));
return;
}
if (!decompiled) return;
try {
if (found instanceof IMember member) {
Location location = SearchUtils.searchOtherSources(member);
if (location != null) locations.add(location);
}
locations.addAll(JDTUtils.searchDecompiledSources(found, classFile, false, false, monitor));
} catch (org.eclipse.core.runtime.OperationCanceledException e) {
throw e;
} catch (RuntimeException | CoreException e) {
JavaLanguageServerPlugin.logInfo("Usages in decompiled " + classFile.getElementName() + " skipped: " + e);
}
}
}, monitor);
}
/** ReferencesHandler.isInsideJRE: a JDK element is searched in the JDK too. */
private static boolean insideJre(IJavaElement element) {
if (!(element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT) instanceof IPackageFragmentRoot root)) return true;
try {
IClasspathEntry entry = root.getRawClasspathEntry();
if (entry.getEntryKind() != IClasspathEntry.CPE_CONTAINER) return false;
IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), root.getJavaProject());
return container != null && container.getKind() == IClasspathContainer.K_DEFAULT_SYSTEM;
} catch (JavaModelException e) {
JavaLanguageServerPlugin.logException(e);
return true;
}
}
private static void add(Search search, IJavaElement element, String kind, boolean declarations,
Map<Location, String> results, IProgressMonitor monitor) throws Exception {
if (element == null) return;
List<Location> locations = new ArrayList<>();
handler.search(element, locations, monitor, declarations);
search.run(element, locations, monitor, declarations);
for (var location : locations) {
if (kind.equals("unknown")) { results.putIfAbsent(location, kind); continue; }
String previous = results.get(location);
+13
Переглянути файл
@@ -106,6 +106,14 @@ def request(method, params):
if 'error' in msg: raise RuntimeError(msg['error'])
return msg.get('result')
raise TimeoutError(method)
def assert_sources(line, col, full=None):
"""The "sources" scope finds what the full search finds in the workspace's sources."""
usages = lambda *scope: request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),line,col,False,*scope]})
full = usages() if full is None else full
sources = usages('sources')
key = lambda rows: sorted(json.dumps(r, sort_keys=True) for r in rows)
assert key(sources) == key(r for r in full if r['location']['uri'].startswith('file:')), (line, col, sources, full)
return sources
try:
init = request('initialize', {'processId':None, 'rootUri':project.as_uri(), 'workspaceFolders':[{'uri':project.as_uri(), 'name':'accessors'}], 'capabilities':{}, 'initializationOptions':{'bundles':[str(bundle)], 'settings':{'java':{'references':{'includeAccessors':True}, 'import':{'gradle':{'enabled':False}, 'maven':{'enabled':False}}}}}})
send({'jsonrpc':'2.0','method':'initialized','params':{}})
@@ -123,6 +131,11 @@ try:
assert kinds.count('getter') == expected[0], (field, kinds)
assert kinds.count('setter') == expected[1], (field, kinds)
assert kinds.count('field') == expected[2], (field, kinds)
assert_sources(line, col, after)
# A JDK method: in the sources, the same as the full search's sources part.
line, text = next((i, t) for i, t in enumerate(source.splitlines()) if 'println' in t)
evidence['jdkSources'] = assert_sources(line, text.index('println'))
assert evidence['jdkSources'], 'no JDK method usages in the sources'
# Respect the existing global preference: the command must not switch it on.
send({'jsonrpc':'2.0','method':'workspace/didChangeConfiguration','params':{'settings':{'java':{'references':{'includeAccessors':False}}}}})
disabled = request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),3,19,False]})
+30 -1
Переглянути файл
@@ -94,6 +94,8 @@ homepage = "https://example.com" # optional
license = "MIT" # optional
change-notes = "1.2.0 — …" # shown under What's New
categories = ["tools"] # marketplace categories, see below
icon = "icon.svg" # optional, see below
icon-dark = "icon_dark.svg" # optional
engines.openidea = "^1.0" # the plugin API this package needs
wasm = "dist/plugin.wasm" # omit for data-only plugins
activation = ["on-language:markdown"] # optional, see below
@@ -116,6 +118,14 @@ icon themes or languages is filed under those, any other under `other`.
Categories an IDE doesn't know, and any after the first three it knows, are
ignored (`check` warns about both).
`icon` is an SVG of the package shown in Settings › Plugins and the
marketplace; `icon-dark`, if given, replaces it with dark themes. Each is at
most 16 KiB and sanitised like file icons (no scripts, external references or
`foreignObject`); an invalid one fails the package. Without `icon`, the
plugin gets the generic plugin icon. `icon` is new in API 1.2: IDEs before it
refuse the manifest, so a package with one declares `engines.openidea = "^1.2"`
(`check` and installing refuse it otherwise).
All paths are relative to the package directory and may not leave it. A
manifest is validated as a whole: if one contribution is invalid, nothing is
installed or loaded. Contribution types the IDE does not know (a newer API) are
@@ -136,7 +146,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?` (§6.2) | no |
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `tools`), `command`, `when?` | no |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`), `view?`, `command`, `when?` | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
| `settings` | `schema` (JSON file), `title?` — one table, see _Settings_ | no |
@@ -145,6 +155,25 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no |
| `fileTemplates` | `id`, `name`, `extension`, `path` (the new file's content; template variables work) — New menu | no |
A `viewItem.context` menu needs `view`, the id of one of the plugin's own
views. It adds the commands to the right-click menu of the items in that
view's `tree` or `list`, and each command gets the item's key as its argument.
`when` clauses can use `viewItem` (the key) and `viewItemKind` (the key up to
its first `:`, so `pod` for `pod:default/nginx`; the whole key when it has no
`:`). Only the menu's `when` sees them, not the command's own `when`; a command
whose `when` is false shows greyed out. Other menus refuse `view`, a web view
has no item menu, and no menu opens when no declaration matches the item.
The menu is new in API 1.2, so a plugin using it declares
`engines.openidea = "^1.2"`. For example:
```toml
[[contributes.menus]]
menu = "viewItem.context"
view = "pods"
command = "kube.logs"
when = "viewItemKind == pod"
```
Declared contributions are live as soon as the plugin is enabled — commands
show in Find Action, menus and the status bar, shortcuts work, themes and icon
themes can be applied, settings pages are there — **before** any plugin code
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c29594e55d321ee5240f8f61223d72c9095695a5b19ff1f8a25c5a6402a4a736
5e7f7adc2c49503d2278ed2a446f18f69561ce51df264100f77f50d69804c277
+57 -1
Переглянути файл
@@ -70,6 +70,51 @@ fn ident(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
/// Index of the `(` opening a method's parameter list inside a declaration
/// fragment. `(`s that belong to annotation arguments — `@Anno(…)` — are
/// skipped so `@DataPermission(column = "id") int count()` finds the paren
/// after `count`, not the one after `DataPermission`.
fn method_paren(stmt: &str) -> Option<usize> {
let mut rest = stmt;
let mut base = 0;
while let Some(i) = rest.find('(') {
// Is the token right before this `(` an annotation name (`@Anno`, `@a.b.Anno`)?
let before = rest[..i].trim_end();
let annotation = before.rfind('@').is_some_and(|a| before[a + 1..].chars().all(|c| ident(c) || c == '.'));
if !annotation {
return Some(base + i);
}
// Skip the annotation's argument list (it may nest and hold literals).
let mut depth = 1usize;
let mut end = None;
let mut chars = rest[i + 1..].char_indices().peekable();
while let Some((j, c)) = chars.next() {
match c {
'"' | '\'' => {
for (_, d) in chars.by_ref() {
if d == c {
break;
}
}
}
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
end = Some(i + 1 + j + 1);
break;
}
}
_ => {}
}
}
let skip = end?;
base += skip;
rest = &rest[skip..];
}
None
}
/// The interface's name and methods (with their parameter names).
pub fn parse_java(text: &str) -> MapperJava {
let package =
@@ -95,7 +140,7 @@ pub fn parse_java(text: &str) -> MapperJava {
}
';' if depth == 0 => {
let stmt = &text[stmt_start..k];
if let Some(paren) = stmt.find('(') {
if let Some(paren) = method_paren(stmt) {
let before = stmt[..paren].trim_end();
let name_start = before.rfind(|c: char| !ident(c)).map_or(0, |p| p + 1);
let method = &before[name_start..];
@@ -361,6 +406,17 @@ mod tests {
assert_eq!(n.line_markers(&xml)[0].tooltip, "Go to UserMapper.findById()");
}
#[test]
fn method_annotations_do_not_swallow_the_method_name() {
// A method-level annotation with arguments: `stmt.find('(')` would land
// inside `@DataPermission(…)` and read `DataPermission` as the name.
let java = parse_java(
"package com.acme;\n\npublic interface SecuredMapper {\n @DataPermission(column = \"id\", scope = (@Scope(\"self\")))\n List<User> findAll(@Param(\"org\") String org);\n\n @org.acme.Check(value = \"(nested)\")\n int count();\n}\n",
);
let names: Vec<_> = java.methods.iter().map(|(m, p)| (m.name.as_str(), p.clone())).collect();
assert_eq!(names, [("findAll", vec!["org".to_owned()]), ("count", Vec::<String>::new())]);
}
#[test]
fn completes_ids_and_parameters() {
let _host = setup();
+1 -1
Переглянути файл
@@ -109,7 +109,7 @@ afterEach(() => {
resetRuns();
disconnect?.();
server?.close();
if (base) rmSync(base, { recursive: true, force: true });
if (base) rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
});
async function open(c: Case): Promise<string> {
+1 -1
Переглянути файл
@@ -133,7 +133,7 @@ afterEach(() => {
resetRuns();
disconnect?.();
server?.close();
if (base) rmSync(base, { recursive: true, force: true });
if (base) rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
});
async function open(c: Case): Promise<string> {
+1 -1
Переглянути файл
@@ -66,7 +66,7 @@ pub fn observe(app: &tauri::AppHandle) {
}
}
fn application_active(app: &tauri::AppHandle) -> bool {
pub(crate) fn application_active(app: &tauri::AppHandle) -> bool {
// A settings window, utility window or native dialog is still this application.
#[cfg(target_os = "macos")]
{
+7
Переглянути файл
@@ -314,6 +314,13 @@ pub async fn project_trust_set(
Ok(())
}
#[tauri::command]
#[specta::specta]
pub async fn project_trust_add_location(state: State<'_, AppState>, path: PathBuf) -> IdeResult<()> {
state.trust.add_location(&path)?;
state.host.refresh_project_trust().await
}
#[tauri::command]
#[specta::specta]
pub async fn project_trust_remove_location(state: State<'_, AppState>, path: PathBuf) -> IdeResult<()> {
+10 -1
Переглянути файл
@@ -136,9 +136,13 @@ pub async fn lsp_resolve_class_file(
/// References of the symbol at `pos`. `project_wide` also searches project files
/// outside the language server's analysis scope; bulk scans over many symbols
/// leave it off. Cancel with `cancel_request(request)`.
/// leave it off. Java, `project_wide`: without `libraries`, the dependencies and the JDK
/// are not searched; with it, those found in the sources arrive on `on_partial` before
/// the slower search for the rest, and the result has them all. Cancel with
/// `cancel_request(request)`.
#[tauri::command]
#[specta::specta]
#[allow(clippy::too_many_arguments)]
pub async fn lsp_references(
window: Window,
state: State<'_, AppState>,
@@ -147,7 +151,10 @@ pub async fn lsp_references(
pos: Pos,
include_declaration: bool,
project_wide: bool,
libraries: bool,
on_partial: tauri::ipc::Channel<References>,
) -> IdeResult<References> {
let on_partial = super::sender(on_partial);
ide_host::ops::lsp::lsp_references(
&state.host,
window.label(),
@@ -156,6 +163,8 @@ pub async fn lsp_references(
pos,
include_declaration,
project_wide,
libraries,
on_partial,
)
.await
}
+1
Переглянути файл
@@ -75,6 +75,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
app::project_trust_status,
app::project_trust_list,
app::project_trust_set,
app::project_trust_add_location,
app::project_trust_remove_location,
workspace::workspace_create,
workspace::workspace_attach,
+6 -2
Переглянути файл
@@ -20,8 +20,12 @@ pub async fn sdk_detect(window: Window, state: State<'_, AppState>, kind: SdkKin
/// The interpreter the project uses: the configured one, else its virtualenv.
#[tauri::command]
#[specta::specta]
pub fn sdk_python_effective(window: Window, state: State<'_, AppState>) -> IdeResult<Option<ide_core::IpcPath>> {
ide_host::ops::sdk::sdk_python_effective(&state.host, window.label())
pub fn sdk_python_effective(
window: Window,
state: State<'_, AppState>,
near: Option<PathBuf>,
) -> IdeResult<Option<ide_core::IpcPath>> {
ide_host::ops::sdk::sdk_python_effective(&state.host, window.label(), near)
}
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
+71 -20
Переглянути файл
@@ -214,7 +214,9 @@ pub fn app_cancel_quit(app: AppHandle, windows: State<'_, WindowsState>) {
});
}
/// Sets the menu's labels / shortcut text (on locale or keymap change) and rebuilds it.
/// Sets the menu's labels / shortcut text and rebuilds it when they changed.
/// Focusing another project window re-pushes the same shared menu; an identical
/// config must not call `set_menu`, which redraws the macOS menu bar.
#[tauri::command]
#[specta::specta]
pub fn menu_configure(
@@ -223,8 +225,9 @@ pub fn menu_configure(
state: State<'_, AppState>,
config: MenuConfig,
) {
*menu_state.config.lock() = config;
menu::install(&app, &menu_state, &state.recent.list());
if menu::store_config(&menu_state, config) {
menu::install(&app, &menu_state, &state.recent.list());
}
}
/// Rebuilds the menu (e.g. after the recent-projects list changed).
@@ -330,36 +333,74 @@ fn update_endpoint_env() -> Option<String> {
/// tauri.conf.json, or the `OPENIDEA_UPDATE_ENDPOINT` environment variable. Empty by
/// default, and "Check for Updates…" is hidden then.
pub fn updates_configured<R: tauri::Runtime>(app: &AppHandle<R>) -> bool {
let in_config = app
.config()
!config_endpoints(app).is_empty() || update_endpoint_env().is_some()
}
/// Where updates are downloaded from (System Settings › Updates).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum UpdateSource {
/// The GitHub releases named in tauri.conf.json.
#[default]
Github,
/// The CNB mirror of the same releases, for networks where GitHub is slow.
Cnb,
}
const CNB_ENDPOINT: &str = "https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json";
fn config_endpoints<R: tauri::Runtime>(app: &AppHandle<R>) -> Vec<String> {
app.config()
.plugins
.0
.get("updater")
.and_then(|u| u.get("endpoints"))
.and_then(|e| e.as_array())
.is_some_and(|e| !e.is_empty());
in_config || update_endpoint_env().is_some()
.map(|e| e.iter().filter_map(|u| u.as_str().map(String::from)).collect())
.unwrap_or_default()
}
fn updater(app: &AppHandle) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
/// The endpoints tried in order: `source` first, the other source when it fails or has
/// no manifest. Bundles are signed, so either source's manifest and downloads verify.
/// No official endpoint (a build without updates) means no mirror either.
fn source_endpoints(official: Vec<String>, source: UpdateSource) -> Vec<String> {
if official.is_empty() {
return official;
}
let mirror = vec![CNB_ENDPOINT.to_string()];
match source {
UpdateSource::Github => [official, mirror].concat(),
UpdateSource::Cnb => [mirror, official].concat(),
}
}
fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
use tauri_plugin_updater::UpdaterExt;
if !updates_configured(app) {
return Ok(None);
}
let env = update_endpoint_env();
let endpoints = match update_endpoint_env() {
Some(url) => vec![url],
None => source_endpoints(config_endpoints(app), source),
};
let endpoints = endpoints
.iter()
.map(|u| u.parse().map_err(|e| IdeError::invalid(format!("update endpoint {u}: {e}"))))
.collect::<IdeResult<Vec<_>>>()?;
let proxy = ide_core::proxy_settings::proxy();
let mut builder = app.updater_builder().configure_client(move |b| ide_http::client::with_proxy(b, &proxy));
if let Some(url) = env {
let url = url.parse().map_err(|e| IdeError::invalid(format!("OPENIDEA_UPDATE_ENDPOINT: {e}")))?;
builder = builder.endpoints(vec![url]).map_err(|e| IdeError::invalid(e.to_string()))?;
}
builder.build().map(Some).map_err(|e| IdeError::unavailable(e.to_string()))
app.updater_builder()
.configure_client(move |b| ide_http::client::with_proxy(b, &proxy))
.endpoints(endpoints)
.map_err(|e| IdeError::invalid(e.to_string()))?
.build()
.map(Some)
.map_err(|e| IdeError::unavailable(e.to_string()))
}
#[tauri::command]
#[specta::specta]
pub async fn app_check_update(app: AppHandle) -> IdeResult<UpdateCheck> {
let Some(updater) = updater(&app)? else {
pub async fn app_check_update(app: AppHandle, source: UpdateSource) -> IdeResult<UpdateCheck> {
let Some(updater) = updater(&app, source)? else {
return Ok(UpdateCheck { enabled: false, update: None });
};
let update = updater.check().await.map_err(|e| IdeError::unavailable(e.to_string()))?;
@@ -379,12 +420,12 @@ pub async fn app_check_update(app: AppHandle) -> IdeResult<UpdateCheck> {
/// not reported: the user didn't ask for this check.
#[tauri::command]
#[specta::specta]
pub async fn app_startup_update_check(app: AppHandle) -> Option<UpdateInfo> {
pub async fn app_startup_update_check(app: AppHandle, source: UpdateSource) -> Option<UpdateInfo> {
static DONE: AtomicBool = AtomicBool::new(false);
if cfg!(debug_assertions) || DONE.swap(true, Ordering::SeqCst) {
return None;
}
match app_check_update(app).await {
match app_check_update(app, source).await {
Ok(check) => check.update,
Err(e) => {
tracing::warn!("startup update check failed: {e}");
@@ -452,6 +493,7 @@ impl Drop for InstallingGuard {
pub async fn app_install_update(
app: AppHandle,
state: State<'_, AppState>,
source: UpdateSource,
request: RequestId,
on_progress: Channel<UpdateProgress>,
) -> IdeResult<()> {
@@ -459,7 +501,7 @@ pub async fn app_install_update(
InstallingGuard::acquire().ok_or_else(|| IdeError::unavailable("an update is already being installed"))?;
let token = state.host.begin_request(request);
let result = async {
let updater = updater(&app)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
let updater = updater(&app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
let update = tokio::select! {
r = updater.check() => r.map_err(|e| IdeError::unavailable(e.to_string()))?,
_ = token.cancelled() => return Err(IdeError::cancelled()),
@@ -522,6 +564,15 @@ mod tests {
assert!(ProgressThrottle::default().chunk(1, Some(0)).is_some());
}
#[test]
fn chosen_source_is_tried_first_and_the_other_after_it() {
let github = "https://github.com/l0ng-ai/openidea/releases/latest/download/latest.json".to_string();
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Github), [github.clone(), CNB_ENDPOINT.into()]);
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb), [CNB_ENDPOINT.into(), github]);
// A build without an update endpoint stays without one.
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
}
#[test]
fn only_one_install_at_a_time() {
let first = InstallingGuard::acquire().expect("first install starts");
+24 -1
Переглянути файл
@@ -1,5 +1,5 @@
use ide_core::{EventSink, IdeEvent};
use tauri::{AppHandle, Emitter};
use tauri::{AppHandle, Emitter, Manager, UserAttentionType};
/// Name of the single backend → UI event. Payload: [`IdeEvent`].
pub const IDE_EVENT: &str = "ide://event";
@@ -38,8 +38,31 @@ pub struct TauriSink {
pub window: Option<String>,
}
/// A debug session stopped on a breakpoint: bounce/flash the taskbar icon
/// (IDEA) unless the user is already looking at an OpenIDEA window. The focus
/// check and the request both touch the windowing system, so they run on the
/// main thread; `emit` itself can come from any debug worker thread.
fn flash_taskbar_unless_focused(app: &AppHandle) {
let handle = app.clone();
let _ = app.run_on_main_thread(move || {
if crate::application_focus::application_active(&handle) {
return;
}
for window in handle.webview_windows().values() {
let _ = window.request_user_attention(Some(UserAttentionType::Informational));
}
});
}
impl EventSink for TauriSink {
fn emit(&self, event: IdeEvent) {
if matches!(
&event,
IdeEvent::Debug { event: ide_core::event::DebugEvent::Stopped { reason, .. }, .. }
if matches!(reason.as_str(), "breakpoint" | "function breakpoint")
) {
flash_taskbar_unless_focused(&self.app);
}
let result = match &self.window {
Some(label) => {
for target in crate::windows::document_windows(&self.app, label) {
+8 -1
Переглянути файл
@@ -174,6 +174,8 @@ pub fn run() {
app.manage(windows);
app.manage(application_focus::ApplicationFocus::default());
#[cfg(target_os = "macos")]
macos::intercept_system_quit(app.handle());
#[cfg(target_os = "macos")]
application_focus::observe(app.handle());
app.manage(menu_state);
if let Some(paths) = setup_opens.lock().take() {
@@ -234,6 +236,7 @@ pub fn run() {
let _ = &early_opens;
if let tauri::RunEvent::Exit = event {
if let Some(state) = app.try_state::<AppState>() {
state.host.stop_processes_on_exit();
state.host.clear_workspace_edit_history_on_exit();
state.host.shutdown_notebooks_on_exit();
}
@@ -253,7 +256,11 @@ fn window_state_flags() -> tauri_plugin_window_state::StateFlags {
/// Routes IDE menu items to the focused window's frontend (`executeAction`).
fn on_menu_event(app: &tauri::AppHandle, event: tauri::menu::MenuEvent) {
let id = event.id().as_ref();
dispatch_menu_action(app, event.id().as_ref());
}
/// Runs menu item `id` as if it were chosen: in the focused window's frontend, or here without one.
pub(crate) fn dispatch_menu_action(app: &tauri::AppHandle, id: &str) {
let Some(route) = menu::route(&menu::spec(menu::Os::current()), id) else { return };
match windows::target_window(app) {
Some(w) => {
+127 -3
Переглянути файл
@@ -7,8 +7,9 @@ use objc2::{
rc::Retained,
runtime::{AnyClass, AnyObject, Imp, ProtocolObject, Sel},
};
use objc2_app_kit::{NSWindow, NSWindowUserTabbingPreference};
use objc2_app_kit::{NSWindow, NSWindowAnimationBehavior, NSWindowUserTabbingPreference};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSRect};
use std::cell::Cell;
use tauri::{AppHandle, Manager, WebviewWindow};
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
@@ -202,6 +203,43 @@ fn present(fullscreen: bool) {
NSApplication::sharedApplication(mtm).setPresentationOptions(options);
}
type ShouldTerminate = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject) -> usize;
/// `NSApplicationTerminateReply`.
const TERMINATE_CANCEL: usize = 0;
const TERMINATE_NOW: usize = 1;
/// The Dock's Quit, the system's app menu and a logout ask the application delegate whether it
/// may terminate; tao's delegate doesn't answer, so AppKit terminated at once, past the exit,
/// running-process and unsaved-changes prompts. Answer it: cancel, and quit like Cmd+Q does.
pub fn intercept_system_quit(app: &AppHandle) {
let _ = APP.set(app.clone());
let Some(mtm) = MainThreadMarker::new() else { return };
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
unsafe {
let delegate: *mut AnyObject = objc2::msg_send![&*application, delegate];
if delegate.is_null() {
return;
}
let class = objc2::ffi::object_getClass(delegate.cast()) as *mut AnyClass;
let imp: Imp = std::mem::transmute(should_terminate as ShouldTerminate);
let added = objc2::ffi::class_addMethod(class, objc2::sel!(applicationShouldTerminate:), imp, c"Q@:@".as_ptr());
if !added.as_bool() {
tracing::warn!("could not handle applicationShouldTerminate:");
}
}
}
unsafe extern "C-unwind" fn should_terminate(_this: *mut AnyObject, _selector: Sel, _sender: *mut AnyObject) -> usize {
let Some(app) = APP.get() else { return TERMINATE_NOW };
// Our own quit exits through the event loop; a system quit during it goes ahead.
if app.try_state::<WindowsState>().is_none_or(|w| w.quitting()) {
return TERMINATE_NOW;
}
crate::dispatch_menu_action(app, "app.quit");
TERMINATE_CANCEL
}
type ToggleFullScreen = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject);
static NATIVE_TOGGLE_FULLSCREEN: std::sync::OnceLock<ToggleFullScreen> = std::sync::OnceLock::new();
@@ -238,16 +276,102 @@ type ConstrainFrameRect = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, NSRec
static NATIVE_CONSTRAIN_FRAME_RECT: std::sync::OnceLock<ConstrainFrameRect> = std::sync::OnceLock::new();
thread_local! {
/// Native window whose next frame assignment must keep the rectangle it was given.
static EXACT_FRAME: Cell<usize> = const { Cell::new(0) };
}
struct ExactFrame(usize);
impl ExactFrame {
fn begin(native: usize) -> Self {
EXACT_FRAME.with(|slot| slot.set(native));
Self(native)
}
}
impl Drop for ExactFrame {
fn drop(&mut self) {
EXACT_FRAME.with(|slot| {
if slot.get() == self.0 {
slot.set(0);
}
});
}
}
/// Copies `from`'s frame onto `to`. `setFrame:display:animate:` finishes before it returns;
/// tao's position and size setters only schedule the change.
pub fn copy_window_frame(from: &WebviewWindow, to: &WebviewWindow) -> tauri::Result<()> {
apply_window_frame(from, to, false)
}
/// Copies the frame and orders `to` front before AppKit can animate or constrain it.
/// A later `show` runs `constrainFrameRect:toScreen:` and slides a titled window into place.
pub fn present_window_frame(from: &WebviewWindow, to: &WebviewWindow) -> tauri::Result<()> {
apply_window_frame(from, to, true)
}
fn apply_window_frame(from: &WebviewWindow, to: &WebviewWindow, show: bool) -> tauri::Result<()> {
if MainThreadMarker::new().is_some() {
return apply_window_frame_on_main(from, to, show);
}
let (tx, rx) = std::sync::mpsc::sync_channel(1);
let from = from.clone();
let to = to.clone();
to.clone().run_on_main_thread(move || {
let _ = tx.send(apply_window_frame_on_main(&from, &to, show));
})?;
rx.recv().map_err(|error| tauri::Error::Io(std::io::Error::other(error.to_string())))?
}
fn apply_window_frame_on_main(from: &WebviewWindow, to: &WebviewWindow, show: bool) -> tauri::Result<()> {
let source_pointer = from.ns_window()?;
let target_pointer = to.ns_window()?;
unsafe {
let source = &*source_pointer.cast::<NSWindow>();
let target = &*target_pointer.cast::<NSWindow>();
let frame = source.frame();
let current = target.frame();
let differs = frame.origin.x != current.origin.x
|| frame.origin.y != current.origin.y
|| frame.size.width != current.size.width
|| frame.size.height != current.size.height;
if !differs && !show {
return Ok(());
}
// Zoom and ordering use the window's animation behavior. `animate: false` alone does not
// stop a zoomed window from sliding to the new frame as it is shown.
let behavior = target.animationBehavior();
target.setAnimationBehavior(NSWindowAnimationBehavior::None);
let result = (|| {
let _exact = ExactFrame::begin(target_pointer as usize);
if differs {
target.setFrame_display_animate(frame, false, false);
}
if show {
to.show()?;
to.set_focus()?;
}
Ok(())
})();
target.setAnimationBehavior(behavior);
result
}
}
/// AppKit keeps a titled window's top edge below the menu bar, and on a notched display below the
/// camera housing, whenever the window is placed, shown or resized. A window in simple fullscreen
/// is titled for its buttons but must still cover the whole screen.
/// is titled for its buttons but must still cover the whole screen. A group-tab frame copy also
/// keeps the rectangle it was given, so the window about to be shown is not shifted.
unsafe extern "C-unwind" fn constrain_frame_rect(
this: *mut AnyObject,
selector: Sel,
frame: NSRect,
screen: *mut AnyObject,
) -> NSRect {
if COVERING.with_borrow(|windows| windows.values().any(|covering| covering.native == this as usize)) {
let exact = EXACT_FRAME.with(|slot| slot.get() == this as usize);
if exact || COVERING.with_borrow(|windows| windows.values().any(|covering| covering.native == this as usize)) {
return frame;
}
match NATIVE_CONSTRAIN_FRAME_RECT.get() {
+22 -1
Переглянути файл
@@ -895,7 +895,7 @@ pub fn action_ids(spec: &[Entry]) -> Vec<&'static str> {
}
/// Localised labels and displayed shortcuts, pushed by the frontend.
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MenuConfig {
pub locale: String,
@@ -961,6 +961,17 @@ pub struct MenuState {
pub disabled: Mutex<HashSet<String>>,
}
/// Stores `next` when it differs from the config last used to build the menu.
/// Callers must not replace the menu on `false`: `set_menu` redraws the macOS menu bar.
pub fn store_config(state: &MenuState, next: MenuConfig) -> bool {
let mut current = state.config.lock();
if *current == next {
return false;
}
*current = next;
true
}
/// The action an item id stands for, if it is an IDE action item.
fn item_action(id: &str) -> Option<&str> {
if id.starts_with(RECENT_PREFIX) || id == "recent.none" || id.starts_with("submenu:") {
@@ -1267,6 +1278,16 @@ mod tests {
}
}
#[test]
fn unchanged_menu_config_is_not_rebuilt() {
let state = MenuState::default();
let mut config = MenuConfig { locale: "en".into(), ..MenuConfig::default() };
assert!(store_config(&state, config.clone()));
assert!(!store_config(&state, config.clone()));
config.labels.insert("menu.file".into(), "File".into());
assert!(store_config(&state, config));
}
#[test]
fn recent_items_route_to_open_recent_with_path() {
let spec = spec(Os::Mac);
+196 -54
Переглянути файл
@@ -56,30 +56,76 @@ fn changed(app: &AppHandle) {
app.state::<AppState>().sink.emit(IdeEvent::WindowGroupsChanged);
}
/// Whether `to` already presents `from`'s frame, so moving it would only make it flicker.
fn same_frame(from: &WebviewWindow, to: &WebviewWindow) -> bool {
let (Ok(from_max), Ok(to_max)) = (from.is_maximized(), to.is_maximized()) else { return false };
let (Ok(from_full), Ok(to_full)) = (from.is_fullscreen(), to.is_fullscreen()) else { return false };
if from_max != to_max || from_full != to_full {
return false;
/// Outer frame in physical pixels. A maximized window is represented by the rectangle it
/// occupies, not by the maximized flag: that flag can match while the rectangles do not.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct OuterFrame {
x: i32,
y: i32,
width: u32,
height: u32,
}
/// Where a group member can be placed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FrameHost {
/// The client can move and resize the window.
Desktop,
/// Wayland does not let clients place top-level windows.
#[cfg_attr(not(any(target_os = "linux", test)), allow(dead_code))]
Wayland,
/// macOS simple fullscreen already covers the screen; rewriting the frame would shrink it.
SimpleFullscreen,
/// Native fullscreen owns a Space. A different frame is transferred, not assigned.
NativeFullscreen,
}
/// What to write before the target window is shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FrameWrite {
/// Already the same rectangle, or this host must not be placed.
Leave,
TransferFullscreen,
Assign(OuterFrame),
}
/// Two windows are aligned only when their outer rectangles match. Maximized or fullscreen
/// flags are not a substitute: `show` presents the current rectangle, and a later move is visible.
fn frame_write(host: FrameHost, from: OuterFrame, to: OuterFrame) -> FrameWrite {
match host {
FrameHost::Wayland | FrameHost::SimpleFullscreen => FrameWrite::Leave,
FrameHost::NativeFullscreen if from == to => FrameWrite::Leave,
FrameHost::NativeFullscreen => FrameWrite::TransferFullscreen,
FrameHost::Desktop if from == to => FrameWrite::Leave,
FrameHost::Desktop => FrameWrite::Assign(from),
}
let same_monitor = match (from.current_monitor(), to.current_monitor()) {
(Ok(Some(a)), Ok(Some(b))) => a.position() == b.position() && a.size() == b.size(),
// An unmapped window may not report a monitor; treat only equal states as matching.
(Ok(None), Ok(None)) | (Err(_), Err(_)) => true,
_ => false,
};
if !same_monitor {
return false;
}
fn outer_frame(window: &WebviewWindow) -> IdeResult<OuterFrame> {
let err = |error: tauri::Error| IdeError::internal(error.to_string());
let position = window.outer_position().map_err(err)?;
let size = window.outer_size().map_err(err)?;
Ok(OuterFrame { x: position.x, y: position.y, width: size.width, height: size.height })
}
fn frame_host(from: &WebviewWindow) -> IdeResult<FrameHost> {
if simple_fullscreen(from.label()) {
return Ok(FrameHost::SimpleFullscreen);
}
from_full
|| from_max
|| (from.outer_position().ok() == to.outer_position().ok() && from.inner_size().ok() == to.inner_size().ok())
#[cfg(target_os = "linux")]
if crate::linux_window_state::is_wayland() {
return Ok(FrameHost::Wayland);
}
if from.is_fullscreen().map_err(|error| IdeError::internal(error.to_string()))? {
return Ok(FrameHost::NativeFullscreen);
}
Ok(FrameHost::Desktop)
}
/// Moves a hidden window onto `from`'s monitor. A restored window keeps its normal position on
/// the monitor it last occupied; maximizing or going fullscreen there would make the window
/// visibly jump across displays when its tab is selected.
/// visibly jump across displays when its tab is selected. macOS copies the AppKit frame instead.
#[cfg(not(target_os = "macos"))]
fn place_on_monitor(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
// Wayland does not let clients place top-level windows; maximizing stays on that output.
#[cfg(target_os = "linux")]
@@ -93,47 +139,91 @@ fn place_on_monitor(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
Ok(())
}
/// Gives `to` the source window's outer frame before `to` is shown.
///
/// Tauri's position, size and maximize calls are queued. On macOS the AppKit calls return
/// before the frame changes, while `show` orders the window front immediately, so the old
/// rectangle appears and then jumps. The frame is written synchronously instead.
fn copy_frame(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
if same_frame(from, to) {
let host = frame_host(from)?;
if matches!(host, FrameHost::Wayland | FrameHost::SimpleFullscreen) {
return Ok(());
}
let err = |e: tauri::Error| IdeError::internal(e.to_string());
let fullscreen = from.is_fullscreen().map_err(err)?;
if fullscreen {
#[cfg(target_os = "macos")]
crate::macos::transfer_fullscreen(from, to).map_err(err)?;
#[cfg(not(target_os = "macos"))]
{
to.set_fullscreen(false).map_err(err)?;
place_on_monitor(from, to)?;
from.set_fullscreen(false).map_err(err)?;
to.set_fullscreen(true).map_err(err)?;
}
return Ok(());
// Tauri's physical rectangles round through the scale factor. On macOS the AppKit frame is
// the one `show` will present, so compare that instead of skipping a real difference.
#[cfg(target_os = "macos")]
if host == FrameHost::Desktop {
return crate::macos::copy_window_frame(from, to).map_err(|error| IdeError::internal(error.to_string()));
}
to.set_fullscreen(false).map_err(err)?;
let maximized = from.is_maximized().map_err(err)?;
if !maximized {
to.unmaximize().map_err(err)?;
to.set_position(from.outer_position().map_err(err)?).map_err(err)?;
// `set_size` excludes GTK's CSD shadow, which tao's inner size includes on Wayland.
#[cfg(target_os = "linux")]
let size = crate::linux_window_state::content_size(&from.as_ref().window()).map_err(err)?;
#[cfg(not(target_os = "linux"))]
let size = from.inner_size().map_err(err)?;
#[cfg(target_os = "linux")]
crate::linux_window_state::normal_size_requested(to.app_handle(), to.label(), size);
to.set_size(size).map_err(err)?;
} else {
// Maximize the target on the source's monitor, not on the monitor it happened to
// occupy while hidden.
to.unmaximize().map_err(err)?;
match frame_write(host, outer_frame(from)?, outer_frame(to)?) {
FrameWrite::Leave => Ok(()),
FrameWrite::TransferFullscreen => transfer_native_fullscreen(from, to),
FrameWrite::Assign(frame) => assign_outer_frame(from, to, frame),
}
}
fn transfer_native_fullscreen(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
let err = |error: tauri::Error| IdeError::internal(error.to_string());
#[cfg(target_os = "macos")]
crate::macos::transfer_fullscreen(from, to).map_err(err)?;
#[cfg(not(target_os = "macos"))]
{
to.set_fullscreen(false).map_err(err)?;
place_on_monitor(from, to)?;
to.maximize().map_err(err)?;
from.set_fullscreen(false).map_err(err)?;
to.set_fullscreen(true).map_err(err)?;
}
Ok(())
}
fn assign_outer_frame(from: &WebviewWindow, to: &WebviewWindow, _frame: OuterFrame) -> IdeResult<()> {
#[cfg(target_os = "macos")]
{
crate::macos::copy_window_frame(from, to).map_err(|error| IdeError::internal(error.to_string()))
}
#[cfg(not(target_os = "macos"))]
{
let err = |error: tauri::Error| IdeError::internal(error.to_string());
to.set_fullscreen(false).map_err(err)?;
if from.is_maximized().map_err(err)? {
// Maximize on the source's monitor. The rectangles differed, so the maximized flags
// alone are not enough; a hidden peer would otherwise appear at its old size.
to.unmaximize().map_err(err)?;
place_on_monitor(from, to)?;
to.maximize().map_err(err)?;
} else {
to.unmaximize().map_err(err)?;
to.set_position(from.outer_position().map_err(err)?).map_err(err)?;
// `set_size` excludes GTK's CSD shadow, which tao's inner size includes on Wayland.
#[cfg(target_os = "linux")]
let size = crate::linux_window_state::content_size(&from.as_ref().window()).map_err(err)?;
#[cfg(not(target_os = "linux"))]
let size = from.inner_size().map_err(err)?;
#[cfg(target_os = "linux")]
crate::linux_window_state::normal_size_requested(to.app_handle(), to.label(), size);
to.set_size(size).map_err(err)?;
}
Ok(())
}
}
/// Shows `to` in place of `from`, at `from`'s frame.
fn show_at_frame(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
let err = |error: tauri::Error| IdeError::internal(error.to_string());
// Order the target front in the same AppKit turn as the frame write. A separate `show` runs
// after that turn and constrains the titled window, which is the jump. Native fullscreen is
// handed over by `copy_frame` instead.
#[cfg(target_os = "macos")]
if !from.is_fullscreen().map_err(err)? {
to.unminimize().map_err(err)?;
return crate::macos::present_window_frame(from, to).map_err(err);
}
copy_frame(from, to)?;
to.unminimize().map_err(err)?;
to.show().map_err(err)?;
to.set_focus().map_err(err)
}
/// Keeps hidden group members at the selected window's frame. Selecting a tab then only
/// changes which window is visible instead of moving or resizing one on screen.
fn sync_member_frames(app: &AppHandle, selected: &str) {
@@ -235,11 +325,12 @@ pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
&& previous.selected != target
&& let Some(from) = app.get_webview_window(&previous.selected)
{
copy_frame(&from, &to)?;
show_at_frame(&from, &to)?;
} else {
to.unminimize().map_err(|e| IdeError::internal(e.to_string()))?;
to.show().map_err(|e| IdeError::internal(e.to_string()))?;
to.set_focus().map_err(|e| IdeError::internal(e.to_string()))?;
}
to.unminimize().map_err(|e| IdeError::internal(e.to_string()))?;
to.show().map_err(|e| IdeError::internal(e.to_string()))?;
to.set_focus().map_err(|e| IdeError::internal(e.to_string()))?;
for member in &previous.members {
if member != target
&& let Some(window) = app.get_webview_window(member)
@@ -546,3 +637,54 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{FrameHost, FrameWrite, OuterFrame, frame_write};
fn frame(x: i32, y: i32, width: u32, height: u32) -> OuterFrame {
OuterFrame { x, y, width, height }
}
#[test]
fn matching_outer_rects_are_left_alone() {
let frame = frame(100, 80, 1200, 800);
assert_eq!(frame_write(FrameHost::Desktop, frame, frame), FrameWrite::Leave);
}
#[test]
fn a_different_outer_rect_is_assigned_before_the_window_is_shown() {
let from = frame(100, 80, 1200, 800);
let to = frame(40, 40, 900, 600);
assert_eq!(frame_write(FrameHost::Desktop, from, to), FrameWrite::Assign(from));
}
#[test]
fn maximized_windows_with_different_rects_still_assign() {
let from = frame(0, 25, 1728, 1055);
let to = frame(0, 25, 1512, 900);
assert_eq!(frame_write(FrameHost::Desktop, from, to), FrameWrite::Assign(from));
}
#[test]
fn simple_fullscreen_does_not_copy_a_frame() {
let from = frame(0, 0, 1728, 1117);
let to = frame(100, 80, 1200, 800);
assert_eq!(frame_write(FrameHost::SimpleFullscreen, from, to), FrameWrite::Leave);
}
#[test]
fn wayland_does_not_place_a_window() {
let from = frame(0, 0, 1200, 800);
let to = frame(10, 10, 800, 600);
assert_eq!(frame_write(FrameHost::Wayland, from, to), FrameWrite::Leave);
}
#[test]
fn native_fullscreen_transfers_only_when_the_rects_differ() {
let from = frame(0, 0, 1728, 1117);
let other = frame(100, 80, 1200, 800);
assert_eq!(frame_write(FrameHost::NativeFullscreen, from, from), FrameWrite::Leave);
assert_eq!(frame_write(FrameHost::NativeFullscreen, from, other), FrameWrite::TransferFullscreen);
}
}
+50 -10
Переглянути файл
@@ -28,6 +28,7 @@ export const commands = {
projectTrustStatus: (path: string) => typedError<TrustStatus, IdeError>(__TAURI_INVOKE("project_trust_status", { path })),
projectTrustList: () => typedError<TrustDecisions, IdeError>(__TAURI_INVOKE("project_trust_list")),
projectTrustSet: (path: string, trusted: boolean, folder: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("project_trust_set", { path, trusted, folder })),
projectTrustAddLocation: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("project_trust_add_location", { path })),
projectTrustRemoveLocation: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("project_trust_remove_location", { path })),
workspaceCreate: (path: string, name: string, projects: string[]) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("workspace_create", { path, name, projects })),
workspaceAttach: (path: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("workspace_attach", { path })),
@@ -424,9 +425,12 @@ export const commands = {
/**
* References of the symbol at `pos`. `project_wide` also searches project files
* outside the language server's analysis scope; bulk scans over many symbols
* leave it off. Cancel with `cancel_request(request)`.
* leave it off. Java, `project_wide`: without `libraries`, the dependencies and the JDK
* are not searched; with it, those found in the sources arrive on `on_partial` before
* the slower search for the rest, and the result has them all. Cancel with
* `cancel_request(request)`.
*/
lspReferences: (request: RequestId, doc: DocId, pos: Pos, includeDeclaration: boolean, projectWide: boolean) => typedError<References, IdeError>(__TAURI_INVOKE("lsp_references", { request, doc, pos, includeDeclaration, projectWide })),
lspReferences: (request: RequestId, doc: DocId, pos: Pos, includeDeclaration: boolean, projectWide: boolean, libraries: boolean, onPartial: Channel<References>) => typedError<References, IdeError>(__TAURI_INVOKE("lsp_references", { request, doc, pos, includeDeclaration, projectWide, libraries, onPartial })),
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
lspWorkspaceSymbols: (request: RequestId, query: string) => typedError<WorkspaceSymbol[], IdeError>(__TAURI_INVOKE("lsp_workspace_symbols", { request, query })),
lspCodeActions: (doc: DocId, range: Range, only: string[]) => typedError<CodeAction[], IdeError>(__TAURI_INVOKE("lsp_code_actions", { doc, range, only })),
@@ -792,7 +796,7 @@ export const commands = {
/** Installed interpreters / toolchains of `kind`; project-local ones first. */
sdkDetect: (kind: SdkKind) => typedError<Sdk[], IdeError>(__TAURI_INVOKE("sdk_detect", { kind })),
/** The interpreter the project uses: the configured one, else its virtualenv. */
sdkPythonEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective")),
sdkPythonEffective: (near: string | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective", { near })),
/** The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`. */
sdkPhpEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_php_effective")),
/** The PHP language level of the project `path` belongs to: the effective one and Auto's. */
@@ -897,7 +901,11 @@ export const commands = {
appQuit: () => __TAURI_INVOKE<void>("app_quit"),
/** A window vetoed the quit (user cancelled its unsaved-changes prompt). */
appCancelQuit: () => __TAURI_INVOKE<void>("app_cancel_quit"),
/** Sets the menu's labels / shortcut text (on locale or keymap change) and rebuilds it. */
/**
* Sets the menu's labels / shortcut text and rebuilds it when they changed.
* Focusing another project window re-pushes the same shared menu; an identical
* config must not call `set_menu`, which redraws the macOS menu bar.
*/
menuConfigure: (config: MenuConfig) => __TAURI_INVOKE<void>("menu_configure", { config }),
/** Rebuilds the menu (e.g. after the recent-projects list changed). */
menuRefresh: () => __TAURI_INVOKE<void>("menu_refresh"),
@@ -910,24 +918,24 @@ export const commands = {
menuSetDisabled: (ids: string[]) => __TAURI_INVOKE<void>("menu_set_disabled", { ids }),
appLogLocation: () => typedError<LogLocation, IdeError>(__TAURI_INVOKE("app_log_location")),
appBuildInfo: () => __TAURI_INVOKE<BuildInfo>("app_build_info"),
appCheckUpdate: () => typedError<UpdateCheck, IdeError>(__TAURI_INVOKE("app_check_update")),
appCheckUpdate: (source: UpdateSource) => typedError<UpdateCheck, IdeError>(__TAURI_INVOKE("app_check_update", { source })),
/**
* The background check made once per process when the first window starts;
* later calls (other windows) and debug builds get `None`. Failures are logged,
* not reported: the user didn't ask for this check.
*/
appStartupUpdateCheck: () => __TAURI_INVOKE<{
appStartupUpdateCheck: (source: UpdateSource) => __TAURI_INVOKE<{
version: string,
currentVersion: string,
notes: string | null,
date: string | null,
} | null>("app_startup_update_check"),
} | null>("app_startup_update_check", { source }),
/**
* Downloads and installs the available update, streaming progress to `on_progress`.
* Cancellable through `request` until the download completes; the UI then restarts
* with `app_restart`. One install runs at a time.
*/
appInstallUpdate: (request: RequestId, onProgress: Channel<UpdateProgress>) => typedError<null, IdeError>(__TAURI_INVOKE("app_install_update", { request, onProgress })),
appInstallUpdate: (source: UpdateSource, request: RequestId, onProgress: Channel<UpdateProgress>) => typedError<null, IdeError>(__TAURI_INVOKE("app_install_update", { source, request, onProgress })),
debugExceptionFilters: () => typedError<SessionExceptionFilters[], IdeError>(__TAURI_INVOKE("debug_exception_filters")),
debugSetExceptionBreakpoints: (choices: { [key in string]: boolean }) => typedError<null, IdeError>(__TAURI_INVOKE("debug_set_exception_breakpoints", { choices })),
debugSetVariable: (session: DebugSessionId, container: number, name: string, evaluateName: string | null, frameId: number | null, value: string) => typedError<Variable, IdeError>(__TAURI_INVOKE("debug_set_variable", { session, container, name, evaluateName, frameId, value })),
@@ -2021,6 +2029,7 @@ export type CatalogPlugin = {
authors: string[],
homepage: string | null,
changeNotes: string | null,
icon: PluginIcon | null,
/** Package directory; install with `install_from_dir(path)`. */
path: IpcPath,
hasCode: boolean,
@@ -2109,6 +2118,8 @@ export type ClassifiedReference = {
access?: ReferenceAccess | null,
location: Location,
kind: ReferenceKind,
/** The usage's line, when the server has it at hand (a library class's). */
text?: string | null,
};
export type ClearCachesResult = {
@@ -3866,6 +3877,8 @@ export type GeneralSettings = {
powerSaveMode?: boolean,
/** File › Rename Project… (project layer): the name shown for the project; empty = its folder name. */
projectName?: string,
/** Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`. */
updateSource?: string,
};
/** A repository of the signed-in account (owned, collaborator, or organization member). */
@@ -4411,6 +4424,11 @@ export type IndexEntry = {
engine?: string,
/** Marketplace categories (`CATEGORIES`); an IDE ignores those it doesn't know. */
categories?: string[],
/**
* The manifest's icon, sanitised by whoever wrote the index and again by
* the IDE before showing it.
*/
icon?: PluginIcon | null,
};
export type IndexStatus = {
@@ -5689,6 +5707,12 @@ export type PluginEvent =
/** Open `url` (`http(s)://`) in the system browser. */
{ type: "openUrl"; pluginId: string; url: string };
/** A plugin's own icon (`icon`, `icon-dark` of its manifest): sanitised SVG markup. */
export type PluginIcon = {
light: string,
dark: string | null,
};
export type PluginInfo = {
id: string,
name: string,
@@ -5697,6 +5721,7 @@ export type PluginInfo = {
authors: string[],
homepage: string | null,
changeNotes: string | null,
icon: PluginIcon | null,
source: PluginSource,
/** Package directory. */
path: IpcPath,
@@ -6172,6 +6197,8 @@ export type References = {
classified?: ClassifiedReference[],
locations: Location[],
incomplete: ReferencesIncomplete | null,
/** The dependencies and the JDK were not searched (asked for without `libraries`). */
librariesSkipped?: boolean,
};
/** Why a references search may have missed usages. */
@@ -6468,7 +6495,10 @@ export type RunConfig_Serialize = {
export type RunExtras = RunExtras_Serialize | RunExtras_Deserialize;
export type RunExtras_Deserialize = {
/** Module supplying a JVM application's classpath; empty means the project root. */
/**
* Owning module, independent of the working directory; also supplies a JVM application's classpath.
* Empty means the project root.
*/
module?: string | null,
/** Values of the configuration type's own form fields (the command line derives from them). */
params?: { [key in string]: string },
@@ -6507,7 +6537,10 @@ export type RunExtras_Deserialize = {
};
export type RunExtras_Serialize = {
/** Module supplying a JVM application's classpath; empty means the project root. */
/**
* Owning module, independent of the working directory; also supplies a JVM application's classpath.
* Empty means the project root.
*/
module?: string | null,
/** Values of the configuration type's own form fields (the command line derives from them). */
params?: { [key in string]: string },
@@ -7598,6 +7631,13 @@ export type UpdateProgress =
/** Download done; the new version is being written over this one. */
{ type: "installing" };
/** Where updates are downloaded from (System Settings › Updates). */
export type UpdateSource =
/** The GitHub releases named in tauri.conf.json. */
"github" |
/** The CNB mirror of the same releases, for networks where GitHub is slow. */
"cnb";
export type Variable = {
name: string,
value: string,
+70 -3
Переглянути файл
@@ -1,9 +1,9 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { commands } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { clipboardDocumentPath, clipboardFilesExtension, pasteEditorClipboard } from "./clipboard";
import { clipboardDocumentPath, clipboardFilesExtension, pasteEditorClipboard, pasteEditorText } from "./clipboard";
import { markdownImages } from "./markdownImages";
vi.mock("@/platform/remote", () => ({ isRemoteWindow: vi.fn(() => false) }));
@@ -204,3 +204,70 @@ it("does not insert into a read-only editor", async () => {
expect(view.state.doc.toString()).toBe("");
expect(list).not.toHaveBeenCalled();
});
describe("multi-caret paste", () => {
const view = (doc: string, ranges: Array<[number, number]>) => {
const v = new EditorView({
state: EditorState.create({
doc,
selection: EditorSelection.create(
ranges.length > 1
? ranges.map(([from, to]) => EditorSelection.range(from, to))
: [EditorSelection.cursor(ranges[0]![0])],
),
extensions: EditorState.allowMultipleSelections.of(true),
}),
parent: document.body,
});
views.push(v);
return v;
};
it("pastes one line per caret when the counts match", () => {
const line = 'icjsdiocjosid "" cdscsd';
// A caret inside each pair of quotes (index 15), as in the issue.
const v = view(
Array(7).fill(line).join("\n"),
Array.from({ length: 7 }, (_, i) => {
const from = i * (line.length + 1) + 15;
return [from, from] as [number, number];
}),
);
pasteEditorText(v, "s\nd\nd\ns\nd\nd\ne");
expect(v.state.doc.toString()).toBe(
Array.from({ length: 7 }, (_, i) => `icjsdiocjosid "${"sddsdde"[i]}" cdscsd`).join("\n"),
);
});
it("keeps a trailing newline as the last caret's empty line (issue #1828)", () => {
const line = 'icjsdiocjosid "" cdscsd';
// Seven carets, six copied lines with a trailing newline: split keeps the
// empty seventh segment, so the last caret gets "" as the issue expects.
const v = view(
Array(7).fill(line).join("\n"),
Array.from({ length: 7 }, (_, i) => {
const from = i * (line.length + 1) + 15;
return [from, from] as [number, number];
}),
);
pasteEditorText(v, "s\nd\nd\ns\nd\nd\n");
expect(v.state.doc.toString()).toBe(
Array.from({ length: 7 }, (_, i) => `icjsdiocjosid "${"sddsdd"[i] ?? ""}" cdscsd`).join("\n"),
);
});
it("pastes the whole text at every caret when the counts differ", () => {
const v = view("a b", [
[1, 1],
[3, 3],
]);
pasteEditorText(v, "x\ny\nz");
expect(v.state.doc.toString()).toBe("ax\ny\nz bx\ny\nz");
});
it("pastes the whole text at a single caret", () => {
const v = view("a", [[1, 1]]);
pasteEditorText(v, "x\ny");
expect(v.state.doc.toString()).toBe("ax\ny");
});
});
+28 -2
Переглянути файл
@@ -1,4 +1,4 @@
import { Facet, Prec } from "@codemirror/state";
import { EditorSelection, Facet, Prec } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard";
import { isRemoteWindow } from "@/platform/remote";
@@ -13,9 +13,35 @@ function clipboardFileFormatter(view: EditorView): ((paths: string[]) => string)
: undefined;
}
/**
* The dispatch shared by every paste entry point. With several carets and a
* clipboard of exactly one line per caret, each caret gets its own line
* (JetBrains behavior): `"a\nb"` at two carets inserts `a` then `b`, not the
* block twice. Any other count pastes the full text at every caret.
* `userEvent` is `"input.paste"` unless the caller passes another (plain-text
* paste opts out of Reformat on Paste through `"input.pastePlain"`).
*/
export function dispatchPaste(view: EditorView, text: string, userEvent = "input.paste") {
const ranges = view.state.selection.ranges;
const lines = text.replace(/\r\n?/g, "\n").split("\n");
if (ranges.length > 1 && lines.length === ranges.length) {
let i = 0;
const spec = view.state.changeByRange((range) => {
const insert = lines[i++]!;
return {
changes: { from: range.from, to: range.to, insert },
range: EditorSelection.cursor(range.from + insert.length),
};
});
view.dispatch({ ...spec, userEvent, scrollIntoView: true });
} else {
view.dispatch(view.state.replaceSelection(text), { userEvent, scrollIntoView: true });
}
}
export function pasteEditorText(view: EditorView, text: string) {
if (!text || !view.dom.isConnected || view.state.readOnly) return;
view.dispatch(view.state.replaceSelection(text), { userEvent: "input.paste", scrollIntoView: true });
dispatchPaste(view, text);
view.focus();
}
+2
Переглянути файл
@@ -18,6 +18,7 @@ export const findLocals = {
export const findStyles = {
".cm-openidea-findMatch": {
backgroundColor: "var(--editor-search)",
color: "var(--fg-search-match, inherit)",
borderRadius: "2px",
},
".cm-openidea-findExcluded": {
@@ -29,6 +30,7 @@ export const findStyles = {
},
".cm-openidea-findMatch-current": {
backgroundColor: "var(--editor-search-current)",
color: "var(--fg-search-match, inherit)",
outline: "1px solid color-mix(in srgb, var(--editor-search-current) 60%, var(--fg-strong))",
},
};
+3 -2
Переглянути файл
@@ -6,6 +6,7 @@ import { offsetToPos, posToOffset } from "@/editor/lsp/positions";
import { caretAnchor, openPopup } from "@/editor/lsp/popupStore";
import { executeAction } from "@/platform/actions";
import { clipLabel, clipboardHistory, recordClipboard } from "./clipboardHistory";
import { dispatchPaste } from "./cm/clipboard";
import { unwrapOptions, type ChainNode, type UnwrapOption } from "./cm/unwrap";
import type { EditorSlot } from "./model/slot";
@@ -13,7 +14,7 @@ const hint = (text: string) => void executeAction("editor.showHint", { text });
export function pasteText(view: EditorView, text: string) {
if (view.state.readOnly) return;
view.dispatch(view.state.replaceSelection(text), { userEvent: "input.paste", scrollIntoView: true });
dispatchPaste(view, text);
view.focus();
}
@@ -125,6 +126,6 @@ export async function pasteAsPlainText(view: EditorView) {
return;
}
if (!text) return;
view.dispatch(view.state.replaceSelection(text), { userEvent: "input.pastePlain", scrollIntoView: true });
dispatchPaste(view, text, "input.pastePlain");
view.focus();
}
+15 -1
Переглянути файл
@@ -15,6 +15,12 @@ vi.mock("@/platform/ipc", async (orig) => {
});
const executeAction = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@/platform/actions", () => ({ executeAction }));
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { lensTargets, usagesLensExtension } = await import("./codeLens");
const { lspDoc } = await import("./lsp");
@@ -89,7 +95,15 @@ describe("background usage counts", () => {
it("uses the server's existing scope and leaves full searches to the explicit action", async () => {
const view = editor();
await settle();
expect(ipc.lspReferences).toHaveBeenCalledWith(expect.any(Number), 7, { line: 0, col: 0 }, false, false);
expect(ipc.lspReferences).toHaveBeenCalledWith(
expect.any(Number),
7,
{ line: 0, col: 0 },
false,
false,
false,
expect.anything(),
);
expect(titles(view)).toEqual(["2 usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
+10 -1
Переглянути файл
@@ -5,6 +5,7 @@
* and symbol, and at most a few reference requests in flight. Beside each
* count, the declaration's last author from VCS blame (`authorLens`).
*/
import { Channel } from "@tauri-apps/api/core";
import { EditorSelection, MapMode, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
@@ -195,7 +196,15 @@ class UsagesLensPlugin {
this.pending.add(request);
// Opening candidate files for each count triggers expensive server analysis.
// Only an explicit Find Usages should widen the server's scope.
return commands.lspReferences(request, doc.doc, { line: t.line, col: t.col }, false, false);
return commands.lspReferences(
request,
doc.doc,
{ line: t.line, col: t.col },
false,
false,
false,
new Channel(),
);
}, wanted);
if (wanted()) {
if (incomplete) this.incomplete = true;
+4 -8
Переглянути файл
@@ -77,15 +77,11 @@ describe("Typo inspection", () => {
expect(diagnosticMarks(lint)).toEqual([]);
view.dispatch({ selection: { anchor: 5 } });
expect(spellingIntentions(view).map((i) => i.label)).toEqual([
"Typo: Change to…",
"Save 'mesage' to project-level dictionary",
"Save 'mesage' to application-level dictionary",
]);
// IDEA's → menu: the dictionaries and the inspection's controls.
expect(spellingIntentions(view).map((i) => i.label)).toEqual(["Typo: Change to…", "Save 'mesage' to dictionary"]);
// IDEA's → menu: each dictionary level and the inspection's controls.
expect(spellingIntentions(view)[0]!.submenu?.map((i) => ("label" in i ? i.label : "-"))).toEqual([
"Save 'mesage' to project-level dictionary",
"Save 'mesage' to application-level dictionary",
"Save to project-level dictionary",
"Save to application-level dictionary",
"-",
"Edit inspection profile setting",
"Disable inspection",
+15 -12
Переглянути файл
@@ -142,26 +142,23 @@ export function spellingIntentions(view: EditorView): ListPopupItem[] {
const typo = typoAt(view.state, sel.head);
if (!typo) return [];
const hasProject = !!useProject.getState().project;
const saves: ListPopupItem[] = [
// One row saves to the project dictionary (application-level without a project);
// its submenu still offers each level, then the inspection controls.
const saveSubmenu: MenuItem[] = [
...(hasProject
? [
{
id: "spelling.saveProject",
label: tx`Save '${typo.word}' to project-level dictionary`,
icon: "bulb-fix",
run: () => saveToDictionary(typo.word, "project"),
label: "Save to project-level dictionary",
run: () => void saveToDictionary(typo.word, "project"),
},
]
: []),
{
id: "spelling.saveIde",
label: tx`Save '${typo.word}' to application-level dictionary`,
icon: "bulb-fix",
run: () => saveToDictionary(typo.word, "ide"),
label: "Save to application-level dictionary",
run: () => void saveToDictionary(typo.word, "ide"),
},
];
const submenu: MenuItem[] = [
...saves.map((s) => ({ id: s.id, label: s.label, verbatim: true, run: () => void s.run() })),
{ kind: "separator" },
...intentionControls({ id: SPELLING_INSPECTION, name: "Typo" }),
];
@@ -172,9 +169,15 @@ export function spellingIntentions(view: EditorView): ListPopupItem[] {
icon: "bulb-fix",
emphasis: true,
run: () => changeTo(view, typo),
submenu,
submenu: saveSubmenu,
},
{
id: "spelling.save",
label: tx`Save '${typo.word}' to dictionary`,
icon: "bulb-fix",
run: () => saveToDictionary(typo.word, hasProject ? "project" : "ide"),
submenu: saveSubmenu,
},
...saves.map((s) => ({ ...s, submenu })),
];
}
+6
Переглянути файл
@@ -65,6 +65,12 @@ const showHint = vi.fn();
vi.mock("@/editor/lsp/hint", () => ({ showHint }));
const executeAction = vi.fn();
vi.mock("@/platform/actions", () => ({ executeAction }));
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
let answer = "cancel";
const ask = vi.fn(async (_request: MessageRequest) => ({ button: answer, checked: false }));
let confirmAnswer: { checked: boolean } | null = { checked: false };
+11 -2
Переглянути файл
@@ -10,6 +10,7 @@
* Files (project view): references to the file's top-level symbols from other
* files, when the language server can answer (`fileUsages`).
*/
import { Channel } from "@tauri-apps/api/core";
import type { EditorView } from "@codemirror/view";
import type { Text } from "@codemirror/state";
import type { LocalSymbol, Location, OutlineItem, Pos, Range, SyntaxNode } from "@/bindings";
@@ -254,7 +255,7 @@ async function findUsages(ctx: EditorDocContext, target: SafeDeleteTarget): Prom
if (target.local)
return target.local.references.filter((r) => outside(ctx.path, r)).map((range) => ({ path: ctx.path, range }));
const { locations: refs } = await lspRequest(() =>
commands.lspReferences(nextRequestId(), ctx.doc, target.at, false, true),
commands.lspReferences(nextRequestId(), ctx.doc, target.at, false, true, false, new Channel()),
);
return refs.filter((l) => outside(l.path, l.range));
}
@@ -554,7 +555,15 @@ export async function fileUsages(paths: readonly string[], signal?: AbortSignal)
// Every symbol of every file: the server's own scope (a project search each would be too slow).
refs = (
await lspRequest(() =>
commands.lspReferences(nextRequestId(), doc, item.selection_range.start, false, false),
commands.lspReferences(
nextRequestId(),
doc,
item.selection_range.start,
false,
false,
false,
new Channel(),
),
)
).locations;
} catch (e) {
+75 -7
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { UpdateCheck, UpdateProgress } from "@/bindings";
import type { Settings, UpdateCheck, UpdateProgress } from "@/bindings";
import type { NotificationService } from "@/workbench/contributions";
vi.mock("@tauri-apps/api/core", () => ({
@@ -20,7 +20,7 @@ function deferred<T>() {
let install: ReturnType<typeof deferred<Result<null>>>;
let check: ReturnType<typeof deferred<Result<UpdateCheck>>>;
let channel: Channel | null;
const appInstallUpdate = vi.fn((_request: number, ch: Channel) => {
const appInstallUpdate = vi.fn((_source: string, _request: number, ch: Channel) => {
channel = ch;
return install.promise;
});
@@ -28,18 +28,35 @@ const appCheckUpdate = vi.fn(() => check.promise);
const appRestart = vi.fn(async () => null);
const cancelRequest = vi.fn(async () => null);
const appBuildInfo = vi.fn(async () => ({ version: "0.1.21" }));
const settingsSet = vi.fn(async () => ({ status: "ok", data: { general: {}, appearance: {} } }));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: { ...actual.commands, appInstallUpdate, appCheckUpdate, appRestart, cancelRequest, appBuildInfo },
commands: {
...actual.commands,
appInstallUpdate,
appCheckUpdate,
appRestart,
cancelRequest,
appBuildInfo,
settingsSet,
},
};
});
const { checkForUpdates, installUpdate, notifyUpdate, progressText, CHECK_TASK_ID, INSTALL_TASK_ID, UPDATE_KEY } =
await import("../updates");
const {
checkForUpdates,
installUpdate,
notifyUpdate,
progressText,
updateSource,
CHECK_TASK_ID,
INSTALL_TASK_ID,
UPDATE_KEY,
} = await import("../updates");
const { provideNotificationService } = await import("@/workbench/contributions");
const { useProject } = await import("@/platform/project");
const { useTasks } = await import("@/workbench/tasks");
@@ -60,7 +77,7 @@ beforeEach(() => {
check = deferred();
provideNotificationService({ notify: (n) => void notes.push(n), expire: (k) => void expired.push(k) });
useTasks.setState({ tasks: [] });
useProject.setState({ project: null, lightEdit: false });
useProject.setState({ project: null, lightEdit: false, settings: null });
});
afterEach(() => vi.clearAllMocks());
@@ -128,12 +145,33 @@ describe("Install and Restart", () => {
install = deferred();
const cancelled = installUpdate("0.1.22");
task(INSTALL_TASK_ID)!.cancel!();
expect(cancelRequest).toHaveBeenCalledWith(appInstallUpdate.mock.calls.at(-1)![0]);
expect(cancelRequest).toHaveBeenCalledWith(appInstallUpdate.mock.calls.at(-1)![1]);
install.resolve({ status: "error", error: { kind: "cancelled", message: "cancelled" } });
await cancelled;
expect(notes.at(-1)).toMatchObject({ level: "info", title: "Update cancelled", key: UPDATE_KEY });
expect(appRestart).not.toHaveBeenCalled();
});
it.each([
["a failed", "unavailable", "github", "CNB", "cnb"],
["a failed", "unavailable", "cnb", "GitHub", "github"],
["a cancelled (likely slow)", "cancelled", "cnb", "GitHub", "github"],
])("offers %s download from %s again from the other source", async (_case, kind, from, label, to) => {
useProject.setState({ settings: { general: { updateSource: from }, appearance: {} } as unknown as Settings });
const first = installUpdate("0.1.22");
install.resolve({ status: "error", error: { kind, message: kind } });
await first;
const action = notes.at(-1)!.actions!.at(-1)!;
expect(action.label).toBe(`Retry with ${label}`);
install = deferred();
action.run();
await tick();
expect(settingsSet).toHaveBeenCalledWith("global", "general.updateSource", JSON.stringify(to));
expect(appInstallUpdate.mock.calls.at(-1)![0]).toBe(to);
install.resolve(ok(null));
await tick();
});
});
describe("Check for Updates", () => {
@@ -184,6 +222,36 @@ describe("Check for Updates", () => {
});
});
describe("updateSource", () => {
const withSettings = (updateSource: string | undefined, locale: string | undefined) =>
useProject.setState({ settings: { general: { updateSource }, appearance: { locale } } as unknown as Settings });
it.each([
["auto", "zh", "cnb"],
["auto", "zh-CN", "cnb"],
["auto", "en", "github"],
["auto", "ko", "github"],
[undefined, "zh", "cnb"],
["github", "zh", "github"],
["cnb", "en", "cnb"],
["bogus", "en", "github"],
])("%s with the %s UI uses %s", (setting, locale, expected) => {
withSettings(setting, locale);
expect(updateSource()).toBe(expected);
});
it("is passed to the check and the install", async () => {
withSettings("cnb", "en");
void checkForUpdates();
expect(appCheckUpdate).toHaveBeenCalledWith("cnb");
check.resolve(ok({ enabled: true, update: null }));
void installUpdate("0.1.22");
expect(appInstallUpdate.mock.calls.at(-1)![0]).toBe("cnb");
install.resolve(ok(null));
await tick();
});
});
describe("progressText", () => {
it("formats known and unknown lengths", () => {
expect(progressText({ type: "downloading", downloaded: 1024 * 1024, total: null })).toEqual({
+2 -1
Переглянути файл
@@ -147,7 +147,8 @@ export function installMenuBridge(): () => void {
push();
pushEnablement(true);
};
// The native menu bar is shared: a focused window re-pushes its own window-scoped labels.
// The menu bar is shared. A focused window re-pushes labels that can differ per window.
// An identical config does not replace the menu, so switching project tabs does not redraw it.
window.addEventListener("focus", onFocus);
const unsubs = [
useI18n.subscribe((s, prev) => {
+51 -9
Переглянути файл
@@ -7,7 +7,7 @@
* repeated click joins the running check or install instead of starting another.
*/
import { Channel } from "@tauri-apps/api/core";
import { t } from "@/platform/i18n";
import { resolveLocale, t } from "@/platform/i18n";
import {
call,
commands,
@@ -16,6 +16,7 @@ import {
nextRequestId,
type UpdateInfo,
type UpdateProgress,
type UpdateSource,
} from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
@@ -30,6 +31,39 @@ function errorText(e: unknown) {
return e instanceof Error ? e.message : String(e);
}
/** System Settings › Updates › Update source; `auto` picks the CNB mirror for the Chinese UI. */
export function updateSource(): UpdateSource {
const { settings } = useProject.getState();
const chosen = settings?.general?.updateSource;
if (chosen === "github" || chosen === "cnb") return chosen;
return resolveLocale(settings?.appearance?.locale) === "zh" ? "cnb" : "github";
}
const SOURCE_NAMES: Record<UpdateSource, string> = { github: "GitHub", cnb: "CNB" };
/** Makes `source` the update source; the retry it precedes uses it even if saving fails. */
async function chooseSource(source: UpdateSource) {
try {
useProject.setState({
settings: await call(commands.settingsSet("global", "general.updateSource", JSON.stringify(source))),
});
} catch {
/* the choice still applies to this retry */
}
}
/**
* Offered once a download failed or was cancelled (likely too slow): the same install from
* the other source. A check never needs it, since it already falls back to the other source.
*/
function otherSourceAction(version: string, source: UpdateSource) {
const other: UpdateSource = source === "cnb" ? "github" : "cnb";
return {
label: t("app.update.retryWith", { source: SOURCE_NAMES[other] }),
run: () => void chooseSource(other).then(() => installUpdate(version, other)),
};
}
let checking: Promise<void> | null = null;
let installing: Promise<void> | null = null;
@@ -56,7 +90,7 @@ async function runCheck() {
key: UPDATE_KEY,
});
try {
const r = await Promise.race([call(commands.appCheckUpdate()), abandoned]);
const r = await Promise.race([call(commands.appCheckUpdate(updateSource())), abandoned]);
if (r === "cancelled") return;
if (!r.enabled) {
notifications().notify({
@@ -85,7 +119,7 @@ async function runCheck() {
/** Silent check once per app start; only an available update is shown. */
export async function checkForUpdatesOnStartup(): Promise<void> {
if (!isTauri()) return;
const update = await commands.appStartupUpdateCheck().catch(() => null);
const update = await commands.appStartupUpdateCheck(updateSource()).catch(() => null);
if (update) notifyUpdate(update);
}
@@ -118,13 +152,13 @@ export function progressText(p: UpdateProgress): { message: string; fraction: nu
}
/** Downloads and installs `version`, then restarts. A second call while one runs joins it. */
export function installUpdate(version: string): Promise<void> {
export function installUpdate(version: string, source = updateSource()): Promise<void> {
if (!isTauri()) return Promise.resolve();
installing ??= runInstall(version).finally(() => (installing = null));
installing ??= runInstall(version, source).finally(() => (installing = null));
return installing;
}
async function runInstall(version: string) {
async function runInstall(version: string, source: UpdateSource) {
const title = t("app.update.downloading", { version });
const request = nextRequestId();
const cancel = () => void commands.cancelRequest(request).catch(() => {});
@@ -160,17 +194,25 @@ async function runInstall(version: string) {
// Replaces the notification whose action is now spent.
balloon([{ label: t("app.update.cancel"), run: cancel }]);
try {
await call(commands.appInstallUpdate(request, channel));
await call(commands.appInstallUpdate(source, request, channel));
} catch (e) {
if (isCancelled(e)) {
notifications().notify({ level: "info", title: t("app.update.cancelled"), key: UPDATE_KEY });
notifications().notify({
level: "info",
title: t("app.update.cancelled"),
key: UPDATE_KEY,
actions: [otherSourceAction(version, source)],
});
} else {
notifications().notify({
level: "error",
title: t("app.update.installFailed"),
body: errorText(e),
key: UPDATE_KEY,
actions: [{ label: t("app.update.retry"), run: () => void installUpdate(version) }],
actions: [
{ label: t("app.update.retry"), run: () => void installUpdate(version, source) },
otherSourceAction(version, source),
],
});
}
return;
+10
Переглянути файл
@@ -15,6 +15,16 @@
font-size: var(--fs-small);
color: var(--fg-muted);
}
.scope {
flex: none;
}
.searching {
flex: none;
display: flex;
align-items: center;
}
.title {
flex: 1;
min-width: 0;
+22 -2
Переглянути файл
@@ -11,15 +11,17 @@ import { Decoration, EditorView } from "@codemirror/view";
import { codePreviewExtensions } from "@/editor/api";
import { basename } from "@/platform/project";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, List, Popup, fileIconName, listNavigate } from "@/ui";
import { Icon, IconButton, List, Popup, Select, Spinner, fileIconName, listNavigate } from "@/ui";
import { openLocation, readFileLines } from "./ipc";
import {
dismissUsagesPopup,
setUsagesPopupScope,
showUsageResults,
usageCount,
useUsagesPopup,
type Usage,
type UsageGroup,
type UsageScope,
} from "./usages";
import { UsagePreview } from "./UsagesView";
import styles from "./UsagesPopup.module.css";
@@ -79,7 +81,7 @@ export function UsagesPopup() {
const ROW = 24;
function UsagesPopupInner() {
const { anchor, symbol, groups, note } = useUsagesPopup();
const { anchor, symbol, groups, note, loading, scope } = useUsagesPopup();
const preview = useUsagesPopupPreview((s) => s.preview);
const all = useMemo<Usage[]>(() => groups.flatMap((g) => g.usages), [groups]);
const [filter, setFilter] = useState("");
@@ -152,6 +154,24 @@ function UsagesPopupInner() {
{filter || items.length !== total ? tx`${items.length} of ${total} found` : tx`${total} found`}
</span>
</span>
{scope && (
<Select<UsageScope>
variant="ghost"
aria-label={tx("Scope")}
className={styles.scope}
value={scope}
options={[
{ value: "project", label: tx("Project Files") },
{ value: "libraries", label: tx("Project and Libraries") },
]}
onChange={setUsagesPopupScope}
/>
)}
{loading && (
<span className={styles.searching} role="status" aria-label={tx("Searching for more usages")}>
<Spinner size={12} />
</span>
)}
{filter && (
<span className={clsx(styles.filter, !items.length && styles.noMatch)} role="status">
{filter}
+13
Переглянути файл
@@ -41,6 +41,19 @@
.error {
color: var(--danger);
}
.link {
flex: none;
border: none;
background: none;
padding: 0;
font: inherit;
color: var(--link);
cursor: pointer;
}
.link:hover {
color: var(--link-hover);
text-decoration: underline;
}
.body {
flex: 1;
min-width: 0;
+20 -2
Переглянути файл
@@ -66,8 +66,16 @@ export function UsagesTabs() {
const tabs = useUsages((s) => s.tabs);
const search = useUsages(activeUsageSearch);
if (!search) return null;
const label = (t: (typeof tabs)[number]) =>
t.symbol ? formatMessage(tx("Usages of '{symbol}'"), { symbol: t.symbol }) : tx("Usages");
const label = (t: (typeof tabs)[number]) => {
if (!t.symbol) return tx("Usages");
const text =
t.scope === "project"
? tx("Usages of '{symbol}' in Project Files")
: t.scope === "libraries"
? tx("Usages of '{symbol}' in Project and Libraries")
: tx("Usages of '{symbol}'");
return formatMessage(text, { symbol: t.symbol });
};
return (
<Tabs
variant="compact"
@@ -268,6 +276,16 @@ export function UsagesView() {
</div>
<div className={styles.body} onKeyDown={onKeyDown}>
<UsageAccessFilter items={allUsages} />
{!search.loading && !search.error && search.scope === "project" && (
<div className={styles.summary}>
<T>Usages in Project Files</T>
{search.searchLibraries && (
<button type="button" className={styles.link} onClick={() => search.searchLibraries?.()}>
{tx("Search in Project and Libraries")}
</button>
)}
</div>
)}
{(search.loading || search.error) && (
<div className={styles.summary} role="status" aria-live="polite">
{search.loading ? (
+8 -2
Переглянути файл
@@ -23,6 +23,12 @@ vi.mock("@/platform/ipc", async (orig) => {
return { ...actual, isTauri: () => true, commands: { ...actual.commands, ...cmd } };
});
vi.mock("./candidates", () => ({ filesMentioning: () => filesMentioning() }));
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { _addEditor } = await import("@/editor/api");
const { fetchUsages } = await import("./usages");
@@ -42,7 +48,7 @@ beforeEach(() => {
describe("Find Usages fallback", () => {
it("uses the server when it answers, even with nothing", async () => {
cmd.lspReferences.mockReturnValueOnce(ok({ locations: [], incomplete: null }));
expect(await fetchUsages(caret)).toEqual({ groups: [], note: null });
expect(await fetchUsages(caret)).toEqual({ groups: [], note: null, librariesSkipped: false });
expect(cmd.syntaxLocals).not.toHaveBeenCalled();
});
@@ -50,7 +56,7 @@ describe("Find Usages fallback", () => {
const usage = { path: "/p/a.ts", range: r(1, 0, 1) };
cmd.lspReferences.mockReturnValueOnce(ok({ locations: [usage], incomplete: "indexing" }));
const res = await fetchUsages(caret, 42 as never);
expect(cmd.lspReferences).toHaveBeenCalledWith(42, 3, { line: 1, col: 0 }, false, true);
expect(cmd.lspReferences).toHaveBeenCalledWith(42, 3, { line: 1, col: 0 }, false, true, false, expect.anything());
expect(res.groups[0]!.usages.length).toBe(1);
expect(res.note).toBe(incompleteNote("indexing", "x"));
expect(incompleteNote("tooManyFiles", "x")).toBe(
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more