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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 1300317730 fix(lsp): open library classes behind jar: URIs
The official Kotlin LSP answers navigation into a dependency with a
`jar:///…/lib.jar!/pkg/Name.class` URI but does not serve its contents through
`workspace/textDocumentContent`, so opening the target failed with "no
language server provides the contents of jar:…", locally and remotely.

`jar:` URIs are now resolved by the backend, where the jars are:
- An entry that is not a class (a sources jar entry, a resource) is read from
  its archive.
- A class is shown as its source from the artifact's `-sources.jar` in the
  Maven repository or the Gradle cache (`Name.java`/`Name.kt`, an inner
  class's outer file, a `FileKt` facade's `File.kt`, a `@file:JvmName`
  file); Go to Declaration then lands on the declaration of the name it was
  invoked on.
- Otherwise the server's `decompile` command is used when it offers one, and
  the error says that neither a source nor a decompiler is available.
- Library tabs name the archive and package (`spring-boot-3.5.16.jar ›
  org.springframework.boot`).

Fixes #982
2026-11-03 22:03:51 +08:00
l0ng-ai 98517019e7 fix(editor): say when a file is outside the language server's projects (#1046)
jdtls only checks the syntax of a Java file outside every module's source
folders (or outside any imported project) and answers navigation with
nothing. The editor then said only "Cannot find declaration to go to", and
the server's explanation was a warning squiggle on line 1.

- A banner above the editor explains it while the server reports it, for
  jdtls (not on the classpath of a project / non-project file), gopls (no
  package, build constraints — this replaces the Go-only banner) and
  rust-analyzer (unlinked file). For Java it offers the Maven / Gradle reload
  when available.
- Go to Declaration / Implementation / Type Declaration that finds nothing
  in such a file gives the reason in its hint.

Fixes #827
2026-11-03 22:02:50 +08:00
l0ng-ai ae406ca2fb fix(java): resolve Maven projects with the profiles chosen in the Maven tool window (#1044)
The profiles checked in the Maven tool window only reached `mvn` (sync and
goal runs) and the Kotlin bridge. jdtls imported every module without them,
so a dependency whose version, or module, comes from a profile stayed
unresolved and its classes were reported as missing, while Build Project ran
without `-P` as well.

- A Maven sync records the profiles it ran with. jdtls gets a copy of the
  user settings.xml with them in `<activeProfiles>` (m2e has no other input
  for profiles), sent as a setting so a running server re-imports instead of
  restarting; the file name follows its content so m2e reloads it.
- Toggling a profile reloads the Maven projects (once for several toggles in
  a row, again after a sync that started with the previous choice).
- Build Project passes the synced profiles with `-P`.
- When jdtls finishes an import or project update it does not re-check open
  files, so their errors stayed until the next edit; open Java files are now
  re-checked on its ProjectStatus report. This also covers a POM edit or a
  dependency added to ~/.m2.

Fixes #993
2026-11-03 22:02:40 +08:00
arookieofcтаa-rookie-of-C-language 9dbae1d189 feat(agents): configurable executable for every built-in agent (#682)
Settings › Tools › Agents is split into Built-in and ACP Registry tabs. The Built-in tab lists every built-in agent with its status (custom executable or not found on PATH) and, for the selected agent, its default launch line, an Executable field (empty = auto-detect on PATH) with Browse and Reset, and its sign-in hint. Edits are staged with the Settings dialog and written on Apply / OK; Cancel discards them.

The override is written to <config>/agents/<id>.toml, keeping hand-written name, driver, args and env; resetting a command-only override removes the file. AgentProvider now exposes the program, args, built-in defaults, login hint and whether the command is editable: built-ins started through a package runner (npx) and registry installs are read-only, with the reason shown.

Fixes #596

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 21:55:51 +08:00
l0ng-ai e4b8b76452 chore: add issue/PR templates, PR check, AGENTS.md and shared agent skills (#1043)
Adds a PR template (linked issue, what and why, how it was verified, review focus), a minimal reproduction field on the bug form and required acceptance criteria on the feature form, and CONTRIBUTING.md with the issue and PR rules. A PR check labels needs-info and leaves one comment when the issue link or the verification section is missing; it only reads the title and description.

AGENTS.md is now tracked, with CLAUDE.md linking to it, and covers layout, rules, commands, the checks CI runs, pitfalls and parallel worktrees. The verify and issue-fix skills are shared under .agents/skills and linked from .claude/skills; the rest of .claude/ stays local.
2026-11-03 21:49:31 +08:00
l0ng-ai e2e699dca9 fix(database): bound large cell previews and use dialog editing (#1040)
Limit grid and export-preview cell text to 1000 UTF-16 code units plus an ellipsis. Edit large values in a wrapped dialog while preserving complete clipboard, export and database values.

Reproduced STATUS_STACK_OVERFLOW (0xC00000FD) in Windows WebView2 against a real PostgreSQL table with nine rows and 8.83 MB of jsonb data. Verified the fix through display, selection, editing, full clipboard copy, JSON file export and PostgreSQL writeback. All PR CI checks passed, including 5625 frontend tests and Rust checks on Windows, macOS and Linux.

Fixes #825
2026-11-03 21:49:26 +08:00
l0ng-ai dcd8ecc5ae fix(java): name reserved Windows device files that abort the Java import (#1032)
On Windows, a project file named after a device (nul, con, aux, prn, com1-9, lpt1-9; nul is typically left by a 2>nul redirect in Git Bash) aborts the Java import: Files.exists reports it missing, Eclipse's refresh builds a child path with an empty name and throws "Path must include project and resource name", so m2e never creates the Java project.

When JDT LS reports that failure on Windows, the server root is scanned for reserved device names (bounded, ignore files not honoured) and a one-time error notification lists them with how to recover. The name check covers COM0-9/LPT0-9 including superscript digits, case-insensitive, with or without extension or trailing spaces. Backend notification texts now go through txTemplate so templated catalog entries translate; zh text added.

Refs #976
2026-11-03 21:09:03 +08:00
l0ng-ai a3b6780823 fix(java): replace module outputs with launch snapshots on Windows (#1038)
Maven launches put a snapshot of each module's class directory on the classpath in place of the original. The originals were built as module.join("target/classes") (`...\app\target/classes` on Windows) while JDT LS reports `...\app\target\classes`; compared as text, the original stayed next to its snapshot, so every resource was on the classpath twice and MyBatis failed with "XML fragments parsed from previous mappers already contains value". Launch class directories are now joined per component, and classpath entries are compared by a key that ignores the verbatim prefix, separators, trailing separators and, on Windows, case.

Fixes #704
2026-11-03 20:59:40 +08:00
arookieofc bd2df0bd3a fix(markdown): keep the preview-only scroll position across remounts (#1009)
Tab switches and mode toggles unmount MarkdownPreview, whose only
scroll state was the DOM scrollTop; Preview Only started over at the
top. Record the preview's own scrollTop in the per-path live markdown
store and restore it on mount (split mode keeps its editor-driven
sync).
2026-11-03 20:55:10 +08:00
Marius Ciepluch 8ca25e1984 fix(markdown): use editor-side tokens in the preview (#992)
* fix(markdown): use editor-side tokens in the preview

The preview paints on var(--bg-editor) but took its text colors from
the UI tokens (--fg, --fg-strong, --fg-secondary), so with a light UI
theme plus a dark editor scheme (e.g. an imported dark .icls) it
rendered black-on-black. The code editor was unaffected because it
uses --fg-editor.

The preview now uses editor-side tokens: text var(--fg-editor),
headings var(--syn-markup-heading), code/pre/th background
var(--bg-editor-inline), blockquote var(--fg-editor) at 80%.

* chore: oxfmt src/features/run/types.ts (fixes format:check broken on main by 002401e8)

* chore: regenerate bindings after rebasing onto main
2026-11-03 20:55:06 +08:00
arookieofc a15712b670 fix(vcs): keep a deleted-upstream branch pushable in the multi-repo Push dialog (#1004)
`@{u}..HEAD` fatally fails when the tracking config remains but the
remote-tracking ref is gone (the upstream branch was deleted on the
remote and the fetch pruned): the repository was dropped from the
multi-repository Push dialog, or, when every repository failed, the
dialog showed the raw fatal and disabled Push. Fall back to recent
history like the single-repository dialog does, so the branch stays
listed and pushable (a plain push recreates the remote branch).
2026-11-03 20:33:41 +08:00
arookieofc 82130d37e5 fix(build): recognize Maven builds whose aggregate POM sits in src/ (#1022) 2026-11-03 20:32:37 +08:00
JawтаClaude Opus 5.5 07456b2562 fix(editor): show the scrollbar thumb over overview marks (#1031)
The overview lane lies over the vertical scrollbar, so a mark the height of the lane (a new file added to git is one green VCS mark) hid the native thumb completely. The lane now draws the thumb itself, above its marks and without taking the pointer, at the position of the native one (scrollbarThumb, inset by its 2px border); it switches to the hover color while the pointer is on the thumb. The native thumb is made transparent in editors that have the lane, so the two don't add up, and still takes the drag. Editors without the lane (notebook cells, previews) keep the native thumb.

Fixes #1014

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-03 20:31:57 +08:00
arookieofc 659afe66f5 fix(code-insight): stop call/type hierarchy from nesting recursive symbols forever (#1016)
A recursive symbol got a fresh id on every level (ids carry the parent
chain), so sibling dedupe never matched and each expansion requested the
same level again, forever. Identify items by their position key instead:
a child whose key repeats an ancestor is kept a leaf, marked recursive,
and never expanded.
2026-11-03 20:31:01 +08:00
JawтаClaude Opus 5.5 a57267fa32 fix(project-tree): reveal files of linked workspace projects (#915) (#1035)
In a workspace the tree's root is the workspace directory, and the linked projects are separate top-level roots outside it. Select Opened File (and other reveals) only looked inside that root and contributed folders, so a file of a linked project was never expanded, selected or scrolled to. Reveal now resolves the innermost linked project containing the path first; the Project Files pane also counts linked projects as shown.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-03 20:30:07 +08:00
Park Jong Hyun 4b1614af1f fix(spell): close a Markdown code fence only on a matching fence (#986)
Any ``` line closed an open fence, so a ```` block showing a ``` block ended early and the inner code was spell checked as prose. Fences now close as in CommonMark: the same character, at least as long as the opening fence, and no info string.

Co-authored-by: fhrmrk <[email protected]>
2026-11-03 19:29:16 +08:00
Park Jong Hyun bdeca5803b fix(spell): skip backslash commands like \brief in comments (#985)
Comments and Markdown went through the string-escape rule, which drops only the letter after a backslash, so the Doxygen command `\brief` was reported as the typo "rief". Outside string literals the whole word after a backslash is skipped now (Doxygen / TeX commands, escapes quoted in comments); string literals still skip only the escape letter.

Co-authored-by: fhrmrk <[email protected]>
2026-11-03 19:29:03 +08:00
Park Jong Hyun 839bd0cdb0 fix(http): add http:// to a URL whose query holds another URL (#988)
A request URL without a scheme defaults to http://, but the check was `contains("://")`, so `GET localhost:8080/login?next=http://…` was sent as is and failed to parse. Only a `://` after a leading RFC 3986 scheme counts now, both for HTTP Client requests and the proxy connection check.

Co-authored-by: fhrmrk <[email protected]>
2026-11-03 19:28:21 +08:00
Park Jong Hyun ebf2c2f8e3 fix(web): redirect a served root without a trailing slash (#987)
`/<token>/<key>` has no segments after the key, so the trailing-slash flag kept its initial value and the root's index.html was served at a URL without the slash; its relative links then resolved above the root and returned 404. The flag now comes from the path, so the root redirects to `/<token>/<key>/` like any other directory.

Co-authored-by: fhrmrk <[email protected]>
2026-11-03 19:28:10 +08:00
Jaw c599265ced fix(format): re-detect indents after Reformat Code (#957)
After Reformat Code rewrote a file's indents (e.g. spaces to tabs per Code Style), the editor kept the indents detected when the file was opened: tabs rendered at the old width, the status bar showed the old indent, and Enter inserted the old indent, mixing tabs and spaces until the file was reopened.

Whole-file format edits from language servers and contributed formatters are now tagged `format.reformat`, and after such a transaction the document runs the open-time indent detection again and reapplies its settings, so every split picks up the new indent.

Refs #935.

Co-authored-by: jaw52 <[email protected]>
2026-11-03 19:25:48 +08:00
l0ng-ai 867774b88a Merge pull request #607 from a-rookie-of-C-language/fix/settings-window-shadow-595
fix(windows): de-parent settings window so DWM paints its shadow
2026-11-03 19:22:02 +08:00
l0ng-ai d54e852c38 fix(java): bundle Lombok with the ECJ constructor-call fix (#1027)
JDT LS 1.63's ECJ 3.46.200 keeps a constructor's super()/this() call as the first of its statements. Lombok 1.18.48 wrapped that call in the @SneakyThrows try block (ECJ internal error, whole workspace build failed), emitted @NonNull checks before it, and generated constructors without it.

The bundled agent is now 1.18.48-openidea.2: v1.18.48 with lombok#4059 and the upstream constructor-call fix lombok#4089. The new file name gives JDT LS a new workspace, so classes from the previous agent are rebuilt.

Fixes #1000
Fixes #830
2026-11-03 19:07:33 +08:00
l0ng-ai efd03630b6 fix(navigation): label string-literal targets by their literal (#1025)
Navigation targets that start at a string literal (a Spring @Value("${key}") consumer reached from a configuration key) are named by the literal instead of the first identifier fragment inside it, which showed as "$". Applies to the declaration chooser, the quick-definition popup and the gutter line-marker chooser.
2026-11-03 18:40:26 +08:00
l0ng-ai bbc6a2bc4c fix(run): keep toolchain-derived values out of saved run configurations (#1023)
The run list applies Languages & Frameworks to every configuration it returns (interpreter or toolchain command, PATH, VIRTUAL_ENV, JAVA_HOME, GOROOT, GOPATH, Go module variables, RUSTUP_TOOLCHAIN), and every save sends the user configurations back from that list, so the derived values were written to run.toml: reopening a configuration showed the IDE's whole PATH in its environment, and since applied values never replace existing ones, a saved configuration kept the old toolchain after the interpreter or SDK changed.

Saving now drops what settings derive: an environment entry or an absolute command counts as derived when applying settings to the configuration without it produces it again. The user's own values, including ones for the same variables, are kept. Covers python, pytest, django-test, npm, cargo, go, maven, tomcat, ruby, rake, rspec and godot; Gradle stays as saved, as the run list already leaves it unapplied.
2026-11-03 18:17:00 +08:00
arookieofc cc4a29fa5d chore(ci): reformat types.ts and regenerate bindings to keep main green (#990)
Reformats src/features/run/types.ts with oxfmt and moves RubySettings to its sorted position in the generated src/bindings.ts.
2026-11-03 18:14:03 +08:00
l0ng-ai 5ad179a9e6 perf(java): stop configuration indexing from blocking navigation and keep it warm (#1012)
Java Go to Definition consults the Spring configuration command only inside @Value / getProperty / getRequiredProperty arguments (tree-sitter check), so ordinary Ctrl+click and Ctrl+hover go straight to JDT instead of waiting on a project-wide index rebuild.

The java-usages bundle (1.2.1) keeps its configuration snapshot across editor open/close, builds, saves of non-Java resources and reconciles; it invalidates on Java model changes and unsaved Java edits only.

Fixes #998
Fixes #1002
2026-11-03 18:12:43 +08:00
Jaw 291fa9affe feat(window): close other / left / right project tabs from the window-group tab menu (#965)
Right-clicking a project tab in a merged window group offers Close Other Tabs, Close Tabs to the Left and Close Tabs to the Right (left/right disabled at the ends); the same commands are in the Command Palette and can take shortcuts.

The backend closes the projects one at a time, focusing each so its own unsaved-changes prompt is visible, as Quit does. Cancelling a prompt stops the batch and leaves that project and the rest open; the clicked tab stays and is selected when the batch finishes. Starting Quit clears a pending batch.

Closes #942.

Co-authored-by: jaw52 <[email protected]>
2026-11-03 17:57:42 +08:00
Azeem Hassniтаazeemhassni ecdd43a55a fix(vfs): poll for changes when the OS file watcher cannot start (#906)
Opening a project failed outright when the OS file watcher could not start (inotify limits used up, a file system without change notifications). The watcher now falls back to polling the same non-ignored directories every 2s, per directory unless flat so excluded trees like `node_modules` and `target` are not rescanned, and the project opens with an "External file changes sync may be slow" warning that gives the reason. Directory mtime changes seen only by polling are dropped so folders are not reported as modified.

Fixes #891.

Co-authored-by: azeemhassni <[email protected]>
2026-11-03 17:37:40 +08:00
Jaw ec465964d2 feat(editor): highlight JSP pages (#937)
JSP files had no highlighting and showed a `?` icon; the HTML mode left directives, scriptlets, JSP comments and EL as plain text and flagged `<c:out/>` / `<jsp:include/>` as unclosed elements.

- A JSP grammar layer (comments, directives, scriptlets, expressions, declarations, EL) with HTML and Java overlays, so markup split by JSP elements still nests and braces match across scriptlets.
- EL as its own grammar top: member/index/method calls, namespaced functions, keyword operators, ternaries, lambdas and collection literals.
- Block comments use `<%-- --%>` in markup and `//` in scriptlets; JSP comments and scriptlets fold.
- `.jsp .jspf .jspx .jsph .tag .tagf .tagx` map to the JSP language with a file icon; `gen:jsp-grammar` regenerates the parser and a test checks it matches the grammar.

Closes #870.

Co-authored-by: jaw52 <[email protected]>
2026-11-03 17:29:59 +08:00
l0ng-ai 59766278c5 fix(i18n): translate counts inside the Update Project and Hot Swap results (#994)
In Chinese the Update Project notification read "已在 2 commits 中更新 3 files" and the Hot Swap result "已重新加载 3 classes". Both sentences were translated, but the counts inside them were English phrases passed in as placeholder values, which are only looked up as exact catalog entries.

Each count is now its own source text per variant (`{count} file` / `{count} files`, `{count} commit` / `{count} commits`, `{count} class` / `{count} classes`), built in the current language before it goes into the sentence. These were the only two places where a translated sentence receives an English count phrase as a value.
2026-11-03 15:56:05 +08:00
arookieofcтаa-rookie-of-C-language cc4ab5d4a8 feat(vcs): push notifications say how many commits went where (#961)
After a push the notification only said "Push successful". It now says what went out, for example "Pushed 3 commits to origin/main", counting the commits the branch was ahead of its upstream before the push. This covers Push and pushing a branch to its own upstream. A push across several repositories stays generic unless exactly one of them had commits to send. The title is translated as a whole for each count.

Fixes #954.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 15:35:01 +08:00
ntbang0901 22a5f21a90 perf(vfs): list directories off the main thread (#973)
`fs_read_dir` was a synchronous Tauri command, so every directory listing ran on the main thread. On a slow file system such as a network share (`\\wsl.localhost\...`), each stat while expanding the project tree stalled the whole UI. The listing now runs on the blocking pool, as the other disk-heavy commands do, both for the desktop command and over RPC.

Refs #916.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-03 15:32:19 +08:00
arookieofcтаa-rookie-of-C-language 5e7ee5e081 fix(agents): delete agent tasks whose worktree git no longer recognizes (#979)
Deleting a worktree-isolated agent task together with its worktree failed for good with "fatal: '<path>' is not a working tree" once git no longer recognized the worktree: its registration was pruned, the repository moved, or the worktree's `.git` file was deleted.

When `git worktree remove --force` fails but the folder is still there and lies inside the agent worktrees directory, the folder is now removed directly, so the task can always be deleted. A stale registration is pruned by git later. Paths outside that directory (the task's cwd comes from its stored record) keep git's error and are never deleted by hand.

Fixes #969.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 15:25:45 +08:00
Kevin f67c478b8b fix(ui): wrap long tooltip text inside the bubble (#983)
Hovering an editor tab with a long path showed a tooltip whose text ran past the bubble: tooltips never wrapped (`white-space: nowrap`) and were capped at 360px.

Tooltip text now wraps inside the bubble, breaking long paths where needed, and the shortcut stays on one line next to it. The bubble grows up to 720px or the window width less 32px, so most paths still fit on one line. Short tooltips look as before (same size and line height), and newlines in tooltip text are still collapsed.

Fixes #968.

Co-authored-by: yangyezhuang <[email protected]>
2026-11-03 15:22:26 +08:00
Roberto Scinoccaтаretsef 002401e8a7 feat(languages): add ERB with an HTML + Ruby editor mode (#720)
Ruby gets an ERB editor mode (HTML with embedded Ruby), Ruby / Rake / RSpec run configuration types, and a Settings › Languages & Frameworks › Ruby page for choosing the interpreter (Auto picks the `.ruby-version` / mise / asdf install, else `ruby` on PATH).

- Run: `.rb` scripts run from the editor context menu, `_spec.rb` / `_test.rb` files narrow an RSpec or Rake (`SPEC=` / `TEST=`) configuration, and Rakefile tasks are detected; Rake and RSpec go through `bundle exec` when the project has a Gemfile. The chosen interpreter's `ruby`, `bundle`, `rake` and `rspec` are used and its bin directory is put on PATH.
- Configuration forms rebuild from a raw command line keeping option values with their options (`--format documentation`, `-I lib`), and a new Ruby configuration opens in the Ruby form with the script still to fill in.
- External Libraries lists the Ruby standard library and the bundle's gems, including those Bundler installs inside the project (`vendor/bundle`).
- Ruby is part of the frontend settings defaults and normalization, so the selected interpreter survives a settings round-trip.

Closes #719

Co-authored-by: retsef <[email protected]>
2026-11-03 15:05:09 +08:00
arookieofcтаa-rookie-of-C-language fcfe26474d fix(format): apply the Code Style indent override to reformat requests (#949)
Settings › Editor › Code Style › Java › Tabs and Indents had no effect on Reformat Code: a file indented with 4 spaces stayed that way after choosing "Use tab character" with tab size and indent 1.

There were two causes. The reformat request sent the editor's indent, which comes from the indents detected in the file, instead of the Code Style; and jdt.ls takes the per-level indent width (`indentation.size`) only from its formatter profile, never from the request. With an explicit Tabs and Indents override for the language, Reformat Code now asks for the Code Style indent (EditorConfig still applies, the detected indents don't; without an override the editor's indent is kept). The jdt.ls profile carries the same override: it is patched into the bundled IntelliJ profile, or put into a minimal generated profile for the default formatter, and custom profiles are left alone. An unset Indent follows the tab size, as in Code Style. With tabs the request sends the tab size; every editor of a document gets the override when it is created, splits and reopened tabs included, not only after a settings change.

Checked with jdt.ls 1.63 on JDK 25: tab character, tab size 1 and indent 1 reformat a 4-space file to one tab per level with both the default and the IntelliJ formatter.

Fixes #935.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 14:56:56 +08:00
arookieofcтаa-rookie-of-C-language 18e16e76a4 fix(desktop): pass the real window label to project-requiring commands (#960)
Add Interpreter (creating a virtualenv), the Python packages list and pip install/uninstall, Settings › Git › Test, JVM listen-mode debugging and Create Patch › Save to file failed with "no project is open in this window", or ran without the project.

Their commands passed an empty window label to ops that resolve the calling window's project. They now pass the real window label, as the other project-scoped commands do. A sweep of every command that passes an empty label found exactly these seven ops using it: `sdk_locate_tools`, `sdk_python_create_venv`, `sdk_python_packages`, `sdk_python_pip`, `vcs_git_version`, `debug_listen_for_jvm` and `vcs_write_patch`. Without the window, the last one skipped the project's disk sync, so a patch saved inside the project showed up as an external change.

Fixes #955.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 14:50:49 +08:00
Piettro b55c398fb5 feat(python): add Pyrefly language server (#911)
Pyrefly (`pyrefly lsp`) joins basedpyright, Pyright and ty as a fallback Python language server. It is installable from Tools as a managed virtualenv tool and is listed among the interchangeable type checkers, before Ruff, so Ruff still runs after them.

Pyrefly only reports type errors in projects with a Pyrefly configuration (`pyrefly.toml` or `[tool.pyrefly]`); hover, completion and navigation work without one. A real-server test (ignored by default, needs `pyrefly` on PATH) covers startup, go-to-definition and diagnostics.

Co-authored-by: pcastro93 <[email protected]>
2026-11-03 14:42:45 +08:00
Jaw 038c23a2c8 feat(vcs): tint test files green in the changes tree (#940)
The changes tree in the Commit and Local Changes views now gives test files a light green background, so test changes stand out from production ones. A file counts as a test when it lies under a test source root (detected or marked by hand) or is named like a test (`*.test.ts`, `*Test.java`, …), the same check the project tree uses; folders under a test root get the tint too. Hover and selection still win.

The colour is a new `--bg-file-tests` token derived from `--success` and `--bg-island`, so every theme gets a matching tint, and it follows test roots as they are marked or unmarked.

Fixes #931.

Co-authored-by: jaw52 <[email protected]>
2026-11-03 14:40:18 +08:00
arookieofcтаa-rookie-of-C-language 2161a2ca03 fix(lsp): serialize the jdt.ls classpath resolve with the build lock (#946)
Running a main class in a multi-module Maven project could fail with "Cannot resolve the classpath: jdtls: Attempted to beginRule: P/<dependency>, does not match outer scope rule: P/<module>".

`java.project.getClasspaths` and `getSettings` ran outside the jdt.ls build lock, so they could overlap a build or an m2e refresh of a sibling module that takes a nested Eclipse scheduling rule. The launch now resolves the classpath and JDK under the same build lock the build commands use. A delegated external build already holds that lock across the launch, so its callers pass `build_lock_held` instead of waiting on it again, which would deadlock.

Fixes #933.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 14:39:29 +08:00
youngtseup c50d212a1d fix(app): keep update progress visible on the welcome screen (#951)
Check for Updates on the welcome screen showed nothing while the request was out: the check ran only as a status-bar task, and the welcome screen has no status bar. Leaving a project also dropped every notification, including a running update download.

A check started with no project or LightEdit window open now shows its progress in a balloon (keyed like the result, so the result replaces it); project windows keep it in the status bar. A project switch clears only project notifications and keeps the app-wide update ones.

Co-authored-by: youngtseup <[email protected]>
2026-11-03 14:38:19 +08:00
Piettro 843ff74d5d fix(tools): name uv as the installer for Python servers when it makes the virtualenv (#936)
CI / Rust (ubuntu-22.04) (push) Failing after 1h0m10s
CI / Remote server (linux musl) (push) Failing after 24m13s
CI / Cargo deny (push) Successful in 48s
CI / Frontend (push) Successful in 24m55s
CI / E2E (push) Failing after 14m16s
CI / Rust (macos-latest) (push) Canceled after 0s
CI / Rust (windows-latest) (push) Canceled after 0s
Tools and the install log named "pip (virtualenv)" for Python language servers (basedpyright, Pyright, ty, Ruff) even when the virtualenv is made with uv, which `install_venv` prefers whenever uv is on `PATH`.

The label now comes from the installer that will actually run: "uv (virtualenv)" when uv is on `PATH`, unchanged otherwise. debugpy's private copy still says pip, since it is always installed with `python -m pip`.

Co-authored-by: pcastro93 <[email protected]>
2026-11-03 14:37:26 +08:00
arookieofcтаa-rookie-of-C-language 53e76e29c6 fix(vcs): discover worktrees created while the project is open (#930)
A linked worktree created below the project while it was open never joined the repository set: its files had no status entries or gutter marks until the project was reopened.

A linked worktree's `.git` is a gitfile and its HEAD lives under `<main>/.git/worktrees/<name>/`. The watcher classified both as non-metadata, `.git/worktrees` was never watched, and the repository rescan only reacted to `<repo>/.git/HEAD`. The watcher now reports the `.git` path and `.git/worktrees/**` (without `.lock` files) as VCS changes and watches `.git/worktrees`; the rescan accepts a worktree's `.git`; and the Add/Remove Worktree commands refresh the repository set directly, so both the in-IDE and the external `git worktree` paths are covered.

Fixes #927.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 14:35:52 +08:00
arookieofc 86d082974f Merge pull request #2 from pcastro93/wayland-csd-shadow
fix(linux): draw GTK's CSD shadow on frameless windows under Wayland
2026-11-03 13:27:35 +08:00
Piettro CastroтаClaude Opus 5.5 ec5302d838 fix(linux): draw GTK's CSD shadow on frameless windows under Wayland
tao makes frameless Wayland windows client-side decorated (an empty GTK
title bar, so the compositor adds no frame) but leaves them undecorated,
so GTK draws no shadow or resize margin and dark windows blend into
whatever is behind them. Decorating the window after build keeps that
empty title bar: GTK adds the theme's shadow and resize edges, nothing
else. Applies to project windows and the Settings window; X11 is
unchanged (decorating there would bring back the WM frame).

- Detect Wayland from GDK's backend (tao's own test), not env vars.
- Measure windows by GTK's content size, which excludes the shadow
  margin, so remembered geometry and Settings placement don't grow.
- Skip the in-page resize handles on Wayland; GTK provides the edges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 00:14:14 -05:00
arookieofcтаa-rookie-of-C-language 00e717d8fd feat(vcs): diff preview in the Git window's Local Changes tab (#714)
The Local Changes tab of the Git tool window showed only the changes tree; a file's diff was visible only after opening a diff tab.

It now previews the selected file's working-tree diff beside the tree when the window is docked at the bottom and below it when docked on a side. The preview follows the selection (arrow keys included), shows a placeholder for no or multiple selection, and can be turned off with View Options › Show Diff Preview (persisted; the selection is kept when toggling).

The preview reuses the diff editor, whose toolbar did not fit a side-docked window: the editor is now a size container, the whitespace and highlighting pickers move to the settings menu below 640px and the separators go below 380px, buttons no longer shrink and the differences counter truncates.

Fixes #710.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 10:18:39 +08:00
Deng Liuтаdengliu 4f64ca3149 feat(agents): enable 1-click ACP registry install and updates for GitHub Copilot (#773)
GitHub Copilot, Qwen Code and Mistral Vibe were listed in the ACP Registry under their registry ids (github-copilot-cli, qwen-code, mistral-vibe), so they showed as unrelated third-party agents and could not be installed over the built-in providers. Registry ids now map to the built-in ids: the rows use the built-in name and icon, install and update into <config>/agents/<id>.toml, show "x.y.z available" when the registry has a newer version, and fall back to the built-in command on PATH after Remove. Installing never overwrites a hand-written agent config, and Remove only deletes a registry install. Changing installed providers reloads them and drops stale probes, so New Task sees the installed version right away.

Co-authored-by: dengliu <[email protected]>
2026-11-03 10:10:31 +08:00
l0ng-ai 93712a1588 chore: add bug report and feature request issue forms (#878)
Structured issue forms for bug reports and feature requests: environment, steps, expected/actual behaviour and logs for bugs; problem, proposal and alternatives for features. Both ask reporters to search existing issues first and keep one problem per issue; blank issues are disabled and the latest release is linked from the chooser. Forms do not require a particular language.

Refs #860
2026-11-03 09:39:11 +08:00
arookieofc dc14a46a17 Merge pull request #1 from fuqiuluo/fix/pr-607-revert-edge
fix(linux): keep settings window edge subtle
2026-11-03 08:42:45 +08:00
arookieofcтаa-rookie-of-C-language 416b65d65e test(editor): make the detach-tab save-failure document dirty (#924)
Since #920, saves skip clean documents, so the detach-tab save-failure test never reached its mocked failing save. The test now edits the document first, keeping its intent: a failing save keeps the tab and opens no window.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 08:31:19 +08:00
l0ng-aiтаClaude Opus 5.5 0a24b79b50 fix(editor): skip clean saves and refresh buffers after disk operations (#920)
Root cause, two parts:
- An explicit save (Save All before a checkout, before running, before Commit) also wrote documents that were not modified, running save actions such as stripping trailing whitespace and adding a final newline on them — files the user never touched gained whitespace-only changes. Saves now skip clean documents, as autosave already did.
- After our own VCS operations rewrote files (checkout, rollback, stash, patch, ignore, commit/worktree hooks, Directory Compare), clean editor buffers were only refreshed by the file watcher, which can miss a rewrite that keeps the length and the timestamp's millisecond. Those operations now reload clean buffers synchronously before returning, keeping each document's chosen encoding; modified buffers keep the existing conflict handling.

Fixes #893

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 07:54:34 +08:00
l0ng-aiтаClaude Opus 5.5 d9929bbe44 fix(vcs): resolve shelf files against their owning repository (#919)
Root cause: shelved file paths are relative to the repository they were shelved from, but Compare with Local, Show Diff, navigation and Unshelve joined them to the selected VCS root. In a project folder that is not itself a repository (or holds several), the local file was not found and Compare with Local stayed disabled. Shelves now record their repository (older shelves fall back to the primary repository), imported patches record the current one, and every shelf action resolves paths against it, with Windows separators handled. Stash and Apply Patch already kept their repository.

Fixes #875

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 07:52:55 +08:00
fuqiuluo d830d21d46 fix(linux): keep the settings edge above content 2026-11-03 07:20:03 +08:00
fuqiuluo fd8161a5a7 Revert "fix(linux): make the frameless settings window edge readable"
This reverts commit bbb1be69a2.
2026-11-03 07:15:24 +08:00
arookieofc bbb1be69a2 fix(linux): make the frameless settings window edge readable
#595 follow-up: the 1px --border-window hairline is nearly invisible on
the dark theme (#40434a against a dark desktop), which fuqiuluo confirmed
on Fedora 44 GNOME Wayland after the first edge commit. Blend the
foreground tone into the ring so the boundary reads on every theme;
still CSS-only, since Wayland gives undecorated windows no compositor
shadow to paint outside the surface.
2026-11-03 07:05:16 +08:00
kkmihaiтаkkMihai 7af2b098cc feat(terminal): paste clipboard media as file paths (#880)
CI / Rust (ubuntu-22.04) (push) Failing after 1h0m17s
CI / Remote server (linux musl) (push) Failing after 25m8s
CI / Cargo deny (push) Successful in 1m39s
CI / Frontend (push) Successful in 25m40s
CI / E2E (push) Failing after 15m24s
CI / Rust (macos-latest) (push) Canceled after 0s
CI / Rust (windows-latest) (push) Canceled after 0s
Pasting an image, audio or video from the clipboard into a local terminal saves the bytes to the per-user terminal cache (20 MB limit, files older than 24 h cleaned up on the next paste, private permissions) and inserts the shell-quoted path without running anything. Copied files paste their original paths, plain text pastes unchanged, and SSH sessions keep the existing remote image-paste route. Paths are quoted per shell (zsh/bash, fish, PowerShell, cmd.exe); fish quoting now escapes backslashes and single quotes.

Fixes #838

Co-authored-by: kkMihai <[email protected]>
2026-11-03 02:09:17 +08:00
Florent Vтаflorentvdry db5251efe6 fix(plugins): install plugin packages from a .zip (#896)
Root cause: Install Plugin from Disk only opened a folder picker and the host could only copy folders, so a zipped plugin could not be installed. The picker now accepts a .zip or a package's plugin.toml, and the host's install_from_path unpacks a zip to a temporary folder and runs it through the existing install_from_dir validation. The package may sit at the archive root or in its only folder (archiver metadata such as __MACOSX is ignored). Archives with unsafe paths or symbolic links, more than 10,000 entries or over 1 GB unpacked are refused, and a zip without plugin.toml (e.g. an IntelliJ plugin) gets a clear error.

Fixes #892

Co-authored-by: florentvdry <[email protected]>
2026-11-03 01:44:28 +08:00
arookieofcтаa-rookie-of-C-language eb633f6ca6 feat(run): run npm scripts from package.json gutter icons (#898)
Every entry under the top-level `scripts` of a package.json gets a run gutter icon with Run/Debug for that script. It uses the detected npm run configuration (re-detected at click time) and otherwise a temporary configuration built with the same package-manager precedence as backend detection: the `packageManager` field, then the lockfile, inheriting the workspace root's manager for members. Workspace member configuration ids use the full relative directory, as the backend does. The "Show run icons" preference hides these icons too, and the markers are real buttons with translated titles.

Fixes #894

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 00:37:14 +08:00
ntbang0901 7c7d656a50 fix(run): select and copy the whole console output with Select All (#903)
Root cause: Cmd/Ctrl+A in the Run console fell through to the browser and selected the whole window, and copying only saw the rows the virtualizer had mounted. Select All now selects the console only (also in its context menu), and copying after it — keyboard, context menu or native copy — takes the whole buffer. copySelectionOnKeyDown accepts a textOf callback for other views that do not mount all their text.

Refs #746

Co-authored-by: ntbang0901 <[email protected]>
2026-11-02 23:41:21 +08:00
Jonas Zuberbuehlerтаjonaszuberbuehler b3c0efd804 fix(web): keep the built-in server inside the served root (#887)
Root cause: the built-in web server rejected `..` segments but followed symlinks, so a committed link such as `x -> /` served any file on disk, also in Restricted Mode. The served root is canonicalized per request, and the requested file — and the index.html served for a directory — is refused with 404 when its real path lies outside it. The server opens the checked real path, and Content-Type still follows the requested name. Links inside the project (e.g. pnpm node_modules) keep working.

Fixes #886

Co-authored-by: jonaszuberbuehler <[email protected]>
2026-11-02 23:39:32 +08:00
l0ng-ai c0c56dac8a fix(run): enable Spring console colours with manual classpaths (#888)
Spring Boot runs with a manual classpath (or no classpath placeholder) skip Java classpath resolution and so also skipped the console colour VM option. The shared console VM options are now applied on that launch path too; explicit spring.output.ansi.enabled settings are kept and resolved classpaths get the option once.
2026-11-02 23:37:52 +08:00
Andrea Basileтаandreabasile 51988985c5 fix(run): run a Python script with the project interpreter, not the runserver command line (#897)
Root cause: projectPython built the interpreter prefix from the first Python configuration by dropping only the .py arguments, so a Django `manage.py runserver` config left `runserver` in the prefix. The prefix now ends where the program starts (`-m` or the script), so program arguments such as `runserver` and `test` never reach it; `uv run python` is kept. Covers both plain scripts and pytest files derived from the same prefix.

Co-authored-by: andreabasile <[email protected]>
2026-11-02 23:37:47 +08:00
arookieofcтаa-rookie-of-C-language ece2b2a59e feat(templates): New Go Module template for go.mod files (#884)
New ▸ Go Module creates go.mod with `module $PROJECT_NAME$` and a `go 1.20` directive. The go.mod language, icon and gopls were already registered; only the file template was missing. It also appears in Search Everywhere and Settings ▸ File and Code Templates.

Fixes #882

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-02 23:37:41 +08:00
arookieofc 58ff3e93d0 fix(linux): paint a hairline edge on the frameless settings window
Linux compositors draw no shadow for undecorated windows (Wayland has
no server-side decorations at all), so the frameless settings window is
indistinguishable from the desktop there — #595's follow-up after the
Windows DWM-shadow fix. Paint a 1px --border-window inset ring around
the window root: the webview draws the same hairline on every
windowing system.
2026-11-02 20:50:29 +08:00
arookieofc 795f8e85f1 fix(windows): de-parent settings window on Windows so DWM paints its shadow
An owned child (WS_POPUP) of a borderless parent gets no DWM shadow,
leaving the frameless settings window flat against its project window.
Ownership is already tracked by the settings-<parent> label (parent-close
cleanup in on_window_event, menu modality), so make the settings window
top-level on Windows; macOS and Linux keep the native parent link.
2026-11-02 20:50:29 +08:00
262 змінених файлів з 10601 додано та 610 видалено

No files matched your search

+91
Переглянути файл
@@ -0,0 +1,91 @@
---
name: issue-fix
description: Triage and fix a GitHub issue (or a user-reported bug) end to end — reproduce, find the root cause, generalise it to every sibling case, fix the class rather than the instance, verify, and open one PR. Use when given an issue URL/number or asked to fix a reported bug and open a PR ("看看这个 issue", "修一下这个 bug", "提 pr").
---
# Fix an issue: from one case to the whole class
The reported case is one sample of a defect class. A fix that only makes the
screenshot go away is not done: the next question is always "does this break for other
languages / platforms / entry points too?". Answer that before anyone asks.
## 1. Read and reproduce
- `gh issue view <n> --comments` (repo `l0ng-ai/openidea`). Read attached logs/screenshots
closely: OS, language, toolchain versions, exact error text.
- Locate the code path and confirm the claim in code, with `file:line` evidence.
Say plainly whether it is a real bug, a missing feature, or user environment.
- Reproduce locally when possible (`fixtures/` projects, `/verify` for runtime). If the
reporter's platform (often Windows/Linux) can't be reproduced here, say so up front.
- Do not ask for a generic environment/log checklist before trying the flow and inspecting the code.
Record the attempt and result; ask only for a fact that actually blocks the next diagnostic step.
Missing fields, limited time, or unavailable automation are not by themselves reasons to ask the reporter.
- Treat a maintainer-confirmed bug as an investigation task even if local reproduction fails. Distinguish
“not reproduced here” from “not a bug”, and do not require the reporter to prove its existence again.
## 2. Name the root cause as a class
Write one sentence of the form "<mechanism> is missing/wrong, so any <X> hits it",
not "<this button> is broken". Typical classes in this codebase:
- Per-language config handled for one language only (`languages/*.toml`, `ide-sdk`).
- Platform gaps: paths, executables, shells, `.cmd`/`.exe`, separators — macOS-only code.
- Toolchain/version discovery: one probe location, no version check, no rescan.
- Two features each implementing half a flow and never joined (feature isolation →
should go through an action/service).
- State not reset on project switch / window reuse; events not scoped per window.
- Failure surfaced as raw stderr/stack trace or retried until "crashed" instead of a
clear status with an action.
- UI: same primitive styled differently in N places.
## 3. Sweep for siblings
Search systematically, not by memory:
- Same pattern elsewhere: `git grep` the function, the config key, the error string,
the hard-coded path/flag. Check every `languages/*.toml` entry and every platform branch.
- Same flow for other languages/runtimes (Java ↔ Kotlin/Gradle, Python ↔ venv/uv,
Node ↔ Deno/Bun, Go, Rust …): would they fail the same way?
- Other callers/entry points of the same flow (menu, context menu, gutter, shortcut, CLI arg).
- Neighbouring failure modes of the same mechanism (not installed / wrong version /
installed but crashes / slow start / installed mid-session).
For broad sweeps spawn one Explore agent with the class description, not the instance.
## 4. Decide the fix at the right altitude
- Fix the mechanism once (shared helper, action, config hook) so siblings are fixed
by construction; don't patch each call site.
- Respect `AGENTS.md` rules (crate boundaries, no cross-feature imports, `IdeResult`,
UTF-16). If the right fix breaks a rule, pick the rule-respecting design and say why.
- Compare with how established IDEs solve it when relevant; prefer the established answer.
- Present: root cause, sibling table, proposed fix, what's deferred. When the user leaves
the choice to you, go ahead without asking again.
## 5. Implement and test the class
- Tests cover the class: table-driven over languages/platforms/states, not just the
reported input. Include the reporter's case verbatim.
- Run the scoped checks (`pnpm vitest run <path>`, `cargo nextest run -p <crate>`), then
`/verify` in the app for UI or runtime behaviour.
## 6. PR
- One branch `fix/<slug>`, one PR unless the user asks otherwise; `Fixes #<n>` in the body.
- Don't stage untracked IDE-state dirs (`.ideal/`, `.openidea/`) or screenshots.
- PR body follows `.github/pull_request_template.md`: `Closes #<n>`, then
**What and why** (user-visible change + root cause at class level, 2–4 sentences),
**How it was verified** (commands run and results, siblings fixed/deferred, what could break and how
it was checked, what was not verified, e.g. "Windows not tested"; for UI changes the before/after
screenshot paths from `/verify`), **Review focus** (optional). Short and plain.
## Report format
Reply in the user's language:
```
Root cause: <one sentence, class level>
Sibling sweep:
| Location / case | Affected? | Action |
Fixed / not covered (why) / not verified (platform)
PR: <url>
```
+57
Переглянути файл
@@ -0,0 +1,57 @@
---
name: verify
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
---
# Verify OpenIDEA in the running app
## Launch
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
session already running for this worktree, reuse that one.
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
`location.href` before acting if anything looks off.
- Make sure the binary contains the change: a session already running for this worktree may be an
older build. Restart it after Rust changes; frontend changes reload through Vite.
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
reload shows an empty `#root`. Stop that app and start the session again.
- Stop everything you started when done and nothing else; never use process-name kills.
## Driving
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
screenshots come back black.
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
## Evidence
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
flows: a numbered series (`after-1.png`, `after-2.png`, ...).
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
acceptance entry. Never commit screenshots to the feature branch.
## Fixture
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
## Flows worth driving
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/issue-fix
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/verify
+75
Переглянути файл
@@ -0,0 +1,75 @@
name: Bug report
description: Something in OpenIDEA doesn't work as expected
labels: [bug]
body:
- type: markdown
attributes:
value: |
Thanks for reporting! Keep logs and error messages exactly as they appear.
One problem per issue, please. If you have several, open one issue for each.
- type: checkboxes
id: checks
attributes:
label: Before you start
options:
- label: I searched [existing issues](https://github.com/l0ng-ai/openidea/issues?q=is%3Aissue) and this hasn't been reported yet.
required: true
- label: I'm on the [latest release](https://github.com/l0ng-ai/openidea/releases/latest), or I noted below that I can't update.
required: true
- type: textarea
id: environment
attributes:
label: Environment
description: |
Open **About OpenIDEA** (macOS: OpenIDEA menu; Windows/Linux: Help menu), click **Copy Info**, and paste it here. Also mention the project type if it matters (e.g. Gradle multi-module, Spring Boot, Go workspace) and whether you use remote development.
render: text
placeholder: |
About OpenIDEA
Version: 0.1.33
Build: ...
Platform: macOS aarch64
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: Start from opening OpenIDEA or a project. A small sample project or snippet helps a lot.
placeholder: |
1. Open a Gradle project whose settings.gradle includes modules in a loop
2. Open the Gradle tool window
3. ...
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Minimal reproduction
description: A link to a small public repository, or the smallest files/snippet that trigger the problem. Optional, but it's the fastest way to get a fix.
placeholder: https://github.com/you/repro-project
- type: textarea
id: expected
attributes:
label: Expected behavior
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
description: What happened instead. Screenshots or a recording are welcome.
validations:
required: true
- type: textarea
id: logs
attributes:
label: Logs
description: |
Use **Help → Show Log in Finder / Explorer / Files** to find `openidea.log` and paste the lines around the problem, or attach the file. Include console output or error messages too. Check for tokens or passwords before posting.
render: text
- type: textarea
id: extra
attributes:
label: Additional context
description: Anything else, such as whether it worked in an earlier version.
+5
Переглянути файл
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Download the latest release
url: https://github.com/l0ng-ai/openidea/releases/latest
about: Many problems are already fixed. Please check the latest version before reporting.
+48
Переглянути файл
@@ -0,0 +1,48 @@
name: Feature request
description: Suggest a new feature or an improvement
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
One request per issue, please.
- type: checkboxes
id: checks
attributes:
label: Before you start
options:
- label: I searched [existing issues](https://github.com/l0ng-ai/openidea/issues?q=is%3Aissue) and this hasn't been requested yet.
required: true
- type: textarea
id: problem
attributes:
label: Problem
description: What are you trying to do, and what gets in the way today?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: How you'd like it to work. Mockups or examples from other tools are welcome.
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: How we'll know it's done. One observable behavior per line.
placeholder: |
- [ ] Right-clicking a test class shows "Run with Coverage"
- [ ] Coverage results open in the Coverage tool window
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives and workarounds
description: Other approaches you considered, or what you do now instead.
- type: textarea
id: extra
attributes:
label: Additional context
+17
Переглянути файл
@@ -0,0 +1,17 @@
Closes #
## What and why
<!-- 2–4 sentences: the change a user notices, and the root cause.
If it doesn't fit, the PR is probably too big; split it. -->
## How it was verified
<!-- Required. Commands you actually ran and their results; what else this could
affect and how you checked it still works.
UI changes: before/after screenshots. Multi-step interactions: a recording.
Backend changes: logs or command output. -->
## Review focus
<!-- Optional: anything you want reviewers to look at closely. -->
+69
Переглянути файл
@@ -0,0 +1,69 @@
name: PR check
on:
# pull_request_target so the check can label PRs from forks. It never checks out
# or runs PR code: it only reads the PR title and description.
pull_request_target:
types: [opened, edited, reopened, ready_for_review]
permissions:
issues: write
pull-requests: write
concurrency:
group: pr-check-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
check:
if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
script: |
const pr = context.payload.pull_request;
const LABEL = 'needs-info';
const MARKER = '<!-- pr-check -->';
// Docs, CI and pure refactors may skip the linked issue.
const NO_ISSUE_TYPES = /^(docs|ci|build|chore|refactor|style|test)(\(.+\))?!?:/;
const body = (pr.body || '').replace(/<!--[\s\S]*?-->/g, '');
const problems = [];
const linksIssue =
/\b(close[sd]?|fix(e[sd])?|resolve[sd]?)\s*:?\s+(#\d+|https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/issues\/\d+)/i.test(body);
if (!linksIssue && !NO_ISSUE_TYPES.test(pr.title)) {
problems.push('Link the issue this PR resolves, e.g. `Closes #123`.');
}
const verified = body.match(/^##+\s*How it was verified\s*$([\s\S]*?)(?=^##+\s|(?![\s\S]))/im);
if (!verified || !verified[1].trim()) {
problems.push('Fill in **How it was verified**: the commands you ran and their results. UI changes need before/after screenshots.');
}
const { owner, repo } = context.repo;
const issue_number = pr.number;
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
const labeled = pr.labels.some(l => l.name === LABEL);
if (problems.length) {
const text = `${MARKER}\nThanks for the PR. Before review, please update the description (see [CONTRIBUTING.md](https://github.com/${owner}/${repo}/blob/main/CONTRIBUTING.md)):\n\n${problems.map(p => `- ${p}`).join('\n')}\n\nThis check reruns when you edit the description.`;
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body: text });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number, body: text });
}
if (!labeled) {
await github.rest.issues.addLabels({ owner, repo, issue_number, labels: [LABEL] });
}
return;
}
// Only undo what this check did: the label is cleared only when our comment exists.
if (existing) {
await github.rest.issues.deleteComment({ owner, repo, comment_id: existing.id });
if (labeled) {
await github.rest.issues.removeLabel({ owner, repo, issue_number, name: LABEL }).catch(() => {});
}
}
+7 -3
Переглянути файл
@@ -30,9 +30,13 @@ target/
test-results/
playwright-report/
# Local AI agent files
CLAUDE.md
.claude/
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
CLAUDE.local.md
.claude/*
!.claude/skills/
.claude/skills/*
!.claude/skills/verify
!.claude/skills/issue-fix
# Local reference screenshots
pycharm-screenshots/
+1
Переглянути файл
@@ -10,6 +10,7 @@
"target",
"src/bindings.ts",
"src/editor/core/cm/angular/parser*.ts",
"src/editor/core/cm/jsp/parser*.ts",
"docs/plugins/themes.md",
"pnpm-lock.yaml",
"**/*.toml",
+118
Переглянути файл
@@ -0,0 +1,118 @@
# OpenIDEA — contributor guide
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
Visual style: dark, low-contrast greys, one cool accent
(`src/styles/tokens.css` is the source of truth for colours and metrics).
## Layout
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
types; never reach into another crate's internals.
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
(thin typed IPC adapters), `events.rs`. No domain logic here.
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
keymap + dispatcher, context keys / `when` clauses, project store.
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
exporting `activate()` registered in `src/features/index.ts`.
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
- `crates/ide-host` — the `openidea-server` binary for remote development.
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins;
`templates/` — plugin starter templates.
- `e2e/` — Playwright UI tests (`pnpm e2e`). `fixtures/` — sample projects per language
for manual and automated testing.
## Rules
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
- Long work never blocks the UI thread or a Tauri command thread: use
`spawn_blocking`/rayon, honour `CancellationToken`.
- Frontend features never import each other; communicate via actions, contributions
and services. All user-invocable behaviour is an action with a stable id; default
shortcuts live in `src/platform/keymaps/`.
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
- User-visible text goes through the text catalog: add every new string to both
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
- Keep comments sparse and purposeful; match surrounding style.
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
unavailable or cannot cover the required checks.
## Issues & PRs
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one issue per PR with
`Closes #<n>`, reproduce first, keep the diff focused, short plain description, and a
**How it was verified** section with commands run, results and (for UI) before/after screenshots.
Unclear product decisions → `needs-decision` and stop.
## Skills
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`verify` drives the running app through Tauri MCP and captures screenshot evidence;
`issue-fix` takes an issue from reproduction to one PR.
## Commands
- `pnpm tauri dev` — run the app with worktree isolation (Node 22.18+).
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
`pnpm gen:bindings`.
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
benches vs budgets). Budgets: `perf/budgets.json`.
## Before opening a PR
Run what CI runs for the parts you touched:
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
commit `src/bindings.ts`; CI fails if it differs.
- Frontend: `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm test`,
`pnpm build`, and `pnpm e2e` for UI flows.
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`).
## Pitfalls
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
the filter and runs the whole suite, which takes several minutes.
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
before committing. A cold build cache can take around 5 minutes. Run long checks one at
a time, not chained in one shell call that may hit the 10-minute tool timeout.
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
doesn't make the first launch fast.
## Parallel worktrees
Several worktrees can be developed and run side by side.
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
`pnpm install` in it.
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
URL to Tauri, and reports an existing launcher instead of starting another for the same
worktree. HMR uses the Vite port.
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
worktree path captured at build time, independent of launch cwd. Launching the same debug
binary again focuses its existing instance and forwards its path argument. Different
worktrees and the installed release can coexist. `--release` uses normal release identity
and bypasses the development wrapper.
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
default MCP session belongs to this worktree.
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
`target` symlinks at a shared directory.
- Each worktree's first build is cold (around 5 minutes) and its Cargo output takes
15–30 GB. Avoid running several heavy builds on one machine at the same time.
- Stop only processes started for the current worktree/session. Never use broad
process-name kills such as `pkill openidea`.
- When done: stop that worktree's app and dev session, delete its build output, then
`git worktree remove ../<name>`.
Symlink
+1
Переглянути файл
@@ -0,0 +1 @@
AGENTS.md
+35
Переглянути файл
@@ -0,0 +1,35 @@
# Contributing to OpenIDEA
These rules apply to everyone, and to any coding agent working on their behalf.
Project layout, coding rules, commands and checks are in [AGENTS.md](AGENTS.md).
## Issues
- One problem or request per issue. Use the issue forms.
- Bugs: steps that reproduce the problem from a fresh start. A minimal sample
project is the fastest way to get a fix.
- Features: state the problem and the acceptance criteria. A feature is ready to
build once a maintainer labels it `planned`.
- Labels track status: `needs-info` waits on the reporter, `needs-decision` waits
on a maintainer, `planned` is accepted, `needs-acceptance` has a fix waiting to be
checked.
## Pull requests
- One issue per PR, linked with `Closes #123`. Feature PRs need a `planned` issue.
Docs, CI and pure refactors may skip the issue.
- Reproduce the problem first, or write a test that fails before the fix.
- Fix the cause, and check whether the same cause breaks anything nearby.
- Keep the diff focused. Unrelated refactors go in their own PR.
- Title: [Conventional Commits](https://www.conventionalcommits.org/), e.g.
`fix(editor): keep the caret visible after folding`.
- Fill in the template. Keep the description short and in plain words. If it
doesn't fit in a few sentences, the PR is probably too big.
- **How it was verified** is required: the commands you ran and their results,
and what else the change could affect. UI changes need before/after screenshots;
multi-step interactions need a recording.
- If a change needs a product decision you can't make, ask in the issue and stop
rather than guessing.
A check on each PR adds `needs-info` when the issue link or the verification
section is missing, and removes it once they're filled in.
Створено
+3
Переглянути файл
@@ -4387,6 +4387,7 @@ dependencies = [
"tokio",
"toml 0.9.12+spec-1.1.0",
"tracing",
"zip",
]
[[package]]
@@ -4428,6 +4429,7 @@ dependencies = [
"tracing",
"wasmtime",
"wasmtime-wasi",
"zip",
]
[[package]]
@@ -6152,6 +6154,7 @@ dependencies = [
"block2 0.6.2",
"dirs 6.0.0",
"dunce",
"gtk",
"ide-agent",
"ide-analysis",
"ide-build",
+3 -2
Переглянути файл
@@ -2,8 +2,9 @@
## Project Lombok
`plugins/lombok/lombok-1.18.48-openidea.1.jar` contains Project Lombok v1.18.48 with the Equinox
classloader fix from [projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059).
`plugins/lombok/lombok-1.18.48-openidea.2.jar` contains Project Lombok v1.18.48 with the Equinox
classloader fix from [projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059)
and the ECJ constructor-call fix from [projectlombok/lombok#4089](https://github.com/projectlombok/lombok/pull/4089).
Copyright (C) 2009-2021 The Project Lombok Authors. MIT license and bundled component
notices are retained in [plugins/lombok/LICENSE](plugins/lombok/LICENSE) and inside the jar.
Source tag, patch commits and build instructions: [plugins/lombok/README.md](plugins/lombok/README.md).
+32 -13
Переглянути файл
@@ -301,23 +301,41 @@ impl AgentManager {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref());
let list = specs
.iter()
.map(|p| AgentProvider {
id: p.id.clone(),
name: p.name.clone(),
command: std::iter::once(p.command.as_str())
.chain(p.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" "),
installed: provider::installed(&p.command),
config: self.shared.known_config(&p.id),
commands: self.shared.known_commands(&p.id),
source: p.source.clone(),
.map(|p| {
let mut info = provider::describe(p);
info.config = self.shared.known_config(&p.id);
info.commands = self.shared.known_commands(&p.id);
info
})
.collect();
*self.shared.providers.write() = specs;
let mut prev = self.shared.providers.write();
let mut probes = self.shared.probes.lock();
probes.retain(|id, _| {
let old = prev.iter().find(|p| &p.id == id);
let new = specs.iter().find(|p| &p.id == id);
matches!((old, new), (Some(a), Some(b)) if a.command == b.command && a.args == b.args && a.env == b.env)
});
*prev = specs;
list
}
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
return Err(IdeError::unavailable("there is no custom agents directory"));
};
provider::set_builtin_command(&dir, id, command.as_deref())
}
/// Re-reads configured/installed agents, drops cached probes, and notifies subscribers.
pub fn reload_providers(&self) {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref());
*self.shared.providers.write() = specs;
self.shared.probes.lock().clear();
self.shared.emit(AgentEvent::Providers);
}
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// and, for Claude Code, skills and custom commands on disk it has not listed.
@@ -808,7 +826,8 @@ impl AgentManager {
// A copy of the task (a fork) may work in the same worktree.
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
if remove_worktree && !shared && isolation == Isolation::Worktree && cwd.exists() {
blocking(move || worktree::remove(&root, &cwd)).await?;
let worktrees = self.shared.paths.worktrees_dir.clone();
blocking(move || worktree::remove(&root, &worktrees, &cwd)).await?;
}
self.tasks.write().remove(id);
*task.deleted.lock() = true;
+20
Переглянути файл
@@ -322,6 +322,15 @@ pub struct AgentProvider {
pub name: String,
/// The command line that starts its ACP server.
pub command: String,
/// Executable and arguments actually launched, without flattening paths containing spaces.
pub program: String,
pub args: Vec<String>,
pub default_program: Option<String>,
pub default_args: Vec<String>,
pub login_hint: Option<String>,
pub command_overridden: bool,
pub command_editable: bool,
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
@@ -331,6 +340,15 @@ pub struct AgentProvider {
pub source: AgentSource,
}
/// Why the executable cannot be changed in built-in agent settings.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentCommandReadOnlyReason {
PackageRunner,
Registry,
CustomAgent,
}
/// Where an agent comes from.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
@@ -413,4 +431,6 @@ pub enum AgentEvent {
index: u32,
entry: AgentEntry,
},
/// The installed or configured agent providers changed.
Providers,
}
+227 -5
Переглянути файл
@@ -2,7 +2,8 @@
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
//! Registry, see `registry`).
use crate::AgentSource;
use crate::{AgentCommandReadOnlyReason, AgentProvider, AgentSource};
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@@ -80,9 +81,92 @@ fn builtins() -> Vec<ProviderSpec> {
.collect()
}
/// Whether `id` names a built-in agent.
/// Whether `id` names a built-in agent that needs no registry install (native drivers
/// and `npx -y` adapters). CLI built-ins (`copilot`, `gemini`, …) can be installed and
/// updated from the ACP Registry into `<config>/agents/<id>.toml`.
pub(crate) fn is_builtin(id: &str) -> bool {
BUILTIN.iter().any(|b| b.0 == id)
BUILTIN.iter().any(|&(bid, _, driver, cmd, _)| bid == id && (driver != Driver::Acp || cmd.first() == Some(&"npx")))
}
/// Display name of a built-in agent, when `id` is one.
pub(crate) fn builtin_name(id: &str) -> Option<&'static str> {
BUILTIN.iter().find(|&&(bid, _, _, _, _)| bid == id).map(|&(_, name, _, _, _)| name)
}
/// The built-in spec of `id`.
pub(crate) fn builtin_spec(id: &str) -> Option<ProviderSpec> {
builtins().into_iter().find(|s| s.id == id)
}
/// Public launch metadata, keeping the built-in defaults separate from agent-file overrides.
pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
let builtin = builtin_spec(&spec.id);
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
Some(AgentCommandReadOnlyReason::Registry)
} else if let Some(default) = &builtin {
matches!(default.command.as_str(), "npx" | "bunx" | "uvx").then_some(AgentCommandReadOnlyReason::PackageRunner)
} else {
Some(AgentCommandReadOnlyReason::CustomAgent)
};
AgentProvider {
id: spec.id.clone(),
name: spec.name.clone(),
command: std::iter::once(spec.command.as_str())
.chain(spec.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" "),
program: spec.command.clone(),
args: spec.args.clone(),
default_program: builtin.as_ref().map(|b| b.command.clone()),
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
login_hint: Some(spec.login_hint.clone()),
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
config: vec![],
commands: vec![],
source: spec.source.clone(),
}
}
/// Overrides built-in `id`'s command through its agent file, preserving other
/// customizations. `None` restores the built-in command and removes a redundant file.
pub(crate) fn set_builtin_command(custom_dir: &Path, id: &str, command: Option<&str>) -> IdeResult<()> {
let Some(builtin) = builtin_spec(id) else {
return Err(IdeError::invalid(format!("{id} is not a built-in agent")));
};
let file = custom_dir.join(format!("{id}.toml"));
let mut agent = if file.try_exists()? {
CustomAgent::read(&file).map_err(IdeError::invalid)?
} else {
CustomAgent {
name: Some(builtin.name.clone()),
driver: builtin.driver,
command: builtin.command.clone(),
args: builtin.args.clone(),
env: BTreeMap::new(),
registry: None,
}
};
if agent.registry.is_some() {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
if command.is_none()
&& agent.name.as_deref() == Some(builtin.name.as_str())
&& agent.driver == builtin.driver
&& agent.args == builtin.args
&& agent.env.is_empty()
{
match std::fs::remove_file(&file) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
_ => {}
}
return Ok(());
}
agent.command = command.unwrap_or(&builtin.command).to_owned();
agent.write(&file)?;
Ok(())
}
/// An agent file, `<config>/agents/<id>.toml`.
@@ -162,7 +246,7 @@ pub(crate) fn load(custom_dir: Option<&Path>) -> Vec<ProviderSpec> {
Some(r) => AgentSource::Registry { version: r.version, update: None },
None => AgentSource::Custom,
};
let spec = ProviderSpec {
let mut spec = ProviderSpec {
name: agent.name.unwrap_or_else(|| id.clone()),
driver: agent.driver,
command: agent.command,
@@ -173,7 +257,13 @@ pub(crate) fn load(custom_dir: Option<&Path>) -> Vec<ProviderSpec> {
id,
};
match specs.iter_mut().find(|s| s.id == spec.id) {
Some(existing) => *existing = spec,
Some(existing) => {
spec.login_hint = existing.login_hint.clone();
if spec.source == AgentSource::Custom {
spec.source = AgentSource::Builtin;
}
*existing = spec;
}
None => specs.push(spec),
}
}
@@ -211,6 +301,54 @@ fn is_executable(p: &Path) -> bool {
mod tests {
use super::*;
#[test]
fn launch_metadata_distinguishes_defaults_overrides_and_read_only_agents() {
let dir = tempfile::tempdir().unwrap();
let list = || load(Some(dir.path())).iter().map(describe).collect::<Vec<_>>();
let defaults = list();
let codex = defaults.iter().find(|p| p.id == "codex").unwrap();
assert_eq!(codex.program, "codex");
assert_eq!(codex.default_program.as_deref(), Some("codex"));
assert_eq!(codex.args, ["app-server"]);
assert_eq!(codex.default_args, codex.args);
assert_eq!(codex.command, "codex app-server");
assert_eq!(codex.login_hint.as_deref(), Some("Run `codex login` in a terminal."));
assert!(!codex.command_overridden);
assert!(codex.command_editable);
for p in &defaults {
assert_eq!(p.source, AgentSource::Builtin);
assert!(p.default_program.is_some());
assert_eq!(p.command_editable, !p.id.ends_with("-acp"));
assert_eq!(
p.command_read_only_reason,
p.id.ends_with("-acp").then_some(AgentCommandReadOnlyReason::PackageRunner)
);
}
set_builtin_command(dir.path(), "codex", Some("/path with spaces/codex")).unwrap();
let overridden = list().into_iter().find(|p| p.id == "codex").unwrap();
assert_eq!(overridden.program, "/path with spaces/codex");
assert_eq!(overridden.args, codex.args);
assert_eq!(overridden.default_program, codex.default_program);
assert!(overridden.command_overridden && overridden.command_editable);
assert_eq!(overridden.source, AgentSource::Builtin);
set_builtin_command(dir.path(), "codex", Some("codex")).unwrap();
assert!(!list().iter().find(|p| p.id == "codex").unwrap().command_overridden);
std::fs::write(
dir.path().join("gemini.toml"),
"command = \"/registry/gemini\"\n[registry]\nid = \"gemini\"\nversion = \"1.0\"\n",
)
.unwrap();
let registry = list().into_iter().find(|p| p.id == "gemini").unwrap();
assert_eq!(registry.default_program.as_deref(), Some("gemini"));
assert!(!registry.command_editable);
assert_eq!(registry.command_read_only_reason, Some(AgentCommandReadOnlyReason::Registry));
assert!(matches!(registry.source, AgentSource::Registry { .. }));
std::fs::write(dir.path().join("mine.toml"), "command = \"mine\"\n").unwrap();
let custom = list().into_iter().find(|p| p.id == "mine").unwrap();
assert_eq!(custom.default_program, None);
assert_eq!(custom.command_read_only_reason, Some(AgentCommandReadOnlyReason::CustomAgent));
}
#[test]
fn custom_agents_extend_and_override_the_builtins() {
let dir = tempfile::tempdir().unwrap();
@@ -230,6 +368,90 @@ mod tests {
assert!(installed("sh"));
}
#[test]
fn set_builtin_command_overrides_and_clears_a_builtin() {
let dir = tempfile::tempdir().unwrap();
set_builtin_command(dir.path(), "not-a-builtin", Some("/x")).unwrap_err();
set_builtin_command(dir.path(), "claude", Some("/opt/claude")).unwrap();
let claude = load(Some(dir.path())).into_iter().find(|s| s.id == "claude").unwrap();
assert_eq!((claude.command.as_str(), claude.driver), ("/opt/claude", Driver::Claude));
assert!(claude.args.is_empty());
// A registry install is neither overwritten nor removed by a command override.
let path = dir.path().join("codex.toml");
CustomAgent {
name: None,
driver: Driver::Acp,
command: "amp".into(),
args: vec![],
env: BTreeMap::new(),
registry: Some(RegistryRef { id: "amp-acp".into(), version: "1.0.0".into() }),
}
.write(&path)
.unwrap();
set_builtin_command(dir.path(), "codex", Some("/x")).unwrap_err();
set_builtin_command(dir.path(), "codex", None).unwrap_err();
assert!(path.exists());
// Clearing (twice) returns the built-in to auto-detection.
set_builtin_command(dir.path(), "claude", None).unwrap();
set_builtin_command(dir.path(), "claude", None).unwrap();
assert!(!dir.path().join("claude.toml").exists());
assert_eq!(load(Some(dir.path())).iter().find(|s| s.id == "claude").unwrap().command, "claude");
}
#[test]
fn set_builtin_command_preserves_other_customizations_on_save_and_reset() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("claude.toml");
for field in ["name", "driver", "args", "env", "unnamed"] {
let mut agent = CustomAgent {
name: Some("Claude Code".into()),
driver: Driver::Claude,
command: "/old/claude".into(),
args: vec![],
env: BTreeMap::new(),
registry: None,
};
match field {
"name" => agent.name = Some("My Claude".into()),
"driver" => agent.driver = Driver::Acp,
"args" => agent.args.push("--verbose".into()),
"env" => {
agent.env.insert("K".into(), "v".into());
}
"unnamed" => agent.name = None,
_ => unreachable!(),
}
agent.write(&path).unwrap();
set_builtin_command(dir.path(), "claude", Some("/new/claude")).unwrap();
agent.command = "/new/claude".into();
assert_eq!(CustomAgent::read(&path).unwrap(), agent, "{field}");
set_builtin_command(dir.path(), "claude", None).unwrap();
agent.command = "claude".into();
assert_eq!(CustomAgent::read(&path).unwrap(), agent, "{field}");
}
}
#[test]
fn resetting_a_command_only_override_removes_the_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("codex.toml");
std::fs::write(
&path,
"name = \"Codex\"\ndriver = \"codex\"\ncommand = \"/custom/codex\"\nargs = [\"app-server\"]\n",
)
.unwrap();
set_builtin_command(dir.path(), "codex", None).unwrap();
assert!(!path.exists());
assert_eq!(
load(Some(dir.path())).into_iter().find(|s| s.id == "codex").unwrap(),
builtin_spec("codex").unwrap()
);
}
#[test]
fn agent_files_round_trip_with_their_registry_table() {
let dir = tempfile::tempdir().unwrap();
+70 -12
Переглянути файл
@@ -165,6 +165,13 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
.into_iter()
.filter_map(|v| serde_json::from_value::<Entry>(v).ok())
.filter(|e| safe_segment(&e.id) && safe_segment(&e.version))
.map(|mut e| {
e.id = canonical_id(&e.id).to_owned();
if let Some(name) = provider::builtin_name(&e.id) {
e.name = name.to_owned();
}
e
})
.collect())
}
@@ -232,11 +239,16 @@ fn choose<'a>(entry: &'a Entry, platform: Platform, on_path: &dyn Fn(&str) -> bo
None
}
/// Registry agents that are built-in ones under another id.
const BUILTIN_ALIASES: &[&str] = &["github-copilot-cli", "qwen-code", "mistral-vibe"];
/// Registry ids that map to a shorter built-in provider id (`<config>/agents/<id>.toml`).
const BUILTIN_ALIASES: &[(&str, &str)] =
&[("github-copilot-cli", "copilot"), ("qwen-code", "qwen"), ("mistral-vibe", "vibe")];
fn canonical_id(id: &str) -> &str {
BUILTIN_ALIASES.iter().find_map(|&(alias, canonical)| (alias == id).then_some(canonical)).unwrap_or(id)
}
fn is_builtin(id: &str) -> bool {
provider::is_builtin(id) || BUILTIN_ALIASES.contains(&id)
provider::is_builtin(canonical_id(id))
}
fn on_path(command: &str) -> bool {
@@ -387,6 +399,7 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
/// Installs (or updates to) the registry's current version of `id`, streaming progress
/// through `emit`, and points the agent file at it.
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
let id = canonical_id(id);
// The saved index is what the user picked from; fetch only when there is none.
let text = match fs::read_to_string(&paths.cache_file) {
Ok(text) => text,
@@ -618,6 +631,7 @@ fn install_uv(
/// Deletes a registry agent's file and installed files.
pub fn remove(paths: &RegistryPaths, id: &str) -> IdeResult<()> {
let id = canonical_id(id);
if !safe_segment(id) {
return Err(IdeError::invalid(format!("invalid agent id {id}")));
}
@@ -812,15 +826,7 @@ mod tests {
let mut providers: Vec<AgentProvider> = provider::load(Some(&p.agents_dir))
.into_iter()
.filter(|s| s.id == "amp-acp")
.map(|s| AgentProvider {
id: s.id,
name: s.name,
command: s.command,
installed: false,
config: vec![],
commands: vec![],
source: s.source,
})
.map(|s| provider::describe(&s))
.collect();
mark_updates(&p, &mut providers);
assert_eq!(
@@ -946,4 +952,56 @@ mod tests {
assert!(remove(&p, "amp-acp").is_err());
assert!(p.agent_file("amp-acp").exists());
}
#[test]
fn maps_github_copilot_cli_to_builtin_copilot_and_tracks_updates() {
let dir = tempfile::tempdir().unwrap();
let p = paths(dir.path());
let index = r#"{"agents":[
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.105",
"description":"GitHub's AI pair programmer",
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
]}"#;
let entries = parse(index).unwrap();
assert_eq!(entries.len(), 1);
assert_eq!((entries[0].id.as_str(), entries[0].name.as_str()), ("copilot", "GitHub Copilot"));
let shown = visible(&p, &entries, MAC_ARM, &|c| c == "npm" || c == "node");
assert_eq!(shown.len(), 1);
assert_eq!(
(shown[0].id.as_str(), shown[0].name.as_str(), shown[0].installed.as_deref()),
("copilot", "GitHub Copilot", None)
);
CustomAgent {
name: Some("GitHub Copilot".into()),
driver: Driver::Acp,
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
args: vec!["--acp".into()],
env: BTreeMap::new(),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.104".into() }),
}
.write(&p.agent_file("copilot"))
.unwrap();
let shown = visible(&p, &entries, MAC_ARM, &|c| c == "npm" || c == "node");
assert_eq!((shown[0].installed.as_deref(), shown[0].update), (Some("1.0.104"), true));
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
let spec = provider::load(Some(&p.agents_dir)).into_iter().find(|s| s.id == "copilot").unwrap();
assert_eq!(spec.name, "GitHub Copilot");
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
let mut providers = vec![provider::describe(&spec)];
mark_updates(&p, &mut providers);
assert_eq!(
providers[0].source,
AgentSource::Registry { version: "1.0.104".into(), update: Some("1.0.105".into()) }
);
remove(&p, "github-copilot-cli").unwrap();
let fallback = provider::load(Some(&p.agents_dir)).into_iter().find(|s| s.id == "copilot").unwrap();
assert_eq!(fallback.source, AgentSource::Builtin);
}
}
+75
Переглянути файл
@@ -942,3 +942,78 @@ async fn task_project_root_controls_local_and_worktree_repositories() {
}
assert_eq!(git(&["worktree", "list", "--porcelain"]).matches("worktree ").count(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn reload_providers_updates_registry_install_clears_stale_probes_and_notifies_subscribers() {
let tmp = tempfile::tempdir().unwrap();
let agents_dir = tmp.path().join("agents");
std::fs::create_dir_all(&agents_dir).unwrap();
let fake_bin = tmp.path().join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
std::fs::write(&fake_bin, "").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake_bin, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let agent = Arc::new(FakeAgent::default());
let connector: Connector = {
let agent = agent.clone();
Arc::new(move |_spec, _cwd, client, _stderr| {
let (a, b) = duplex(1 << 20);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let server = Peer::connect_framed(br, bw, agent.clone(), Framing::Lines);
agent.servers.lock().push(server);
Ok(Peer::connect_framed(ar, aw, client, Framing::Lines))
})
};
let mgr = AgentManager::with_connector(
AgentPaths {
project_root: tmp.path().to_path_buf(),
store_dir: tmp.path().join("store"),
worktrees_dir: tmp.path().join("worktrees"),
models_file: tmp.path().join("models.json"),
custom_agents_dir: Some(agents_dir.clone()),
home_dir: None,
},
tokio::runtime::Handle::current(),
connector,
);
// Seed a stale failed probe for copilot before installing its custom TOML.
mgr.shared.probes.lock().insert(
"copilot".into(),
AgentProbe {
provider: "copilot".into(),
name: None,
version: None,
protocol: "ACP".into(),
capabilities: AgentCapabilities::default(),
auth_methods: Vec::new(),
error: Some("copilot --acp was not found on PATH.".into()),
},
);
let events = Arc::new(Mutex::new(Vec::new()));
let events_sink = events.clone();
mgr.subscribe(Arc::new(move |ev| events_sink.lock().push(ev)));
let toml = format!(
"name = \"GitHub Copilot\"\ncommand = {:?}\nargs = [\"--acp\", \"--stdio\"]\n",
fake_bin.to_string_lossy()
);
std::fs::write(agents_dir.join("copilot.toml"), toml).unwrap();
mgr.reload_providers();
assert!(events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)));
assert!(!mgr.shared.probes.lock().contains_key("copilot"));
let copilot = mgr.providers().into_iter().find(|p| p.id == "copilot").unwrap();
assert!(copilot.installed);
assert!(copilot.command.contains(&*fake_bin.to_string_lossy()));
let probe = mgr.probe("copilot", false).await.unwrap();
assert!(probe.error.is_none());
}
+51 -4
Переглянути файл
@@ -48,8 +48,24 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
Ok(Created { path, branch, base, base_commit })
}
pub(crate) fn remove(project_root: &Path, path: &Path) -> IdeResult<()> {
repo_at(project_root)?.remove_worktree(path, true)
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
/// worktree (a pruned registration, a moved repository, a deleted `.git` file)
/// it fails with "is not a working tree". A folder under `worktrees_dir` is still
/// ours, so it is removed directly to keep the task deletable (a stale
/// registration prunes later); anything else keeps git's error.
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
let repo = repo_at(project_root)?;
let err = match repo.remove_worktree(path, true) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if !path.exists() {
return Ok(());
}
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
return Err(err);
}
std::fs::remove_dir_all(path).map_err(|e| IdeError::internal(e.to_string()))
}
/// Files under `cwd` that differ from `base` (untracked files included), with line counts.
@@ -153,7 +169,7 @@ mod tests {
assert!(snapshot(&dir).unwrap().is_empty());
assert_eq!(file_at(&dir, &dir.join("a.txt"), "HEAD").unwrap(), None);
assert!(create(&dir, &tmp.path().join("wt"), "Edit A", None).is_err());
assert!(remove(&dir, &dir).is_err());
assert!(remove(&dir, tmp.path(), &dir).is_err());
}
fn git(dir: &Path, args: &[&str]) {
@@ -202,7 +218,38 @@ mod tests {
// A second task with the same title gets its own worktree.
assert_eq!(create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap().branch, "agent/edit-a-2");
remove(&repo, &created.path).unwrap();
remove(&repo, &tmp.path().join("wt"), &created.path).unwrap();
assert!(!created.path.exists());
}
#[test]
fn a_broken_worktree_registration_still_leaves_a_deletable_folder() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
// A pruned registration (the repository moved, `git worktree prune` ran).
let created = create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap();
let registration = repo.join(".git/worktrees").join(created.path.file_name().unwrap());
std::fs::remove_dir_all(registration).unwrap();
remove(&repo, &tmp.path().join("wt"), &created.path).unwrap();
assert!(!created.path.exists());
// A deleted `.git` file in the worktree itself.
let created = create(&repo, &tmp.path().join("wt"), "Edit B", None).unwrap();
std::fs::remove_file(created.path.join(".git")).unwrap();
remove(&repo, &tmp.path().join("wt"), &created.path).unwrap();
assert!(!created.path.exists());
// A folder outside the worktrees directory is never deleted by hand.
let elsewhere = tmp.path().join("elsewhere");
std::fs::create_dir(&elsewhere).unwrap();
std::fs::write(elsewhere.join("keep.txt"), "x\n").unwrap();
assert!(remove(&repo, &tmp.path().join("wt"), &elsewhere).is_err());
assert!(elsewhere.join("keep.txt").exists());
}
}
+31 -4
Переглянути файл
@@ -158,8 +158,11 @@ fn detect_dir(dir: &Path, model: &BuildModel, root: &Path) -> Option<BuildSystem
}
/// `root/rel`, without a trailing separator for the root itself.
/// `root` / `rel`, joined per `/`-separated component: on Windows a single join of
/// `a/b` keeps the `/`, and such a path does not compare equal to the same directory
/// as other tools (JDT LS) spell it.
fn subdir(root: &Path, rel: &str) -> PathBuf {
if rel.is_empty() { root.to_path_buf() } else { root.join(rel) }
rel.split('/').filter(|part| !part.is_empty()).fold(root.to_path_buf(), |path, part| path.join(part))
}
fn rel_str(root: &Path, dir: &Path) -> String {
@@ -737,11 +740,11 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
.iter()
.flat_map(|s| {
["classes/kotlin", "classes/groovy", "classes/scala", "classes/java", "resources"]
.map(|d| module.join("build").join(d).join(s))
.map(|d| subdir(module, &format!("build/{d}/{s}")))
})
.collect(),
BuildSystem::Maven if test => vec![module.join("target/test-classes"), module.join("target/classes")],
BuildSystem::Maven => vec![module.join("target/classes")],
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
BuildSystem::Maven => vec![subdir(module, "target/classes")],
_ => Vec::new(),
};
dirs.into_iter().filter(|d| d.is_dir()).collect()
@@ -751,6 +754,30 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
mod tests {
use super::*;
/// Launch outputs use the platform separator throughout, so they compare equal to
/// the same directories as JDT LS reports them.
#[test]
fn launch_dirs_use_one_separator() {
let root = tempfile::tempdir().unwrap();
let module = subdir(root.path(), "parent/app");
for dir in ["target/classes", "target/test-classes", "build/classes/java/main", "build/resources/test"] {
std::fs::create_dir_all(subdir(&module, dir)).unwrap();
}
let foreign = if std::path::MAIN_SEPARATOR == '\\' { '/' } else { '\\' };
let dirs = [
launch_class_dirs(BuildSystem::Maven, &module, true),
launch_class_dirs(BuildSystem::Gradle, &module, true),
]
.concat();
assert_eq!(dirs.len(), 4, "{dirs:?}");
for dir in &dirs {
let suffix = dir.strip_prefix(root.path()).unwrap().to_string_lossy().into_owned();
assert!(!suffix.contains(foreign), "{suffix}");
}
assert_eq!(subdir(root.path(), ""), root.path());
assert_eq!(subdir(root.path(), "a//b/"), root.path().join("a").join("b"));
}
fn write(root: &Path, rel: &str, text: &str) {
let p = root.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
+1 -1
Переглянути файл
@@ -18,7 +18,7 @@ mod xml;
pub use gradle::{GradleModel, GradleProject, GradleTask};
pub use maven::{MavenDependency, MavenModel, MavenPlugin, MavenProfile, MavenProject, Omission};
pub use sync::{SyncOptions, SyncProgress, sync_gradle, sync_maven};
pub use sync::{SyncOptions, SyncProgress, maven_profiles, save_maven_profiles, sync_gradle, sync_maven};
use serde::{Deserialize, Serialize};
use specta::Type;
+36 -4
Переглянути файл
@@ -966,13 +966,19 @@ fn rel_path(root: &Path, p: &Path) -> String {
}
/// The POMs that are not modules of another one: the root `pom.xml`, else the
/// shallowest `pom.xml` of each branch (a folder holding several builds).
/// shallowest `pom.xml` of each branch (a folder holding several builds). An
/// 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 };
@@ -986,9 +992,16 @@ fn top_level_poms(root: &Path) -> Vec<PathBuf> {
}
dirs.sort();
for d in dirs.into_iter().rev() {
if d.join("pom.xml").is_file() {
out.push(d.join("pom.xml"));
} else if depth + 1 < POM_SEARCH_DEPTH {
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));
}
}
@@ -1706,6 +1719,25 @@ mod tests {
assert!(!is_maven_project(&root.join("c")));
}
#[test]
fn aggregate_pom_in_src_is_a_build() {
// Issue #1001: `src/pom.xml` aggregating modules under `src/` is recognized,
// with its modules loaded — while `src` stays unsearched otherwise.
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(
root,
"src/pom.xml",
"<project><groupId>g</groupId><artifactId>parent</artifactId><packaging>pom</packaging>\
<modules><module>app</module></modules></project>",
);
write(root, "src/app/pom.xml", "<project><groupId>g</groupId><artifactId>app</artifactId></project>");
let model = load_with_repo(root, None);
let names: Vec<&str> = model.projects.iter().map(|p| p.artifact_id.as_str()).collect();
assert_eq!(names, ["parent", "app"]);
assert!(is_maven_project(root));
}
#[test]
fn property_interpolation() {
let props: HashMap<String, String> =
+18
Переглянути файл
@@ -88,6 +88,24 @@ fn maven_sync_goals(effective: &Path, offline: bool) -> Vec<String> {
]
}
const GRADLE_CACHE: &str = "gradle.json";
const MAVEN_PROFILES: &str = "maven-profiles.json";
/// The Maven profiles (`-P` entries, `!id` deactivates) the project was last synced
/// with: what the IDE resolves it with besides `mvn` (the Java language server, Build Project).
pub fn maven_profiles(cache_dir: &Path) -> Vec<String> {
read_cache(cache_dir, MAVEN_PROFILES).unwrap_or_default()
}
/// Records the profiles of a sync for [`maven_profiles`]; `true` when they changed.
pub fn save_maven_profiles(cache_dir: &Path, profiles: &[String]) -> IdeResult<bool> {
if maven_profiles(cache_dir) == profiles {
return Ok(false);
}
std::fs::create_dir_all(cache_dir)?;
let json = serde_json::to_vec(profiles).map_err(|e| IdeError::internal(e.to_string()))?;
std::fs::write(cache_dir.join(MAVEN_PROFILES), json)?;
Ok(true)
}
fn read_cache<T: DeserializeOwned>(dir: &Path, name: &str) -> Option<T> {
serde_json::from_slice(&std::fs::read(dir.join(name)).ok()?).ok()
+8
Переглянути файл
@@ -548,6 +548,7 @@ pub struct LanguagesSettings {
pub typescript: TypeScriptSettings,
pub prettier: PrettierSettings,
pub java: JavaSettings,
pub ruby: RubySettings,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -605,6 +606,13 @@ impl Default for PythonSettings {
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct RubySettings {
/// Project interpreter executable; empty = auto-detect (`.ruby-version`, mise / asdf, else `ruby` on PATH).
pub interpreter: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct NodeSettings {
+2
Переглянути файл
@@ -18,6 +18,7 @@ pub enum Tool {
Go,
Maven,
Gradle,
Ruby,
}
impl Tool {
@@ -30,6 +31,7 @@ impl Tool {
Tool::Go => &["go", "golang"],
Tool::Maven => &["maven"],
Tool::Gradle => &["gradle"],
Tool::Ruby => &["ruby"],
}
}
}
+18 -2
Переглянути файл
@@ -23,6 +23,13 @@ pub fn providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
Ok(providers)
}
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
pub fn set_command(host: &Host, window: &str, id: String, command: Option<String>) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.set_builtin_command(&id, command)
}
/// Where ACP Registry agents are saved (`<config>/agents`, like the user's own) and installed.
pub(crate) fn registry_paths(host: &Host) -> RegistryPaths {
RegistryPaths::new(&host.config_dir, &host.local_data_dir)
@@ -63,13 +70,21 @@ pub async fn registry_install(
.await
.map_err(join_err);
host.end_request(request);
result?
result??;
for project in host.projects() {
project.agents.reload_providers();
}
Ok(())
}
/// Removes a registry agent: its agent file and installed files.
pub async fn registry_remove(host: &Host, _window: &str, id: String) -> IdeResult<()> {
let paths = registry_paths(host);
tokio::task::spawn_blocking(move || ide_agent::registry::remove(&paths, &id)).await.map_err(join_err)?
tokio::task::spawn_blocking(move || ide_agent::registry::remove(&paths, &id)).await.map_err(join_err)??;
for project in host.projects() {
project.agents.reload_providers();
}
Ok(())
}
/// Slash commands to complete for `provider` in `task`'s directory, or in the project
@@ -179,6 +194,7 @@ pub async fn base_text(host: &Host, window: &str, task: String, path: IpcPath) -
pub(crate) fn register(d: &mut Dispatcher) {
d.add("agent_subscribe", |c| async move { subscribe(&c.host, &c.window, c.channel("onEvent")?) });
d.add("agent_providers", |c| async move { providers(&c.host, &c.window) });
d.add("agent_set_command", |c| async move { set_command(&c.host, &c.window, c.arg("id")?, c.arg("command")?) });
d.add("agent_registry_list", |c| async move { registry_list(&c.host, &c.window, c.arg("request")?).await });
d.add("agent_registry_install", |c| async move {
registry_install(&c.host, &c.window, c.arg("id")?, c.arg("request")?, c.sender("onEvent")?).await
+25 -2
Переглянути файл
@@ -74,6 +74,18 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
model
}
/// `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 {
let profiles = ide_build::maven_profiles(cache);
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
for p in &mut m.projects {
p.options.push(format!("-P{}", profiles.join(",")));
}
}
model
}
/// Maven and Gradle projects of the window's project, from the build files plus the last sync.
pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
host.require_trust(window)?;
@@ -98,6 +110,12 @@ pub async fn build_sync(
let project = host.project(window)?;
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
let bridge_profiles = profiles.clone();
// What the Java language server and Build Project resolve the project with from now on.
let profiles_changed = tool == BuildTool::Maven
&& ide_build::save_maven_profiles(&cache, &profiles).unwrap_or_else(|e| {
tracing::warn!("Maven profiles not saved: {e}");
false
});
let token = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let current = load(&root, &cache, &settings);
@@ -152,6 +170,10 @@ pub async fn build_sync(
let lsp = project.lsp.clone();
let uris = build_files.iter().map(|f| ide_lsp::path_to_uri_string(&project.root.join(f))).collect();
tokio::spawn(async move {
if profiles_changed {
// jdtls takes the profiles from its Maven settings (see `ide_sdk::maven_profiles`).
lsp.reconfigure().await;
}
if let Err(e) = lsp.java_update_project_configs(&project.root, uris).await {
tracing::debug!("java/projectConfigurationsUpdate: {e}");
}
@@ -257,7 +279,8 @@ pub async fn build_run(
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache = cache.join(crate::project::project_key(member));
let plan = compile::plan(member, &load(member, &member_cache, &settings), kind, file.as_deref())?;
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
let plan = compile::plan(member, &model, kind, file.as_deref())?;
match &mut combined {
Some(combined) => combined.steps.extend(plan.steps),
None => combined = Some(plan),
@@ -267,7 +290,7 @@ pub async fn build_run(
plan.title = workspace.name;
plan
} else {
compile::plan(&root, &load(&root, &cache, &settings), kind, file.as_deref())?
compile::plan(&root, &with_profiles(load(&root, &cache, &settings), &cache), kind, file.as_deref())?
};
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
+1 -1
Переглянути файл
@@ -91,7 +91,7 @@ mod tests {
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
+31 -25
Переглянути файл
@@ -56,14 +56,16 @@ pub async fn copy_merge(
if overwrite {
project.history.record_deletion(&to, DELETE_SNAPSHOT_LIMIT);
}
ide_vfs::copy_merge(
&from,
&to,
overwrite,
Some(&project.root),
&project.exclude_globs(),
(&source_root, &destination_root),
)
project.with_disk_sync(|| {
ide_vfs::copy_merge(
&from,
&to,
overwrite,
Some(&project.root),
&project.exclude_globs(),
(&source_root, &destination_root),
)
})
})
.await
}
@@ -71,24 +73,28 @@ pub async fn copy_merge(
/// Files of a deleted folder snapshotted in Local History.
const DELETE_SNAPSHOT_LIMIT: usize = 2000;
pub fn read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<FileEntry>> {
let excludes = host
.project(window)
.map(|p| {
let globs = p.exclude_globs();
// `read_dir` matches relative to the enclosing repository: re-anchor
// project-root patterns (`/build`) when the project is a repo subfolder.
let repo = p.root.ancestors().find(|d| d.join(".git").exists());
match repo.and_then(|r| p.root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
Some(rel) => {
let rel = rel.to_string_lossy().replace('\\', "/");
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
/// Runs on the blocking pool: on a network share (`\\wsl.localhost`) every stat is slow.
pub async fn read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<FileEntry>> {
let project = host.project(window);
host.blocking(move || {
let excludes = project
.map(|p| {
let globs = p.exclude_globs();
// `read_dir` matches relative to the enclosing repository: re-anchor
// project-root patterns (`/build`) when the project is a repo subfolder.
let repo = p.root.ancestors().find(|d| d.join(".git").exists());
match repo.and_then(|r| p.root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
Some(rel) => {
let rel = rel.to_string_lossy().replace('\\', "/");
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
}
None => globs,
}
None => globs,
}
})
.unwrap_or_default();
ide_vfs::read_dir(&path, &excludes)
})
.unwrap_or_default();
ide_vfs::read_dir(&path, &excludes)
})
.await
}
/// Creates an empty file; inside a project, honours the EditorConfig
+66 -4
Переглянути файл
@@ -59,7 +59,7 @@ async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
};
let external_build = if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
let mut info = project.lsp.java_launch(&module, test, build && !delegated, cancel).await?;
let mut info = project.lsp.java_launch(&module, test, build && !delegated, delegated, cancel).await?;
let lsp_ms = started.elapsed().as_millis();
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
@@ -86,7 +86,7 @@ async fn resolve_launch(
};
let mut class_paths: Vec<String> = built.iter().map(|p| p.to_string_lossy().into_owned()).collect();
for p in std::mem::take(&mut info.class_paths) {
if !class_paths.contains(&p) {
if !class_paths.iter().any(|c| same_entry(c, &p, cfg!(windows))) {
class_paths.push(p);
}
}
@@ -131,15 +131,44 @@ async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// A classpath entry as a comparable key. Entries come from JDT LS and from our own
/// build model, which spell one directory differently on Windows (`\\?\` prefix,
/// `/` or `\\`, drive-letter case); compared as text, a module output stayed on the
/// classpath next to its launch snapshot and every resource was found twice.
fn entry_key(path: &str, windows: bool) -> String {
let path = match path.strip_prefix(r"\\?\UNC\") {
Some(share) => format!(r"\\{share}"),
None => path.strip_prefix(r"\\?\").unwrap_or(path).to_owned(),
};
let mut key = if windows { path.replace('\\', "/") } else { path };
while key.len() > 1 && key.ends_with('/') {
key.pop();
}
if windows { key.to_lowercase() } else { key }
}
fn same_entry(a: &str, b: &str, windows: bool) -> bool {
a == b || entry_key(a, windows) == entry_key(b, windows)
}
fn use_snapshot(info: &mut JavaLaunchInfo, built: &[PathBuf], snapshot: &std::path::Path) -> Vec<PathBuf> {
use_snapshot_on(info, built, snapshot, cfg!(windows))
}
fn use_snapshot_on(
info: &mut JavaLaunchInfo,
built: &[PathBuf],
snapshot: &std::path::Path,
windows: bool,
) -> Vec<PathBuf> {
let mut copies = Vec::new();
for (index, source) in built.iter().enumerate() {
let dest = snapshot.join(index.to_string());
let original = source.to_string_lossy();
info.class_paths.retain(|p| p != original.as_ref());
info.class_paths.retain(|p| !same_entry(p, &original, windows));
let mut modular = false;
for path in &mut info.module_paths {
if path == original.as_ref() {
if same_entry(path, &original, windows) {
*path = dest.to_string_lossy().into_owned();
modular = true;
}
@@ -185,6 +214,39 @@ pub(crate) fn register(d: &mut Dispatcher) {
mod tests {
use super::*;
/// JDT LS and our build model spell a module output differently on Windows; the
/// snapshot must still replace it, or resources (MyBatis mapper XML) load twice.
#[test]
fn snapshots_replace_outputs_however_windows_spells_them() {
let built = PathBuf::from(r"D:\workspace\arm\arm-web\target/classes");
let jdtls = [
r"D:\workspace\arm\arm-web\target\classes",
r"d:\workspace\arm\arm-web\target\classes",
r"D:/workspace/arm/arm-web/target/classes/",
r"\\?\D:\workspace\arm\arm-web\target\classes",
];
for spelled in jdtls {
let mut info = JavaLaunchInfo {
class_paths: vec![spelled.into(), r"D:\m2\mybatis.jar".into()],
module_paths: vec![spelled.into()],
..Default::default()
};
use_snapshot_on(&mut info, std::slice::from_ref(&built), std::path::Path::new(r"C:\cache\launch-x"), true);
assert_eq!(info.class_paths, [r"D:\m2\mybatis.jar"], "{spelled}");
assert_eq!(
info.module_paths,
[std::path::Path::new(r"C:\cache\launch-x").join("0").to_string_lossy()],
"{spelled}"
);
}
assert!(same_entry(r"\\?\UNC\server\share\app\target\classes", r"\\server\share\app\target/classes", true));
// Different directories stay different, and other platforms keep case and `\`.
assert!(!same_entry(r"D:\a\target\classes", r"D:\a\target\test-classes", true));
assert!(!same_entry("/work/App/target/classes", "/work/app/target/classes", false));
assert!(!same_entry(r"/work/a\b", "/work/a/b", false));
assert!(same_entry("/work/app/target/classes/", "/work/app/target/classes", false));
}
#[test]
fn launch_snapshots_survive_jdt_overwrites_and_replace_module_outputs() {
let root = tempfile::tempdir().unwrap();
+12 -1
Переглянути файл
@@ -62,13 +62,24 @@ fn detected_and_saved(
all
}
/// 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(
host: &Host,
window: &str,
configs: &[RunConfig],
removed_detected_ids: &[String],
) -> IdeResult<()> {
ide_run::save_user_configs_with_removals(&host.project(window)?.root, configs, removed_detected_ids)
let project = host.project(window)?;
let settings = project.settings.effective();
let configs: Vec<RunConfig> = configs
.iter()
.map(|c| match c.kind.as_str() {
"gradle" => c.clone(),
_ => ide_sdk::apply::without_derived(c, &project.root, &settings),
})
.collect();
ide_run::save_user_configs_with_removals(&project.root, &configs, removed_detected_ids)
}
pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit<OutputChunk>) -> IdeResult<RunInfo> {
+340 -27
Переглянути файл
@@ -1,6 +1,61 @@
use ide_core::{IdeError, IdeResult};
use std::path::Path;
const LIFETIME: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
const DIRECTORY: &str = "terminal-images";
fn extension(mime: &str) -> IdeResult<&str> {
match mime {
"image/png" => Ok("png"),
"image/jpeg" => Ok("jpg"),
"image/gif" => Ok("gif"),
"image/webp" => Ok("webp"),
"image/bmp" => Ok("bmp"),
"image/svg+xml" => Ok("svg"),
"image/tiff" => Ok("tiff"),
"image/x-icon" => Ok("ico"),
"audio/wav" | "audio/x-wav" => Ok("wav"),
"audio/mpeg" => Ok("mp3"),
"audio/mp4" => Ok("m4a"),
"audio/ogg" => Ok("ogg"),
"audio/webm" | "video/webm" => Ok("webm"),
"audio/flac" => Ok("flac"),
"audio/aac" => Ok("aac"),
"video/mp4" => Ok("mp4"),
"video/ogg" => Ok("ogv"),
"video/quicktime" => Ok("mov"),
_ => Err(IdeError::invalid("unsupported clipboard media type")),
}
}
fn owned_name(name: &str) -> bool {
let name = name.strip_prefix(".partial-").unwrap_or(name);
let Some((id, ext)) = name.strip_prefix("image-").and_then(|s| s.split_once('.')) else { return false };
id.len() == 32
&& id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
&& matches!(
ext,
"png"
| "jpg"
| "gif"
| "webp"
| "bmp"
| "svg"
| "tiff"
| "ico"
| "wav"
| "mp3"
| "m4a"
| "ogg"
| "webm"
| "flac"
| "aac"
| "mp4"
| "ogv"
| "mov"
)
}
#[cfg(unix)]
mod unix {
use super::*;
@@ -8,24 +63,7 @@ mod unix {
use std::fs::File;
use std::io::{self, Write};
use std::os::unix::fs::MetadataExt;
use std::time::{Duration, SystemTime};
const LIFETIME: Duration = Duration::from_secs(24 * 60 * 60);
const DIRECTORY: &str = "terminal-images";
fn extension(mime: &str) -> IdeResult<&str> {
match mime {
"image/png" => Ok("png"),
"image/jpeg" => Ok("jpg"),
"image/gif" => Ok("gif"),
"image/webp" => Ok("webp"),
"image/bmp" => Ok("bmp"),
"image/svg+xml" => Ok("svg"),
"image/tiff" => Ok("tiff"),
"image/x-icon" => Ok("ico"),
_ => Err(IdeError::invalid("unsupported image type")),
}
}
use std::time::SystemTime;
fn open_directory(data_dir: &Path) -> io::Result<File> {
if !data_dir.is_absolute() {
@@ -55,14 +93,6 @@ mod unix {
Ok(dir)
}
fn owned_name(name: &str) -> bool {
let name = name.strip_prefix(".partial-").unwrap_or(name);
let Some((id, ext)) = name.strip_prefix("image-").and_then(|s| s.split_once('.')) else { return false };
id.len() == 32
&& id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
&& matches!(ext, "png" | "jpg" | "gif" | "webp" | "bmp" | "svg" | "tiff" | "ico")
}
fn cleanup(dir: &File, now: SystemTime) -> io::Result<()> {
for entry in Dir::read_from(dir)? {
let entry = entry?;
@@ -140,6 +170,7 @@ mod unix {
use super::*;
use std::fs;
use std::os::unix::fs::{PermissionsExt, symlink};
use std::time::Duration;
#[test]
fn stores_bytes_with_private_modes_and_unpredictable_names() {
@@ -211,10 +242,292 @@ mod unix {
}
}
#[cfg(windows)]
mod windows {
use super::*;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
use std::time::SystemTime;
use windows_sys::Win32::Storage::FileSystem::{
FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
FILE_SHARE_WRITE,
};
fn open_directory(path: &Path) -> io::Result<File> {
if !path.is_absolute() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "data directory must be absolute"));
}
let dir = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
let meta = dir.metadata()?;
if !meta.is_dir() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"terminal media directory must not be a reparse point",
));
}
Ok(dir)
}
fn cleanup(path: &Path, now: SystemTime) -> io::Result<()> {
for entry in fs::read_dir(path)? {
let entry = entry?;
if !entry.file_name().to_str().is_some_and(owned_name) {
continue;
}
let file = match OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(entry.path())
{
Ok(file) => file,
Err(_) => continue,
};
let meta = file.metadata()?;
if meta.is_file()
&& meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& meta
.modified()
.ok()
.and_then(|time| now.duration_since(time).ok())
.is_some_and(|age| age >= LIFETIME)
{
match fs::remove_file(entry.path()) {
Ok(()) => (),
Err(error) if error.kind() == io::ErrorKind::NotFound => (),
Err(error) => return Err(error),
}
}
}
Ok(())
}
fn store_with(
data_dir: &Path,
data: &[u8],
mime: &str,
now: SystemTime,
write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>,
) -> IdeResult<String> {
let ext = extension(mime)?;
let _parent = open_directory(data_dir)?;
let path = data_dir.join(DIRECTORY);
match fs::create_dir(&path) {
Ok(()) => (),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => (),
Err(error) => return Err(error.into()),
}
let _dir = open_directory(&path)?;
cleanup(&path, now)?;
let name = format!("image-{}.{}", uuid::Uuid::new_v4().simple(), ext);
let target = path.join(&name);
let temporary = path.join(format!(".partial-{name}"));
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
let result = write(&mut file, data);
drop(file);
if let Err(error) = result {
let _ = fs::remove_file(&temporary);
return Err(error.into());
}
if let Err(error) = fs::hard_link(&temporary, &target) {
let _ = fs::remove_file(&temporary);
return Err(error.into());
}
let _ = fs::remove_file(&temporary);
Ok(target.to_string_lossy().into_owned())
}
pub(in crate::ops::term) fn store(data_dir: &Path, data: &[u8], mime: &str) -> IdeResult<String> {
store_with(data_dir, data, mime, SystemTime::now(), |file, bytes| file.write_all(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
fn junction(path: &Path, target: &Path) {
let output = std::process::Command::new("powershell.exe")
.args([
"-NoProfile",
"-NonInteractive",
"-Command",
"New-Item -ItemType Junction -Path $env:OPENIDEA_TEST_JUNCTION -Target $env:OPENIDEA_TEST_TARGET -ErrorAction Stop | Out-Null",
])
.env("OPENIDEA_TEST_JUNCTION", path)
.env("OPENIDEA_TEST_TARGET", target)
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
}
#[test]
fn rejects_reparse_data_and_storage_directories() {
let root = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let link = root.path().join("data");
junction(&link, outside.path());
assert!(store(&link, b"x", "image/png").is_err());
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 0);
fs::remove_dir(&link).unwrap();
let link = root.path().join(DIRECTORY);
junction(&link, outside.path());
assert!(store(root.path(), b"x", "image/png").is_err());
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 0);
fs::remove_dir(&link).unwrap();
}
#[test]
fn expiry_only_removes_owned_regular_media_at_boundary() {
let root = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let path = root.path().join(DIRECTORY);
fs::create_dir(&path).unwrap();
let _dir = open_directory(&path).unwrap();
let now = SystemTime::now();
let names = [
"image-00000000000000000000000000000001.png",
"image-00000000000000000000000000000002.mp3",
".partial-image-00000000000000000000000000000003.mp4",
"image-00000000000000000000000000000004.webm",
"image-00000000000000000000000000000005.wav",
"unrelated.png",
"image-00000000000000000000000000000006.exe",
];
for (name, time) in names.iter().zip([
now - LIFETIME,
now - LIFETIME,
now - LIFETIME,
now - LIFETIME + Duration::from_secs(1),
now + Duration::from_secs(1),
now - LIFETIME,
now - LIFETIME,
]) {
let file = File::create(path.join(name)).unwrap();
file.set_times(fs::FileTimes::new().set_modified(time)).unwrap();
}
let link = path.join("image-00000000000000000000000000000007.png");
junction(&link, outside.path());
let directory = path.join("image-00000000000000000000000000000008.png");
fs::create_dir(&directory).unwrap();
cleanup(&path, now).unwrap();
for name in &names[..3] {
assert!(!path.join(name).exists());
}
for name in &names[3..] {
assert!(path.join(name).exists());
}
assert!(directory.is_dir());
assert!(fs::symlink_metadata(&link).unwrap().file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0);
fs::remove_dir(link).unwrap();
}
#[test]
fn failed_write_removes_partial_file() {
let root = tempfile::tempdir().unwrap();
let result = store_with(root.path(), b"partial", "audio/ogg", SystemTime::now(), |file, bytes| {
file.write_all(bytes)?;
Err(io::Error::other("simulated failure"))
});
assert!(result.is_err());
assert_eq!(fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), 0);
}
#[test]
fn publication_preserves_existing_target() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join(DIRECTORY);
let result = store_with(root.path(), b"new", "video/mp4", SystemTime::now(), |file, bytes| {
file.write_all(bytes)?;
let temporary = fs::read_dir(&path)?.next().unwrap()?.file_name();
let target = temporary.to_str().unwrap().strip_prefix(".partial-").unwrap();
fs::write(path.join(target), b"existing")
});
assert!(result.is_err());
let files: Vec<_> = fs::read_dir(&path).unwrap().map(|entry| entry.unwrap().path()).collect();
assert_eq!(files.len(), 1);
assert_eq!(fs::read(&files[0]).unwrap(), b"existing");
assert!(!files[0].file_name().unwrap().to_str().unwrap().starts_with(".partial-"));
}
#[test]
fn storage_handles_prevent_directory_replacement() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join(DIRECTORY);
let result = store_with(root.path(), b"x", "image/png", SystemTime::now(), |file, bytes| {
assert!(fs::rename(&path, root.path().join("replaced")).is_err());
file.write_all(bytes)
});
assert_eq!(fs::read(result.unwrap()).unwrap(), b"x");
}
}
}
#[cfg(unix)]
pub(super) use unix::store;
#[cfg(not(unix))]
#[cfg(windows)]
pub(super) use windows::store;
#[cfg(not(any(unix, windows)))]
pub(super) fn store(_data_dir: &Path, _data: &[u8], _mime: &str) -> IdeResult<String> {
Err(IdeError::internal("private terminal image storage is unsupported on this platform"))
}
#[cfg(all(test, any(unix, windows)))]
mod tests {
use super::*;
#[test]
fn stores_supported_media_with_expected_extensions_and_unique_names() {
let root = tempfile::tempdir().unwrap();
let types = [
("image/png", "png"),
("image/jpeg", "jpg"),
("image/gif", "gif"),
("image/webp", "webp"),
("image/bmp", "bmp"),
("image/svg+xml", "svg"),
("image/tiff", "tiff"),
("image/x-icon", "ico"),
("audio/wav", "wav"),
("audio/x-wav", "wav"),
("audio/mpeg", "mp3"),
("audio/mp4", "m4a"),
("audio/ogg", "ogg"),
("audio/webm", "webm"),
("audio/flac", "flac"),
("audio/aac", "aac"),
("video/mp4", "mp4"),
("video/webm", "webm"),
("video/ogg", "ogv"),
("video/quicktime", "mov"),
];
let mut paths = std::collections::HashSet::new();
for (mime, ext) in types {
let path = store(root.path(), mime.as_bytes(), mime).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), mime.as_bytes());
assert_eq!(Path::new(&path).extension().unwrap(), ext);
assert!(owned_name(Path::new(&path).file_name().unwrap().to_str().unwrap()));
assert!(paths.insert(path));
}
assert_eq!(std::fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), types.len());
}
#[test]
fn rejects_unsupported_mime_before_creating_storage() {
let root = tempfile::tempdir().unwrap();
for mime in ["text/plain", "application/octet-stream", "image/unknown", "audio/unknown", "video/unknown", ""] {
let error = store(root.path(), b"x", mime).unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput);
assert_eq!(error.message, "unsupported clipboard media type");
}
assert!(!root.path().join(DIRECTORY).exists());
}
#[test]
fn rejects_relative_data_directory() {
assert!(store(Path::new("relative-data"), b"x", "image/png").is_err());
}
}
+72 -28
Переглянути файл
@@ -123,18 +123,18 @@ fn per_repo(
Ok(())
}
/// Shelf and patches work in the primary repository only: changes of a nested one
/// fail instead of being left out silently.
fn in_primary_repo(project: &Project, paths: &[PathBuf]) -> IdeResult<()> {
/// A shelf is one patch for one owning repository. Validate the whole selection before reverting files.
fn shelf_repository(project: &Project, paths: &[PathBuf]) -> IdeResult<PathBuf> {
let repos = project.repos();
let primary = repos.primary().map(|r| r.root());
match paths.iter().find(|p| repos.for_path(p).map(|r| r.root()) != primary) {
Some(p) => Err(ide_core::IdeError::invalid(format!(
"{} is in another git repository; shelving and patches support the project's main repository only",
p.display()
))),
None => Ok(()),
let root = paths
.first()
.and_then(|p| repos.for_path(p))
.map(|r| r.root())
.ok_or_else(|| ide_core::IdeError::invalid("select files in a git repository to shelve"))?;
if paths.iter().any(|p| repos.for_path(p).map(|r| r.root()) != Some(root)) {
return Err(ide_core::IdeError::invalid("select files from a single git repository to shelve"));
}
Ok(root.to_path_buf())
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
@@ -281,7 +281,7 @@ pub async fn vcs_add_to_ignore(
}
}
apply_git_executable(&project.settings.effective());
let result = ide_vcs::add_to_ignore(&paths, destination);
let result = project.with_disk_sync(|| ide_vcs::add_to_ignore(&paths, destination));
// Exclude may live outside a worktree's watched directory. Refresh filters and UI explicitly.
project.watcher.reload_ignore_rules();
for (_, watcher) in project.content_watchers.lock().iter() {
@@ -322,7 +322,7 @@ pub async fn vcs_commit(
// Commit hooks may run for a long time.
let project = host.project(window)?;
blocking(move || {
project.with_repo_at(repo.as_deref(), |r| {
project.with_repo_recorded(repo.as_deref(), None, |r| {
r.commit_with(&message, &options, &|path| project.vcs_encoding(path, None))
})
})
@@ -729,7 +729,13 @@ pub async fn vcs_add_worktree(
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
project.with_repo_at(repo.as_deref(), |r| r.add_worktree(&path, &commitish, new_branch.as_deref()))
let result = project
.with_repo_recorded(repo.as_deref(), None, |r| r.add_worktree(&path, &commitish, new_branch.as_deref()));
// A worktree below the project is a new repository: rescan so its files
// join the status and gutter queries (the watcher picks the gitfile up
// too, but only as a debounced event later).
project.refresh_repositories();
result
})
.await
}
@@ -743,7 +749,12 @@ pub async fn vcs_remove_worktree(
) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force))).await
blocking(move || {
let result = project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force));
project.refresh_repositories();
result
})
.await
}
pub async fn vcs_compare_scope(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<CompareScope> {
@@ -846,7 +857,7 @@ pub async fn vcs_apply_patch(
) -> IdeResult<ApplyOutcome> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.apply_patch(&patch))).await
blocking(move || project.with_repo_recorded(repo.as_deref(), None, |r| r.apply_patch(&patch))).await
}
/// Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them.
@@ -854,16 +865,23 @@ pub async fn vcs_shelve(host: &Host, window: &str, name: String, paths: Vec<Path
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
in_primary_repo(&project, &paths)?;
let repo = shelf_repository(&project, &paths)?;
keep_private(&project.root);
project.with_repo_recorded(None, Some("Shelve"), |r| r.shelve(&shelf_dir(&project.root), &name, &paths))
project.with_repo_recorded(Some(&repo), Some("Shelve"), |r| r.shelve(&shelf_dir(&project.root), &name, &paths))
})
.await
}
pub fn vcs_shelves(host: &Host, window: &str) -> IdeResult<Vec<ShelvedChangeList>> {
let project = host.project(window)?;
ide_vcs::shelf::list(&shelf_dir(&project.root))
let mut shelves = ide_vcs::shelf::list(&shelf_dir(&project.root))?;
let primary = project.repos().primary().map(|r| ide_core::IpcPath::from(r.root().to_path_buf()));
for entry in &mut shelves {
if entry.repo.is_none() {
entry.repo = primary.clone();
}
}
Ok(shelves)
}
/// Unshelve: applies the shelved patch (3-way merging; conflicts are left for the
@@ -878,7 +896,8 @@ pub async fn vcs_unshelve(
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
project.with_repo_recorded(None, Some("Unshelve"), |r| {
let repo = ide_vcs::shelf::repository(&shelf_dir(&project.root), &id)?;
project.with_repo_recorded(repo.as_deref(), Some("Unshelve"), |r| {
ide_vcs::shelf::unshelve_path(r, &shelf_dir(&project.root), &id, remove, path.as_deref())
})
})
@@ -902,12 +921,30 @@ pub fn vcs_shelf_patch(host: &Host, window: &str, id: String, path: Option<Strin
pub async fn vcs_shelf_diff(host: &Host, window: &str, id: String) -> IdeResult<Vec<ide_vcs::shelf::ShelfDiffFile>> {
let project = host.project(window)?;
blocking(move || project.with_repo(|r| ide_vcs::shelf::diff_files(r, &shelf_dir(&project.root), &id))).await
blocking(move || {
let repo = ide_vcs::shelf::repository(&shelf_dir(&project.root), &id)?;
project.with_repo_at(repo.as_deref(), |r| ide_vcs::shelf::diff_files(r, &shelf_dir(&project.root), &id))
})
.await
}
pub async fn vcs_shelf_import(host: &Host, window: &str, name: String, patch: String) -> IdeResult<()> {
pub async fn vcs_shelf_import(
host: &Host,
window: &str,
repo: Option<PathBuf>,
name: String,
patch: String,
) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || ide_vcs::shelf::import_patch(&shelf_dir(&project.root), &name, &patch)).await
blocking(move || {
if repo.is_none() && project.repos().is_empty() {
return ide_vcs::shelf::import_patch(&shelf_dir(&project.root), &name, &patch, None);
}
project.with_repo_at(repo.as_deref(), |r| {
ide_vcs::shelf::import_patch(&shelf_dir(&project.root), &name, &patch, Some(r.root()))
})
})
.await
}
pub fn vcs_changelists_load(host: &Host, window: &str) -> IdeResult<ChangelistState> {
@@ -922,13 +959,20 @@ pub fn vcs_changelists_save(host: &Host, window: &str, changelists: ChangelistSt
}
/// Create Patch › Save to file.
pub async fn vcs_write_patch(_host: &Host, _window: &str, path: PathBuf, patch: String) -> IdeResult<()> {
pub async fn vcs_write_patch(host: &Host, window: &str, path: PathBuf, patch: String) -> IdeResult<()> {
let project = host.project(window).ok();
blocking(move || {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
let write = || {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(&path, patch)?;
Ok(())
};
match project {
Some(project) => project.with_disk_sync(write),
None => write(),
}
std::fs::write(&path, patch)?;
Ok(())
})
.await
}
@@ -1107,7 +1151,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_shelf_rename", |c| async move { vcs_shelf_rename(&c.host, &c.window, c.arg("id")?, c.arg("name")?) });
d.add("vcs_shelf_diff", |c| async move { vcs_shelf_diff(&c.host, &c.window, c.arg("id")?).await });
d.add("vcs_shelf_import", |c| async move {
vcs_shelf_import(&c.host, &c.window, c.arg("name")?, c.arg("patch")?).await
vcs_shelf_import(&c.host, &c.window, c.arg("repo")?, c.arg("name")?, c.arg("patch")?).await
});
d.add("vcs_shelf_patch", |c| async move { vcs_shelf_patch(&c.host, &c.window, c.arg("id")?, c.arg("path")?) });
d.add("vcs_changelists_load", |c| async move { vcs_changelists_load(&c.host, &c.window) });
+54 -10
Переглянути файл
@@ -129,6 +129,7 @@ impl Host {
let root = root.clone();
let data_dir = self.local_data_dir.clone();
let config_dir = self.config_dir.clone();
let build_cache = self.local_data_dir.join("cache").join(&project_key).join("build");
let sink = sink.clone();
let formatter_problem = std::sync::Mutex::new(None);
lsp.set_config_hook(Box::new(move |cfg, server_root| {
@@ -142,6 +143,15 @@ impl Host {
let root = member.as_ref().unwrap_or(&root);
ide_sdk::apply::server_launch_overrides(cfg, &effective);
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
if cfg.name == "jdtls" {
// A workspace member keeps its build model under its own key (Build Project).
let cache = match &member {
Some(member) => build_cache.join(crate::project::project_key(member)),
None => build_cache.clone(),
};
let profiles = ide_build::maven_profiles(&cache);
ide_sdk::maven_profiles::configure_jdtls(cfg, root, &effective, &profiles, &cache);
}
ide_sdk::java::cap_java_home(cfg, &ide_sdk::java::installed_jdks());
if cfg.name == "jdtls" {
let problem = ide_lsp::jdtls::configure_formatter(
@@ -325,15 +335,35 @@ impl Host {
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
}
}
// A repository was cloned / initialised / removed below the project: its
// `.git/HEAD` (the watcher reports nothing else of `.git`) appeared or went.
// A repository was cloned / initialised / removed below the project:
// its `.git/HEAD` appeared or went. A linked worktree's `.git` is a
// plain gitfile, and that file is the only marker written inside the
// worktree itself, so the `.git` path counts too.
let known = repos.read().roots();
let git_dirs = changed.iter().chain(&batch.removed).chain(&batch.vcs).any(|p| {
let Some(dir) = p.ends_with(".git/HEAD").then(|| p.parent().and_then(Path::parent)).flatten()
else {
return false;
let mut git_dirs = changed.iter().chain(&batch.removed).chain(&batch.vcs).any(|p| {
let dir = if p.ends_with(".git/HEAD") {
p.parent().and_then(Path::parent)
} else if p.ends_with(".git") {
p.parent()
} else {
None
};
known.iter().any(|r| r == dir) != p.is_file()
let Some(dir) = dir else { return false };
known.iter().any(|r| r == dir) != p.exists()
});
// A linked worktree was registered or unregistered in the main
// gitdir: `git worktree add` / `remove` creates or deletes
// `.git/worktrees/<name>`. Its own gitfile is written before the
// watcher can watch the new directory, so this entry is what
// Linux per-directory watchers see.
git_dirs |= batch.vcs.iter().any(|p| {
let rest: Vec<_> = p
.components()
.skip_while(|c| c.as_os_str() != ".git")
.skip(1) // the `.git` component itself
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
});
if git_dirs {
scan_repositories(&root, &repos, &settings, &sink);
@@ -345,6 +375,13 @@ impl Host {
}),
)?
};
if let Some(reason) = watcher.polling() {
sink.emit(IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
title: "External file changes sync may be slow".into(),
body: Some(reason.into()),
});
}
// Scratch files live outside the project; watch them too so the
// Project view and open editors follow changes made there.
@@ -682,17 +719,24 @@ impl Project {
self.with_repo_at(None, f)
}
pub(crate) fn with_disk_sync<T>(&self, f: impl FnOnce() -> IdeResult<T>) -> IdeResult<T> {
let result = f();
// Failed operations can also leave changed files (for example merge conflicts).
self.documents.sync_after_disk_change();
result
}
/// Runs a VCS operation that rewrites the working tree (checkout, merge,
/// rebase, pull, reset, stash, rollback): Local History gets a label and a
/// snapshot of every locally changed file before, and a label after.
/// `None` runs `f` like [`with_repo`](Self::with_repo) (operations that keep the working tree).
/// Clean buffers follow the resulting files before returning; `None` omits the history labels.
pub fn with_repo_recorded<T>(
&self,
at: Option<&Path>,
operation: Option<&str>,
f: impl FnOnce(&Repo) -> IdeResult<T>,
) -> IdeResult<T> {
let Some(name) = operation else { return self.with_repo_at(at, f) };
let Some(name) = operation else { return self.with_disk_sync(|| self.with_repo_at(at, f)) };
self.history_label(&format!("Before {name}"));
if let Ok(changed) = self.with_repo_at(at, |r| r.status()) {
for file in changed.iter().take(HISTORY_BATCH_LIMIT) {
@@ -701,7 +745,7 @@ impl Project {
}
}
}
let result = self.with_repo_at(at, f);
let result = self.with_disk_sync(|| self.with_repo_at(at, f));
self.history_label(&format!("After {name}"));
result
}
+1 -1
Переглянути файл
@@ -178,7 +178,7 @@ impl Dispatcher {
Ok(())
})
.add("cancel_task", |c| async move { Ok(ide_core::task::cancel(c.arg::<TaskId>("id")?)) })
.add("fs_read_dir", |c| async move { ops::fs::read_dir(&c.host, &c.window, c.arg("path")?) })
.add("fs_read_dir", |c| async move { ops::fs::read_dir(&c.host, &c.window, c.arg("path")?).await })
.add("fs_entry_kind", |c| async move { ops::fs::entry_kind(&c.host, c.arg("path")?).await })
.add("fs_create_file", |c| async move { ops::fs::create_file(&c.host, &c.window, c.arg("path")?) })
.add("fs_create_file_bytes", |c| async move {
+9 -6
Переглянути файл
@@ -1,4 +1,4 @@
#![cfg(unix)]
#![cfg(any(unix, windows))]
use ide_core::{NullSink, TerminalId};
use ide_host::{Host, HostConfig, ops};
@@ -28,8 +28,8 @@ async fn storage_requires_a_registered_terminal() {
.spawn(
TerminalOptions {
cwd: root.path().into(),
shell: Some("/bin/sh".into()),
args: vec![],
shell: Some(if cfg!(windows) { "powershell.exe" } else { "/bin/sh" }.into()),
args: if cfg!(windows) { vec!["-NoLogo".into(), "-NoProfile".into()] } else { vec![] },
env: Default::default(),
cols: 80,
rows: 24,
@@ -40,9 +40,12 @@ async fn storage_requires_a_registered_terminal() {
Box::new(|_| {}),
)
.unwrap();
let path = ops::term::store_image(&host, terminal.id, vec![1, 2, 3], "image/png".into()).await.unwrap();
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
for mime in ["image/png", "audio/mpeg", "video/mp4"] {
let path = ops::term::store_image(&host, terminal.id, vec![1, 2, 3], mime.into()).await.unwrap();
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
}
assert!(ops::term::store_image(&host, terminal.id, vec![1], "application/octet-stream".into()).await.is_err());
host.terminals.kill(terminal.id).unwrap();
assert!(ops::term::store_image(&host, terminal.id, vec![4], "image/png".into()).await.is_err());
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 1);
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 3);
}
+240
Переглянути файл
@@ -0,0 +1,240 @@
use ide_core::{ChangeSet, NullSink, TextChange};
use ide_host::{Host, HostConfig, Project, ops::vcs};
use std::{path::Path, process::Command, sync::Arc, time::Duration};
const ORIGINAL: &str = "SELECT *\nFROM patients\n\tLIMIT 10 OFFSET 0";
const OTHER: &str = "SELECT id\nFROM patients\n\tLIMIT 20 OFFSET 0";
fn git(root: &Path, args: &[&str]) -> String {
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8(out.stdout).unwrap()
}
struct Fixture {
host: Host,
project: Arc<Project>,
path: std::path::PathBuf,
doc: ide_core::DocId,
_temp: tempfile::TempDir,
}
impl Fixture {
async fn new() -> Self {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
// The command must synchronize documents even when watcher delivery is excluded.
let path = root.join("node_modules/query.sql");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
git(&root, &["init", "-b", "main"]);
git(&root, &["config", "user.name", "Test"]);
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
git(&root, &["config", "core.autocrlf", "false"]);
std::fs::write(&path, ORIGINAL).unwrap();
git(&root, &["add", "-f", "node_modules/query.sql"]);
git(&root, &["commit", "-m", "original"]);
git(&root, &["switch", "-c", "other"]);
std::fs::write(&path, OTHER).unwrap();
git(&root, &["commit", "-am", "other"]);
git(&root, &["switch", "main"]);
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let doc = project.documents.open(&path).unwrap().id;
Self { host, project, path, doc, _temp: temp }
}
fn saved_edit(&self, text: &str) {
self.project.documents.replace_all(self.doc, text).unwrap();
self.project.documents.save(self.doc).unwrap();
}
fn assert_clean(&self, text: &str) {
let snapshot = self.project.documents.snapshot(self.doc).unwrap();
assert_eq!(snapshot.text, text);
assert!(!snapshot.dirty);
self.project.documents.save_all().unwrap();
assert_eq!(std::fs::read_to_string(&self.path).unwrap(), text);
}
}
impl Drop for Fixture {
fn drop(&mut self) {
self.host.close_project("main");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn checkout_reloads_clean_open_documents_before_returning() {
let f = Fixture::new().await;
vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None).await.unwrap();
f.assert_clean(OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rollback_reloads_clean_open_documents_before_returning() {
let f = Fixture::new().await;
f.saved_edit(&format!("{ORIGINAL}\n"));
vcs::vcs_discard(&f.host, "main", vec![f.path.clone()]).await.unwrap();
f.assert_clean(ORIGINAL);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stash_and_unstash_reload_clean_open_documents_before_returning() {
let f = Fixture::new().await;
let edited = format!("{ORIGINAL}\n");
f.saved_edit(&edited);
vcs::vcs_stash_push(&f.host, "main", None, None, false, false).await.unwrap();
f.assert_clean(ORIGINAL);
vcs::vcs_stash_apply(&f.host, "main", None, 0, true, false, None).await.unwrap();
f.assert_clean(&edited);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn applying_patch_reloads_clean_open_documents_before_returning() {
let f = Fixture::new().await;
std::fs::write(&f.path, OTHER).unwrap();
let patch = git(&f.project.root, &["diff"]);
git(&f.project.root, &["restore", "."]);
vcs::vcs_apply_patch(&f.host, "main", None, patch).await.unwrap();
f.assert_clean(OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn writing_patch_file_reloads_its_clean_open_document() {
let f = Fixture::new().await;
vcs::vcs_write_patch(&f.host, "main", f.path.clone(), OTHER.into()).await.unwrap();
f.assert_clean(OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn directory_compare_overwrite_reloads_clean_open_documents() {
let f = Fixture::new().await;
let base = f.project.root.parent().unwrap();
let source = base.join("source");
let destination = base.join("destination");
std::fs::create_dir_all(&source).unwrap();
std::fs::create_dir_all(&destination).unwrap();
std::fs::write(source.join("query.sql"), OTHER).unwrap();
let path = destination.join("query.sql");
std::fs::write(&path, ORIGINAL).unwrap();
let doc = f.project.documents.open(&path).unwrap();
ide_host::ops::fs::copy_merge(&f.host, "main", source, destination, "query.sql".into(), true).await.unwrap();
let snapshot = f.project.documents.snapshot(doc.id).unwrap();
assert_eq!(snapshot.text, OTHER);
assert!(!snapshot.dirty);
f.project.documents.save_all().unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn failed_working_tree_operation_synchronizes_partial_disk_changes() {
let f = Fixture::new().await;
let result: ide_core::IdeResult<()> = f.project.with_repo_recorded(None, Some("Git merge"), |_| {
std::fs::write(&f.path, OTHER).unwrap();
Err(ide_core::IdeError::invalid("merge stopped with conflicts"))
});
assert!(result.is_err());
f.assert_clean(OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn working_tree_operation_reloads_same_size_same_timestamp_changes() {
let f = Fixture::new().await;
let modified = std::fs::metadata(&f.path).unwrap().modified().unwrap();
let replacement = ORIGINAL.replace("LIMIT 10", "LIMIT 20");
f.project
.with_repo_recorded(None, Some("Git checkout"), |_| {
std::fs::write(&f.path, &replacement).unwrap();
std::fs::File::options()
.write(true)
.open(&f.path)
.unwrap()
.set_times(std::fs::FileTimes::new().set_modified(modified))
.unwrap();
Ok(())
})
.unwrap();
f.assert_clean(&replacement);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn working_tree_operation_does_not_discard_unsaved_edits() {
let f = Fixture::new().await;
let version = f.project.documents.snapshot(f.doc).unwrap().version;
f.project
.documents
.edit(f.doc, version, ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "-- local\n".into() }] })
.unwrap();
vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None).await.unwrap();
let snapshot = f.project.documents.snapshot(f.doc).unwrap();
assert_eq!(snapshot.text, format!("-- local\n{ORIGINAL}"));
assert!(snapshot.dirty);
assert_eq!(std::fs::read_to_string(&f.path).unwrap(), OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn adding_local_exclude_reloads_open_ignore_document() {
let f = Fixture::new().await;
let path = f.project.root.join(".git/info/exclude");
let doc = f.project.documents.open(&path).unwrap();
let ignored = f.project.root.join("generated.txt");
std::fs::write(&ignored, "generated\n").unwrap();
vcs::vcs_add_to_ignore(&f.host, "main", vec![ignored], ide_vcs::IgnoreDestination::LocalExclude).await.unwrap();
let disk = std::fs::read_to_string(&path).unwrap();
assert!(disk.contains("/generated.txt"));
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().text, disk);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn commit_hook_reloads_clean_open_documents() {
use std::os::unix::fs::PermissionsExt;
let f = Fixture::new().await;
f.saved_edit(&format!("{ORIGINAL}\n"));
git(&f.project.root, &["add", "-u"]);
let hook = f.project.root.join(".git/hooks/pre-commit");
std::fs::write(&hook, "#!/bin/sh\nprintf 'SELECT hook;' > node_modules/query.sql\n").unwrap();
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
vcs::vcs_commit(
&f.host,
"main",
None,
"commit with hook".into(),
ide_vcs::CommitOptions { run_hooks: true, ..Default::default() },
)
.await
.unwrap();
f.assert_clean("SELECT hook;");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn worktree_checkout_hook_reloads_clean_open_documents() {
use std::os::unix::fs::PermissionsExt;
let f = Fixture::new().await;
let hook = f.project.root.join(".git/hooks/post-checkout");
std::fs::write(&hook, "#!/bin/sh\nprintf 'SELECT hook;' > ../project/node_modules/query.sql\n").unwrap();
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
let linked = f.project.root.parent().unwrap().join("linked");
vcs::vcs_add_worktree(&f.host, "main", None, linked, "other".into(), None).await.unwrap();
f.assert_clean("SELECT hook;");
}
+123
Переглянути файл
@@ -0,0 +1,123 @@
//! Shelves retain their repository even when the project root is above or below it.
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops::vcs};
use std::{path::Path, process::Command, sync::Arc, time::Duration};
fn git(root: &Path, args: &[&str]) {
let output = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
}
async fn check_shelves(layout: &str) {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let project_root = base.join("project");
let roots = match layout {
"same" => vec![project_root.clone()],
"below" => vec![base.clone()],
"two" => vec![project_root.join("项目A"), project_root.join("repoB")],
_ => vec![project_root.join("项目A")],
};
std::fs::create_dir_all(project_root.join("dirB")).unwrap();
for (i, root) in roots.iter().enumerate() {
std::fs::create_dir_all(root.join("src")).unwrap();
git(root, &["init", "-b", "main"]);
git(root, &["config", "user.name", "Test"]);
git(root, &["config", "user.email", "[email protected]"]);
std::fs::write(root.join("src/same.txt"), format!("base {i}\n")).unwrap();
git(root, &["add", "src"]);
git(root, &["commit", "-m", "initial"]);
std::fs::write(root.join("src/same.txt"), format!("shelved {i}\n")).unwrap();
}
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&project_root, true, false).unwrap();
let project = host.open_project("main", &project_root).unwrap();
for _ in 0..500 {
if project.repos().all().len() == roots.len() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(project.repos().all().len(), roots.len());
let primary = project.repos().primary().unwrap().root().to_path_buf();
if roots.len() == 2 {
assert!(
vcs::vcs_shelve(&host, "main", "mixed".into(), roots.iter().map(|r| r.join("src/same.txt")).collect())
.await
.is_err()
);
assert!(vcs::vcs_shelves(&host, "main").unwrap().is_empty());
}
for (i, root) in roots.iter().enumerate() {
let entry = vcs::vcs_shelve(&host, "main", "work".into(), vec![root.join("src/same.txt")]).await.unwrap();
assert_eq!(entry.repo.as_deref(), Some(root.as_path()));
assert_eq!(std::fs::read_to_string(root.join("src/same.txt")).unwrap(), format!("base {i}\n"));
let listed = vcs::vcs_shelves(&host, "main").unwrap();
assert_eq!(listed.iter().find(|s| s.id == entry.id).unwrap().repo, entry.repo);
let diffs = vcs::vcs_shelf_diff(&host, "main", entry.id.clone()).await.unwrap();
assert_eq!(diffs[0].before.as_deref(), Some(format!("base {i}\n").as_str()));
assert_eq!(diffs[0].after.as_deref(), Some(format!("shelved {i}\n").as_str()));
vcs::vcs_shelf_rename(&host, "main", entry.id.clone(), "renamed".into()).unwrap();
let patch = vcs::vcs_shelf_patch(&host, "main", entry.id.clone(), None).unwrap();
vcs::vcs_shelf_import(&host, "main", Some(root.clone()), "imported".into(), patch).await.unwrap();
let imported = vcs::vcs_shelves(&host, "main").unwrap().into_iter().find(|s| s.name == "imported").unwrap();
assert_eq!(imported.repo, entry.repo);
vcs::vcs_shelf_delete(&host, "main", imported.id, None).unwrap();
if root != &primary {
let info = ide_core::project_dir::path(&project_root, "shelf").join(&entry.id).join("shelf.json");
let original = std::fs::read(&info).unwrap();
let mut metadata: serde_json::Value = serde_json::from_slice(&original).unwrap();
metadata["repo"] = serde_json::json!(base.join("missing-repository"));
std::fs::write(&info, serde_json::to_vec(&metadata).unwrap()).unwrap();
assert!(vcs::vcs_shelf_diff(&host, "main", entry.id.clone()).await.is_err());
assert!(vcs::vcs_unshelve(&host, "main", entry.id.clone(), false, None).await.is_err());
assert_eq!(std::fs::read_to_string(root.join("src/same.txt")).unwrap(), format!("base {i}\n"));
std::fs::write(info, original).unwrap();
}
vcs::vcs_unshelve(&host, "main", entry.id.clone(), false, Some("src/same.txt".into())).await.unwrap();
assert_eq!(std::fs::read_to_string(root.join("src/same.txt")).unwrap(), format!("shelved {i}\n"));
// Old shelves were always made in the primary repository; missing ownership keeps that meaning.
if root == &primary {
let info = ide_core::project_dir::path(&project_root, "shelf").join(&entry.id).join("shelf.json");
let mut metadata: serde_json::Value = serde_json::from_slice(&std::fs::read(&info).unwrap()).unwrap();
metadata.as_object_mut().unwrap().remove("repo");
std::fs::write(info, serde_json::to_vec(&metadata).unwrap()).unwrap();
assert_eq!(
vcs::vcs_shelves(&host, "main").unwrap().into_iter().find(|s| s.id == entry.id).unwrap().repo,
entry.repo
);
assert_eq!(
vcs::vcs_shelf_diff(&host, "main", entry.id).await.unwrap()[0].after.as_deref(),
Some(format!("shelved {i}\n").as_str())
);
}
}
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shelf_at_repo_root() {
check_shelves("same").await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shelf_in_non_git_project() {
check_shelves("above").await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shelves_in_two_repositories() {
check_shelves("two").await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shelf_in_project_below_repository() {
check_shelves("below").await;
}
+93
Переглянути файл
@@ -0,0 +1,93 @@
use ide_core::NullSink;
use ide_host::{Host, HostConfig, Project, ops::vcs};
use std::{path::PathBuf, process::Command, sync::Arc, time::Duration};
fn git(root: &std::path::Path, args: &[&str]) {
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
async fn wait_for_repos(project: &Arc<Project>, count: usize) {
for _ in 0..200 {
if project.repos().all().len() >= count {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
panic!("expected {} repositories, found {}", count, project.repos().all().len());
}
struct Fixture {
host: Host,
project: Arc<Project>,
root: PathBuf,
_temp: tempfile::TempDir,
}
impl Fixture {
async fn new() -> Self {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
git(&root, &["init", "-b", "main"]);
git(&root, &["config", "user.name", "Test"]);
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
git(&root, &["config", "core.autocrlf", "false"]);
std::fs::write(root.join("file.txt"), "original\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "original"]);
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
wait_for_repos(&project, 1).await;
Self { host, project, root, _temp: temp }
}
}
impl Drop for Fixture {
fn drop(&mut self) {
self.host.close_project("main");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn command_added_worktree_joins_the_repository_set() {
let f = Fixture::new().await;
let linked = f.root.join("linked");
vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "main".into(), Some("topic".into())).await.unwrap();
let roots = f.project.repos().roots();
assert!(roots.contains(&linked), "worktree below the project did not join the repository set: {roots:?}");
assert_eq!(roots.len(), 2);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn removed_worktree_leaves_the_repository_set() {
let f = Fixture::new().await;
let linked = f.root.join("linked");
vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "main".into(), Some("topic".into())).await.unwrap();
assert_eq!(f.project.repos().all().len(), 2);
vcs::vcs_remove_worktree(&f.host, "main", None, linked, false).await.unwrap();
assert_eq!(f.project.repos().all().len(), 1);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn watcher_picks_up_a_worktree_added_below_the_project() {
let f = Fixture::new().await;
let linked = f.root.join("watched");
git(&f.root, &["worktree", "add", "watched", "-b", "watched"]);
wait_for_repos(&f.project, 2).await;
let roots = f.project.repos().roots();
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
}
+11 -1
Переглянути файл
@@ -57,6 +57,16 @@ pub fn shared() -> IdeResult<reqwest::Client> {
Ok(client)
}
/// `url`, with `http://` in front unless it starts with a scheme: a `://` later
/// on (`localhost:8080/login?next=http://…`) does not count.
pub(crate) fn with_scheme(url: &str) -> String {
let has_scheme = url.split_once("://").is_some_and(|(scheme, _)| {
scheme.starts_with(|c: char| c.is_ascii_alphabetic())
&& scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
});
if has_scheme { url.to_owned() } else { format!("http://{url}") }
}
/// HTTP Proxy › Check connection: GETs `url` through `proxy` (the settings as
/// edited, not yet applied). Any response but `407` counts as connected.
pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &CancellationToken) -> IdeResult<String> {
@@ -64,7 +74,7 @@ pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &Cancell
return Err(IdeError::invalid(problem));
}
let url = url.trim();
let url = if url.contains("://") { url.to_owned() } else { format!("http://{url}") };
let url = with_scheme(url);
let client = build(proxy)?;
let request = client.get(&url).timeout(Duration::from_secs(30));
let response = tokio::select! {
+16 -4
Переглянути файл
@@ -1,6 +1,6 @@
//! Preparing (substitution, body includes) and executing requests.
use crate::client::describe;
use crate::client::{describe, with_scheme};
use crate::env::{Environments, Resolver};
use crate::parse::{BodyPart, RawRequest};
use ide_core::{CancellationToken, IdeError, IdeResult};
@@ -84,10 +84,8 @@ pub fn prepare(
Some((_, host)) => format!("http://{host}{url}"),
None => return Err(IdeError::invalid(format!("relative URL {url} needs a Host header"))),
}
} else if !url.contains("://") {
format!("http://{url}")
} else {
url
with_scheme(&url)
};
Ok(PreparedRequest {
name: raw.block.name.clone(),
@@ -214,6 +212,20 @@ mod tests {
assert_eq!(p.url, "http://localhost:9000/status");
}
#[test]
fn urls_without_a_scheme_default_to_http() {
let url = |text: &str| {
let f = parse(text);
prepare(&f.requests[0], &f.variables, &Environments::default(), None, None).unwrap().url
};
assert_eq!(url("GET localhost:8080/health\n"), "http://localhost:8080/health");
assert_eq!(
url("GET localhost:8080/login?next=http://localhost:3000/\n"),
"http://localhost:8080/login?next=http://localhost:3000/"
);
assert_eq!(url("GET https://api.test/cb?u=http://x\n"), "https://api.test/cb?u=http://x");
}
#[tokio::test]
async fn executes_against_a_local_server() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
+9 -2
Переглянути файл
@@ -22,6 +22,7 @@ const BUILTIN: &[(&str, &str)] = &[
("dockerfile", include_str!("../../../languages/dockerfile.toml")),
("dotenv", include_str!("../../../languages/dotenv.toml")),
("elixir", include_str!("../../../languages/elixir.toml")),
("erb", include_str!("../../../languages/erb.toml")),
("erlang", include_str!("../../../languages/erlang.toml")),
("fsharp", include_str!("../../../languages/fsharp.toml")),
("gitattributes", include_str!("../../../languages/gitattributes.toml")),
@@ -44,6 +45,7 @@ const BUILTIN: &[(&str, &str)] = &[
("javascriptreact", include_str!("../../../languages/javascriptreact.toml")),
("json", include_str!("../../../languages/json.toml")),
("jsonc", include_str!("../../../languages/jsonc.toml")),
("jsp", include_str!("../../../languages/jsp.toml")),
("julia", include_str!("../../../languages/julia.toml")),
("kotlin", include_str!("../../../languages/kotlin.toml")),
("latex", include_str!("../../../languages/latex.toml")),
@@ -520,6 +522,8 @@ mod tests {
"MsGenny",
"Vue",
"Angular Template",
"ERB",
"JSP",
];
fn reg() -> LanguageRegistry {
@@ -553,7 +557,7 @@ mod tests {
fn alternative_servers_are_fallbacks() {
let reg = reg();
for (lang, servers) in [
("python", vec!["basedpyright", "pyright", "ty"]),
("python", vec!["basedpyright", "pyright", "ty", "pyrefly"]),
("typescript", vec!["vtsls", "typescript-language-server"]),
] {
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
@@ -610,7 +614,7 @@ mod tests {
let cfg = reg.get(&LanguageId::new("python")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallbacks: hover, rename and symbols stay with the type checker.
assert_eq!(names, ["basedpyright", "pyright", "ty", "ruff"]);
assert_eq!(names, ["basedpyright", "pyright", "ty", "pyrefly", "ruff"]);
let ruff = cfg.language_servers.iter().find(|s| s.name == "ruff").unwrap();
assert_eq!((ruff.command.as_str(), ruff.args.as_slice()), ("ruff", ["server".to_string()].as_slice()));
assert!(ruff.require_root_marker && !ruff.fallback);
@@ -776,6 +780,7 @@ mod tests {
("AppDelegate.m", "objective-c"),
("a.rb", "ruby"),
("Gemfile", "ruby"),
("show.html.erb", "erb"),
("index.php", "php"),
("init.lua", "lua"),
("main.dart", "dart"),
@@ -800,6 +805,8 @@ mod tests {
("a.less", "less"),
("App.vue", "vue"),
("App.svelte", "svelte"),
("index.jsp", "jsp"),
("WEB-INF/tags/card.tag", "jsp"),
("package.json", "json"),
("tsconfig.json", "jsonc"),
("tsconfig.app.json", "jsonc"),
+80 -2
Переглянути файл
@@ -1,9 +1,9 @@
//! Source ranges for Spring-style configuration keys. This is a syntax index,
//! not a YAML evaluator: aliases, merge keys and runtime profile precedence are
//! intentionally left to the YAML server / application.
use super::lines::LineIndex;
use super::lines::{LineIndex, byte_at};
use super::{ParsedTree, Syntax, TreeError};
use ide_core::{LanguageId, Range};
use ide_core::{LanguageId, Pos, Range};
use tree_sitter::Node;
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -26,6 +26,40 @@ impl Syntax {
}
}
/// Spring's property lookups whose first argument names a configuration key.
const PROPERTY_LOOKUPS: [&str; 2] = ["getProperty", "getRequiredProperty"];
impl Syntax {
/// Whether `pos` in Java `text` lies where a configuration key can be written:
/// inside the arguments of a `@Value` annotation or of a `getProperty` /
/// `getRequiredProperty` call. Everywhere else Go to Definition is ordinary
/// Java navigation and need not consult the configuration index. A file the
/// grammar cannot parse answers false.
pub fn java_configuration_site(&self, text: &str, pos: Pos, cancelled: &dyn Fn() -> bool) -> bool {
let Some(at) = byte_at(text, pos) else { return false };
self.with_parsed(&LanguageId::new("java"), text, cancelled, |tree| {
let mut node = tree.tree.root_node().descendant_for_byte_range(at, at);
while let Some(n) = node {
let Some(parent) = n.parent() else { break };
let callee = parent.child_by_field_name("name").map(|name| &text[name.byte_range()]);
match (n.kind(), parent.kind(), callee) {
("annotation_argument_list", "annotation", Some(name)) => {
return name.rsplit('.').next() == Some("Value");
}
("argument_list", "method_invocation", Some(name)) if PROPERTY_LOOKUPS.contains(&name) => {
return true;
}
// Keys are expressions; nothing above a body or declaration can hold one.
(_, "block" | "class_body" | "interface_body" | "program", _) => return false,
_ => node = Some(parent),
}
}
false
})
.unwrap_or(false)
}
}
impl ParsedTree<'_> {
pub fn configuration_keys(&self, cancelled: &dyn Fn() -> bool) -> Vec<ConfigurationKey> {
let mut out = Vec::new();
@@ -188,6 +222,50 @@ fn unescape_property(raw: &str) -> Option<String> {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn java_configuration_sites() {
let text = r#"package a;
import org.springframework.beans.factory.annotation.Value;
class A {
@Value("${app.port:80}") int port;
@org.springframework.beans.factory.annotation.Value(value = Keys.NAME) String name;
@Values("x") int other;
@Override public String toString() {
String v = env.getProperty("app.host", "h") + env.getRequiredProperty(Keys.USER);
return helper.getValue("😀 app.port") + String.valueOf(port) + env.getProperty("k").trim();
}
}
"#;
let syntax = Syntax::new();
let at = |needle: &str, offset: u32| {
let line = text.lines().position(|l| l.contains(needle)).unwrap();
let byte = text.lines().nth(line).unwrap().find(needle).unwrap();
let col = text.lines().nth(line).unwrap()[..byte].encode_utf16().count() as u32 + offset;
syntax.java_configuration_site(text, Pos::new(line as u32, col), &|| false)
};
// @Value arguments (literal, qualified annotation, constant key).
assert!(at("${app.port", 2));
assert!(at("Keys.NAME", 6));
// Lookup arguments, including a constant and the default value.
assert!(at("\"app.host\"", 3));
assert!(at("\"h\"", 1));
assert!(at("Keys.USER", 1));
assert!(at("\"k\"", 1));
// Ordinary Java: names, other annotations, other calls, the lookup's own name and receiver.
assert!(!at("@Value(\"$", 2));
assert!(!at("int port", 4));
assert!(!at("@Values", 9));
assert!(!at("@Override", 2));
assert!(!at("getProperty(\"app", 3));
assert!(!at("env.getProperty(\"app", 1));
assert!(!at("app.port\")", 1));
assert!(!at("valueOf", 2));
assert!(!at(".trim", 2));
// Out of range and non-Java input.
assert!(!syntax.java_configuration_site(text, Pos::new(99, 0), &|| false));
assert!(!syntax.java_configuration_site("", Pos::new(0, 0), &|| false));
}
#[test]
fn yaml_structures_and_utf16() {
let text = "app:\n 'time-out': 1\n hosts:\n - url: a\n - {url: b}\n map: {east: {size: 2}}\n---\n\"app.name\": ok\n'😀': {port: 3}\n";
+10
Переглянути файл
@@ -86,6 +86,16 @@ pub(crate) fn utf16_len(s: &str) -> u32 {
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
}
/// Byte offset of `pos` (line, UTF-16 column) in `text`; None past the last line.
pub(crate) fn byte_at(text: &str, pos: Pos) -> Option<usize> {
let mut start = 0;
for _ in 0..pos.line {
start += text[start..].find('\n')? + 1;
}
let line_end = text[start..].find('\n').map_or(text.len(), |i| start + i);
Some(start + utf16_to_byte(&text[start..line_end], pos.col as usize))
}
pub(crate) fn utf16_to_byte(s: &str, offset: usize) -> usize {
let mut units = 0;
for (i, c) in s.char_indices() {
+2 -2
Переглянути файл
@@ -201,11 +201,11 @@ impl Syntax {
/// The grammar web features parse `lang` with: its own for HTML and CSS, the
/// CSS grammar for SCSS / Less (selectors and custom properties parse alike),
/// HTML for Vue / Svelte single-file components.
/// HTML for Vue / Svelte single-file components and JSP pages.
fn web_grammar(&self, lang: &LanguageId) -> Option<&Grammar> {
let name = match lang.as_str() {
"scss" | "less" => "css",
"vue" | "svelte" => "html",
"vue" | "svelte" | "jsp" => "html",
_ => self.grammar(lang).map(|g| g.spec.name)?,
};
web::is_web_grammar(name).then(|| self.grammar(&LanguageId::new(name))).flatten()
+1 -10
Переглянути файл
@@ -6,7 +6,7 @@
//! `<style>` elements of HTML documents and feed the symbol index (see
//! [`super::Syntax::tags`]), so a lookup is an exact index query.
use super::lines::{LineIndex, utf16_to_byte};
use super::lines::{LineIndex, byte_at};
use super::{Grammar, parse};
use crate::SymbolTag;
use ide_core::{Pos, Range, SymbolKind};
@@ -130,15 +130,6 @@ pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text:
out
}
fn byte_at(text: &str, pos: Pos) -> Option<usize> {
let mut start = 0;
for _ in 0..pos.line {
start += text[start..].find('\n')? + 1;
}
let line_end = text[start..].find('\n').map_or(text.len(), |i| start + i);
Some(start + utf16_to_byte(&text[start..line_end], pos.col as usize))
}
/// The whitespace-separated token of `value` (starting at byte `base`) around byte `at`.
fn token_at(value: &str, base: usize, at: usize) -> Option<(usize, &str)> {
let rel = at.checked_sub(base)?;
+1
Переглянути файл
@@ -24,6 +24,7 @@ globset.workspace = true
ignore.workspace = true
toml.workspace = true
percent-encoding = "2"
zip.workspace = true
[dev-dependencies]
tempfile.workspace = true
+7
Переглянути файл
@@ -228,6 +228,10 @@ impl Handler for ClientHandler {
"window/logMessage" => {
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
match params.get("type").and_then(Value::as_u64) {
Some(1) if self.server.name == "jdtls" && text.contains(crate::jdtls::reserved_names::IMPORT_FAILURE) => {
tracing::warn!("[{}] {text}", self.server.name);
mgr.report_import_failure(self.server.root.clone(), text.to_owned());
}
Some(1) => tracing::warn!("[{}] {text}", self.server.name),
Some(2 | 3) => tracing::info!("[{}] {text}", self.server.name),
_ => tracing::debug!("[{}] {text}", self.server.name),
@@ -237,6 +241,9 @@ impl Handler for ClientHandler {
"language/status" if self.server.name == "jdtls" && params["type"] == "ServiceReady" => {
mgr.java_import_ready(self.server.clone(), self.generation);
}
"language/status" if self.server.name == "jdtls" && params["type"] == "ProjectStatus" => {
mgr.java_projects_updated(self.server.clone(), self.generation);
}
// The Angular server's project loading, shown like `$/progress`; one
// task while several projects load.
"angular/projectLoadingStart" if !self.server.progress.lock().contains_key(ANGULAR_LOADING) => self
+68 -7
Переглянути файл
@@ -20,6 +20,7 @@ const SERVER: &str = "jdtls";
pub(crate) mod configuration;
mod formatter;
pub(crate) mod reserved_names;
pub use formatter::configure_formatter;
/// First start imports the Maven / Gradle model, which can take minutes.
const READY_TIMEOUT: Duration = Duration::from_secs(240);
@@ -335,6 +336,35 @@ impl LspManager {
});
}
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
.lock()
.values()
.filter(|d| d.language.as_str() == "java" && d.path.starts_with(&server.root))
.map(|d| crate::uri::path_to_uri_string(&d.path))
.collect();
if uris.is_empty() {
return;
}
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
let request = run.peer.request::<_, Value>("workspace/executeCommand", params, None);
if let Ok(Err(e)) | Err(e) =
tokio::time::timeout(COMMAND_TIMEOUT, request).await.map_err(|_| ide_jsonrpc::RpcError::Timeout)
{
tracing::debug!("jdtls: java.project.refreshDiagnostics {uri}: {e}");
}
}
});
}
/// The jdtls instance serving `path` (a module directory or source file),
/// started if needed and waited for.
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
@@ -521,11 +551,15 @@ impl LspManager {
}
/// Builds (when asked), then resolves the classpath and JDK of the module at `module`.
/// The classpath queries take the module's workspace scheduling rule like the build
/// commands do, so they run under the build lock; pass `build_lock_held` when the caller
/// already holds it (the delegated external build), or the wait would deadlock.
pub async fn java_launch(
&self,
module: &Path,
test: bool,
build: bool,
build_lock_held: bool,
cancel: &CancellationToken,
) -> IdeResult<JavaLaunchInfo> {
let build = if build { Some(self.java_build(module, cancel).await?) } else { None };
@@ -538,14 +572,23 @@ impl LspManager {
}
_ => (Vec::new(), 0),
};
let cp = self.java_classpath(module, test, cancel).await?;
let java_home = match self.java_vm_location(module, cancel).await {
Ok(home) => home,
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
Err(e) => {
tracing::debug!("java.project.getSettings: {e}");
let (cp, java_home) = {
let (server, _) = self.jdtls(module, cancel).await?;
let _lock = if build_lock_held {
None
}
} else {
Some(cancellable_wait(cancel, server.java_build_lock.lock()).await?)
};
let cp = self.java_classpath(module, test, cancel).await?;
let java_home = match self.java_vm_location(module, cancel).await {
Ok(home) => home,
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
Err(e) => {
tracing::debug!("java.project.getSettings: {e}");
None
}
};
(cp, java_home)
};
Ok(JavaLaunchInfo {
build,
@@ -651,6 +694,24 @@ impl LspManager {
}
}
impl LspManager {
/// JDT LS aborted its import with `message`: when reserved Windows device names
/// below `root` are the cause, say which (once). The walk runs off the RPC thread.
pub(crate) fn report_import_failure(&self, root: PathBuf, message: String) {
let Some(me) = self.me.upgrade() else { return };
self.runtime.spawn_blocking(move || {
let Some(body) = reserved_names::import_failure_hint(&root, &message, cfg!(windows)) else { return };
if me.first_message(SERVER, &body) {
me.sink().emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Error,
title: "Java project import failed".into(),
body: Some(body),
});
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
+14 -2
Переглянути файл
@@ -117,13 +117,25 @@ impl LspManager {
return Ok(None);
}
// Definition in ordinary Java code remains JDT's definition. Reverse
// configuration navigation is offered on string expressions; field/config
// accessor usages are merged into the ordinary Find Usages response.
// configuration navigation is offered only inside `@Value` / property
// lookup arguments: the command builds a project-wide index, and every
// Ctrl+click and Ctrl+hover probe would otherwise wait on it before JDT
// answers. Field/config accessor usages are merged into Find Usages.
if !config && !usages {
let text = snap.text.as_str();
if !text.contains("Value") && !text.contains("getProperty") && !text.contains("getRequiredProperty") {
return Ok(None);
}
let text = text.to_owned();
let cancelled = cancel.clone();
let site = tokio::task::spawn_blocking(move || {
syntax().java_configuration_site(&text, pos, &|| cancelled.is_cancelled())
})
.await
.unwrap_or(false);
if !site {
return Ok(None);
}
}
let key = if config {
let text = snap.text.as_str().to_owned();
+143 -3
Переглянути файл
@@ -7,6 +7,61 @@ use std::path::Path;
const PROFILE: &str = "OpenIDEA IntelliJ IDEA";
const XML: &str = include_str!("intellij.xml");
const GENERATED_PROFILE: &str = "OpenIDEA Code Style";
const TAB_CHAR: &str = "org.eclipse.jdt.core.formatter.tabulation.char";
const TAB_SIZE: &str = "org.eclipse.jdt.core.formatter.tabulation.size";
const INDENT_SIZE: &str = "org.eclipse.jdt.core.formatter.indentation.size";
/// The Tabs and Indents override as Eclipse formatter settings. The profile must
/// carry them too: `indentation.size`, the per-level width, cannot come from the
/// format request, and an unset Indent follows the tab size, as in IDEA.
fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, String)>> {
let tab_char = style.use_tab.map(|tab| if tab { "tab" } else { "space" });
let indent = style.indent.or(style.tab_size);
if tab_char.is_none() && style.tab_size.is_none() && indent.is_none() {
return None;
}
let mut settings: Vec<(&'static str, String)> = Vec::new();
if let Some(char) = tab_char {
settings.push((TAB_CHAR, char.to_owned()));
}
if let Some(size) = style.tab_size {
settings.push((TAB_SIZE, size.to_string()));
}
if let Some(size) = indent {
settings.push((INDENT_SIZE, size.to_string()));
}
Some(settings)
}
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
for (id, value) in settings {
let marker = format!(r#"<setting id="{id}" value=""#);
let Some(at) = xml.find(&marker) else { continue };
let start = at + marker.len();
let Some(end) = xml[start..].find('"') else { continue };
xml.replace_range(start..start + end, value);
}
xml
}
/// A minimal Eclipse profile with just the override: unset keys keep jdtls's
/// built-in formatter defaults.
fn indent_profile_xml(settings: &[(&'static str, String)]) -> String {
let mut xml = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<profiles version="21">
<profile kind="CodeFormatterProfile" name="{}" version="21">
"#,
GENERATED_PROFILE
);
for (id, value) in settings {
xml.push_str(&format!(r#" <setting id="{id}" value="{value}"/>"#));
xml.push('\n');
}
xml.push_str(" </profile>\n</profiles>\n");
xml
}
/// Protocol settings only: switching profiles reaches a running jdtls through
/// didChangeConfiguration. Explicit language-server settings are applied later.
@@ -31,12 +86,17 @@ pub fn configure_formatter(
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
cfg.settings = Some(settings);
let Some(style) = style else { return Ok(()) };
let indent = indent_settings(style);
let (path, profile) = match style.formatter.as_deref() {
Some("intellij") => {
let path = data_dir.join("lsp/jdtls/intellij.xml");
std::fs::create_dir_all(path.parent().unwrap())?;
if std::fs::read_to_string(&path).ok().as_deref() != Some(XML) {
ide_vfs::write_atomic(&path, XML.as_bytes())?;
let xml = match indent {
Some(indent) => patch_profile_xml(XML.to_owned(), &indent),
None => XML.to_owned(),
};
if std::fs::read_to_string(&path).ok().as_deref() != Some(xml.as_str()) {
ide_vfs::write_atomic(&path, xml.as_bytes())?;
}
(path, PROFILE)
}
@@ -54,9 +114,22 @@ pub fn configure_formatter(
if !path.is_file() {
return Err(ide_core::IdeError::invalid(format!("Not a formatter XML file: {}", path.display())));
}
// The user's profile defines the style; the override stays editor-only.
(path, "")
}
_ => return Ok(()),
_ => {
// Default formatter: with a Tabs and Indents override, hand jdtls a
// minimal generated profile carrying it — the format request cannot
// set indentation.size. Without an override the built-in style stays.
let Some(indent) = indent else { return Ok(()) };
let path = data_dir.join("lsp/jdtls/indent.xml");
std::fs::create_dir_all(path.parent().unwrap())?;
let xml = indent_profile_xml(&indent);
if std::fs::read_to_string(&path).ok().as_deref() != Some(xml.as_str()) {
ide_vfs::write_atomic(&path, xml.as_bytes())?;
}
(path, GENERATED_PROFILE)
}
};
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
settings["java"]["format"]["settings"] = formatter_overrides(
@@ -144,6 +217,73 @@ mod tests {
}
}
#[test]
fn tabs_and_indents_override_reaches_the_formatter_profile() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
let data = dir.path().join("data");
std::fs::create_dir_all(&root).unwrap();
// The IntelliJ profile is the bundled XML with the override patched in.
let mut cfg = config("jdtls");
let style = LanguageCodeStyle {
formatter: Some("intellij".into()),
use_tab: Some(true),
tab_size: Some(1),
indent: Some(1),
..Default::default()
};
configure_formatter(&mut cfg, Some(&style), &root, &data, None).unwrap();
let settings = crate::handler::all_settings(&cfg)["java"]["format"]["settings"].clone();
assert_eq!(settings["profile"], PROFILE);
let patched = std::fs::read_to_string(data.join("lsp/jdtls/intellij.xml")).unwrap();
assert!(patched.contains(&format!(r#"<setting id="{TAB_CHAR}" value="tab"/>"#)));
assert!(patched.contains(&format!(r#"<setting id="{TAB_SIZE}" value="1"/>"#)));
assert!(patched.contains(&format!(r#"<setting id="{INDENT_SIZE}" value="1"/>"#)));
// The default formatter gets a minimal generated profile.
let mut cfg = config("jdtls");
let style = LanguageCodeStyle { use_tab: Some(false), tab_size: Some(2), ..Default::default() };
configure_formatter(&mut cfg, Some(&style), &root, &data, None).unwrap();
let settings = crate::handler::all_settings(&cfg)["java"]["format"]["settings"].clone();
let path = data.join("lsp/jdtls/indent.xml");
assert_eq!(settings["url"], crate::uri::path_to_uri_string(&path));
assert_eq!(settings["profile"], GENERATED_PROFILE);
let xml = std::fs::read_to_string(&path).unwrap();
assert!(xml.contains(&format!(r#"<setting id="{TAB_CHAR}" value="space"/>"#)));
// An unset Indent follows the tab size, as in IDEA.
assert!(xml.contains(&format!(r#"<setting id="{INDENT_SIZE}" value="2"/>"#)));
// Only Indent: the bundled tab settings stay.
let mut cfg = config("jdtls");
let style = LanguageCodeStyle { formatter: Some("intellij".into()), indent: Some(2), ..Default::default() };
configure_formatter(&mut cfg, Some(&style), &root, &data, None).unwrap();
let patched = std::fs::read_to_string(data.join("lsp/jdtls/intellij.xml")).unwrap();
assert!(patched.contains(&format!(r#"<setting id="{INDENT_SIZE}" value="2"/>"#)));
assert!(patched.contains(&format!(r#"<setting id="{TAB_CHAR}" value="space"/>"#)));
assert!(patched.contains(&format!(r#"<setting id="{TAB_SIZE}" value="4"/>"#)));
}
#[test]
fn tabs_and_indents_override_leaves_custom_profiles_alone() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir_all(&root).unwrap();
let custom = root.join("style.xml");
std::fs::write(&custom, XML).unwrap();
let mut cfg = config("jdtls");
let style = LanguageCodeStyle {
formatter: Some("custom".into()),
formatter_path: Some("style.xml".into()),
use_tab: Some(true),
tab_size: Some(1),
indent: Some(1),
..Default::default()
};
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(std::fs::read_to_string(&custom).unwrap(), XML);
}
#[test]
fn unavailable_custom_paths_are_nonfatal_and_do_not_set_launch_error() {
let dir = tempfile::tempdir().unwrap();
+180
Переглянути файл
@@ -0,0 +1,180 @@
//! Windows reserved device names (`nul`, `con`, …) inside a Java project.
//!
//! On Windows, a directory listing returns such a file (often left by a shell
//! redirect like `2>nul` in Git Bash), but `Files.exists` reports it missing as the
//! name resolves to the device. Eclipse's resource refresh then builds a child path
//! with an empty name and the Maven / Gradle import aborts during JDT LS
//! initialization with "Path must include project and resource name", so no Java
//! project is created. The user only sees every run fail with "module is not
//! imported"; this names the files that cause it.
use std::path::{Path, PathBuf};
/// What JDT LS logs when the import aborts on such an entry.
pub(crate) const IMPORT_FAILURE: &str = "Path must include project and resource name";
/// Directory entries visited per scan, and reserved names reported at most.
const MAX_VISITED: usize = 200_000;
const MAX_REPORTED: usize = 20;
/// Whether Windows treats `name` as a device: CON, PRN, AUX, NUL, COM0–9 or LPT0–9
/// (also with superscript digits), in any case, with or without an extension and
/// trailing spaces or dots.
pub(crate) fn is_reserved_device_name(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or_default().trim_end_matches(' ');
let upper = stem.to_ascii_uppercase();
if ["CON", "PRN", "AUX", "NUL"].contains(&upper.as_str()) {
return true;
}
let mut chars = upper.chars();
let prefix: String = chars.by_ref().take(3).collect();
let digit: Vec<char> = chars.collect();
(prefix == "COM" || prefix == "LPT")
&& matches!(digit.as_slice(), [d] if d.is_ascii_digit() || matches!(d, '¹' | '²' | '³'))
}
/// Entries below `root` with a reserved device name, in walk order (bounded).
/// Ignore files are not honoured: Eclipse's refresh does not honour them either.
pub(crate) fn reserved_entries(root: &Path) -> Vec<PathBuf> {
ignore::WalkBuilder::new(root)
.standard_filters(false)
.follow_links(false)
.build()
.take(MAX_VISITED)
.filter_map(Result::ok)
.filter(|entry| entry.depth() > 0 && entry.file_name().to_str().is_some_and(is_reserved_device_name))
.map(ignore::DirEntry::into_path)
.take(MAX_REPORTED)
.collect()
}
/// The notification body for a JDT LS log `message` from the server at `root`:
/// the reserved-name entries that abort the import, when the message is that
/// failure and the host is Windows (elsewhere such names are ordinary files).
pub(crate) fn import_failure_hint(root: &Path, message: &str, windows: bool) -> Option<String> {
if !windows || !message.contains(IMPORT_FAILURE) {
return None;
}
let entries = reserved_entries(root);
if entries.is_empty() {
return None;
}
let paths = entries
.iter()
.map(|path| path.strip_prefix(root).unwrap_or(path).display().to_string())
.collect::<Vec<_>>()
.join(", ");
Some(format!(
"The Java project cannot be imported because these files use a name Windows reserves for devices: {paths}. Delete or rename them, then restart the Java language server."
))
}
#[cfg(test)]
mod tests {
use super::*;
/// A path Windows does not resolve to a device (`\\?\`): the only way to create a
/// file named `nul` there. Elsewhere such names are ordinary files.
fn verbatim(path: &Path) -> PathBuf {
let text = path.to_string_lossy();
if cfg!(windows) && !text.starts_with(r"\\?\") {
PathBuf::from(format!(r"\\?\{text}"))
} else {
path.to_path_buf()
}
}
/// Writes `root` / `parts` (joined per component: verbatim paths take no `/`).
fn write(root: &Path, parts: &[&str], text: &str) {
let path = parts.iter().fold(root.to_path_buf(), |path, part| path.join(part));
std::fs::create_dir_all(verbatim(path.parent().unwrap())).unwrap();
std::fs::write(verbatim(&path), text).unwrap();
}
/// Removes a tree that may hold reserved names, which a plain path cannot delete on Windows.
fn remove(dir: tempfile::TempDir) {
let _ = std::fs::remove_dir_all(verbatim(&dir.keep()));
}
#[test]
fn reserved_device_names() {
for name in [
"nul",
"NUL",
"Nul",
"nul.txt",
"nul.tar.gz",
"nul ",
"con",
"prn",
"aux",
"com1",
"COM9",
"com0",
"lpt1",
"LPT9",
"com¹",
"lpt³",
"aux.java",
] {
assert!(is_reserved_device_name(name), "{name}");
}
for name in [
"null",
"nuls",
"anul",
"console",
"auxiliary",
"com",
"com10",
"lpt",
"lptx",
"comA",
".nul",
"",
"src",
"pom.xml",
"nul_file",
] {
assert!(!is_reserved_device_name(name), "{name}");
}
}
#[test]
fn import_failure_names_the_reserved_entries() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
write(root, &["nul"], "54 bytes of shell output");
write(root, &["module", "aux.txt"], "");
write(root, &["node_modules", "x", "con"], "");
write(root, &["module", "src", "Null.java"], "class Null {}");
write(root, &[".gitignore"], "nul\nnode_modules/\n");
let message = "Initialization failed | java.lang.IllegalArgumentException: Path must include project and resource name: /bkbits-parent | at UnifiedTree.createChildNodeFromFileSystem(UnifiedTree.java:320)";
let hint = import_failure_hint(root, message, true).unwrap();
let sep = std::path::MAIN_SEPARATOR;
for path in ["nul".to_owned(), format!("module{sep}aux.txt"), format!("node_modules{sep}x{sep}con")] {
assert!(hint.contains(&path), "{path} missing from {hint}");
}
assert!(!hint.contains("Null.java"));
assert!(hint.ends_with("then restart the Java language server."));
// Other failures, other hosts, and projects without such names stay silent.
assert_eq!(import_failure_hint(root, "Initialization failed | java.lang.NullPointerException", true), None);
assert_eq!(import_failure_hint(root, message, false), None);
let clean = tempfile::tempdir().unwrap();
write(clean.path(), &["pom.xml"], "<project/>");
assert_eq!(import_failure_hint(clean.path(), message, true), None);
remove(dir);
}
#[test]
fn reports_a_bounded_number_of_entries() {
let dir = tempfile::tempdir().unwrap();
for i in 0..30 {
write(dir.path(), &[&format!("m{i}"), "nul"], "");
}
assert_eq!(reserved_entries(dir.path()).len(), MAX_REPORTED);
remove(dir);
}
}
+112 -24
Переглянути файл
@@ -16,6 +16,7 @@ mod handler;
mod inspect;
pub mod jdtls;
mod launch;
mod library_source;
mod scope;
mod server;
mod tcp;
@@ -273,6 +274,30 @@ impl<T> Outcome<T> {
/// Implementation requests of one line-marker pass in flight at once.
const IMPLEMENTATION_CONCURRENCY: usize = 4;
/// Library classes in `jar:` targets (the official Kotlin LSP) go to their source
/// in the artifact's sources jar when it is cached, at the declaration of the
/// name navigated from; [`LspManager::virtual_document`] serves it.
async fn library_sources(snap: &DocSnap, pos: Pos, locs: Vec<Location>) -> Vec<Location> {
if !locs.iter().any(|l| l.uri.as_deref().is_some_and(|u| u.starts_with("jar:") && u.ends_with(".class"))) {
return locs;
}
let name = library_source::identifier_at(snap.text.line(pos.line as usize), pos.col).map(str::to_owned);
tokio::task::spawn_blocking(move || {
locs.into_iter()
.map(|loc| {
let Some(uri) = loc.uri.as_deref().filter(|u| u.starts_with("jar:") && u.ends_with(".class")) else {
return loc;
};
let Some((source, text)) = library_source::class_source(uri) else { return loc };
let range = name.as_deref().map(|n| library_source::declaration_range(&text, n)).unwrap_or_default();
Location { path: source.clone().into(), range, uri: Some(source) }
})
.collect()
})
.await
.unwrap_or_default()
}
fn goto_method(kind: GotoKind) -> (&'static str, &'static str, &'static str) {
match kind {
GotoKind::Definition => ("textDocument/definition", "definitionProvider", "go to definition"),
@@ -1187,6 +1212,7 @@ impl LspManager {
{
Ok(Some(r)) => {
let locs = convert::goto_response(&self.conv(t.enc()), r);
let locs = library_sources(snap, pos, locs).await;
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
if !locs.is_empty() {
return Ok(locs);
@@ -2218,12 +2244,35 @@ impl LspManager {
/// Contents of a virtual document, from the server that owns `uri`:
/// `workspace/textDocumentContent` (LSP 3.18) when the server serves the
/// scheme, jdtls' `java/classFileContents` for `jdt:` URIs. Cached.
/// scheme, jdtls' `java/classFileContents` for `jdt:` URIs. A `jar:` entry
/// is read from its archive, a `jar:` class shown as its library source
/// (see [`library_source`]) or else decompiled by the server. Cached.
pub async fn virtual_document(&self, uri: &str) -> IdeResult<VirtualDocument> {
if let Some(d) = self.virtual_docs.lock().get(uri) {
return Ok(d.clone());
}
let scheme = virtual_doc::scheme(uri).to_owned();
let jar_class = scheme == "jar" && library_source::parse(uri).is_some_and(|e| e.entry.ends_with(".class"));
if scheme == "jar" {
let found = {
let uri = uri.to_owned();
tokio::task::spawn_blocking(move || match library_source::parse(&uri) {
Some(e) if !e.entry.ends_with(".class") => {
library_source::read_entry(&e.jar, &e.entry).map(|text| (e.entry, text))
}
Some(_) => library_source::class_source(&uri)
.and_then(|(source, text)| Some((library_source::parse(&source)?.entry, text))),
None => None,
})
.await
.ok()
.flatten()
};
if let Some((entry, text)) = found {
let title = entry.rsplit('/').next().unwrap_or(&entry).to_owned();
return Ok(self.store_virtual(uri, text, Some(title), &[], self.origin_server(uri).map(|s| s.id)));
}
}
let class_file = scheme == "jdt" || (scheme == "file" && uri.ends_with(".class"));
let origin = self.origin_server(uri);
let mut servers: Vec<Arc<Server>> = origin.iter().cloned().collect();
@@ -2246,6 +2295,25 @@ impl LspManager {
} else if class_file && languages.iter().any(|l| l.as_str() == "java") {
self.call::<_, Option<String>>(t, "java/classFileContents", json!({ "uri": uri }), None, LONG_TIMEOUT)
.await
} else if jar_class && t.caps().commands().iter().any(|c| c == "decompile") {
// The official Kotlin LSP: `decompile` answers `{ code, language }`.
self.call::<_, Option<Value>>(
t,
"workspace/executeCommand",
json!({ "command": "decompile", "arguments": [uri] }),
None,
LONG_TIMEOUT,
)
.await
.map(|v| {
v.and_then(|v| match v {
Value::String(text) => Some(text),
v => ["code", "text", "content"]
.iter()
.find_map(|k| v.get(k).and_then(Value::as_str))
.map(str::to_owned),
})
})
} else {
continue;
};
@@ -2257,33 +2325,53 @@ impl LspManager {
continue;
}
};
let decompiled = virtual_doc::is_decompiled(&text);
let title = virtual_doc::title(uri, decompiled);
let detected = self.languages.detect(Path::new(&title), None);
let language_id = if detected == LanguageId::plain_text() {
languages.first().cloned().unwrap_or(detected)
} else {
detected
};
let doc = VirtualDocument {
uri: uri.to_owned(),
text,
language_id,
title,
description: virtual_doc::description(uri),
decompiled,
};
self.virtual_origins.lock().entry(uri.to_owned()).or_insert(t.server.id);
let mut cache = self.virtual_docs.lock();
if cache.len() >= VIRTUAL_CACHE_LIMIT {
cache.clear();
}
cache.insert(uri.to_owned(), doc.clone());
return Ok(doc);
return Ok(self.store_virtual(uri, text, None, &languages, Some(t.server.id)));
}
if jar_class && error.is_none() {
return Err(IdeError::not_found(format!(
"no source or decompiler is available for {}: its sources jar is not in the local Maven or Gradle cache, and no language server decompiles it",
virtual_doc::title(uri, false)
)));
}
Err(error.unwrap_or_else(|| IdeError::not_found(format!("no language server provides the contents of {uri}"))))
}
/// Caches `text` as the virtual document `uri`, titled `title` (else after the URI).
fn store_virtual(
&self,
uri: &str,
text: String,
title: Option<String>,
languages: &[LanguageId],
server: Option<ide_core::ServerId>,
) -> VirtualDocument {
let decompiled = virtual_doc::is_decompiled(&text);
let title = title.unwrap_or_else(|| virtual_doc::title(uri, decompiled));
let detected = self.languages.detect(Path::new(&title), None);
let language_id = if detected == LanguageId::plain_text() {
languages.first().cloned().unwrap_or(detected)
} else {
detected
};
let doc = VirtualDocument {
uri: uri.to_owned(),
text,
language_id,
title,
description: virtual_doc::description(uri),
decompiled,
};
if let Some(server) = server {
self.virtual_origins.lock().entry(uri.to_owned()).or_insert(server);
}
let mut cache = self.virtual_docs.lock();
if cache.len() >= VIRTUAL_CACHE_LIMIT {
cache.clear();
}
cache.insert(uri.to_owned(), doc.clone());
doc
}
/// Called when a server sends `workspace/applyEdit`; installed by `src-tauri`
/// so edits flow through `ide-workspace::Documents`.
pub fn set_config_hook(&self, hook: Box<ConfigFn>) {
+299
Переглянути файл
@@ -0,0 +1,299 @@
//! `jar:` URIs (`jar:///…/lib.jar!/pkg/Name.class`, also `jar:file:///…`) that
//! language servers return for library code: the official Kotlin LSP for the
//! classes of a dependency, Metals and others for entries of a sources jar.
//! Not every server can serve their contents (`workspace/textDocumentContent`),
//! so they are read here, where the jars are (also on a remote backend): an
//! entry as is, a class as its source from the artifact's `-sources.jar` next to
//! it in the Maven or Gradle cache.
use ide_core::{Pos, Range};
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use std::io::Read;
use std::path::{Path, PathBuf};
/// An entry of an archive named by a `jar:` URI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct JarEntry {
/// The URI up to the archive path (`jar:///` or `jar:file:///`), kept for new URIs.
prefix: String,
pub jar: PathBuf,
/// `/`-separated, without a leading `/`.
pub entry: String,
}
pub(crate) fn parse(uri: &str) -> Option<JarEntry> {
let rest = uri.strip_prefix("jar:")?;
let (archive, entry) = rest.split_once("!/")?;
let (prefix, path) = if let Some(path) = archive.strip_prefix("file://") {
("jar:file://", path)
} else if let Some(path) = archive.strip_prefix("//") {
("jar://", path)
} else {
("jar:", archive)
};
let path = percent_decode_str(path).decode_utf8().ok()?;
let path = if cfg!(windows) {
// `/C:/x` → `C:\x`
let trimmed = path.strip_prefix('/').filter(|s| s.as_bytes().get(1) == Some(&b':')).unwrap_or(&path);
PathBuf::from(trimmed.replace('/', "\\"))
} else {
PathBuf::from(path.into_owned())
};
let entry = percent_decode_str(entry.split(['?', '#']).next().unwrap_or(entry)).decode_utf8().ok()?;
Some(JarEntry { prefix: prefix.to_owned(), jar: path, entry: entry.trim_start_matches('/').to_owned() })
}
const PATH: &AsciiSet = &CONTROLS.add(b' ').add(b'#').add(b'%').add(b'?').add(b'!');
impl JarEntry {
/// The URI of `entry` in `jar`, written like the URI this one came from.
fn uri_of(&self, jar: &Path, entry: &str) -> String {
let mut path = jar.to_string_lossy().replace('\\', "/");
if !path.starts_with('/') {
path.insert(0, '/');
}
let encode = |s: &str| utf8_percent_encode(s, PATH).to_string();
format!("{}{}!/{}", self.prefix, encode(&path), encode(entry))
}
}
/// The text of `entry` in the archive `jar`, when it is a UTF-8 file.
pub(crate) fn read_entry(jar: &Path, entry: &str) -> Option<String> {
let mut zip = zip::ZipArchive::new(std::fs::File::open(jar).ok()?).ok()?;
let mut file = zip.by_name(entry).ok()?;
let mut text = String::new();
file.read_to_string(&mut text).ok()?;
Some(text)
}
/// The library source for a class entry: its `.kt` / `.java` file in the
/// artifact's sources jar, as `(uri, text)`.
pub(crate) fn class_source(uri: &str) -> Option<(String, String)> {
let jar = parse(uri)?;
let class = jar.entry.strip_suffix(".class")?;
for sources in sources_jars(&jar.jar) {
if let Some((entry, text)) = source_entry(&sources, class) {
return Some((jar.uri_of(&sources, &entry), text));
}
}
None
}
/// Sources jars of the artifact `jar`: `<name>-sources.jar` next to it (Maven
/// repository), or in a sibling hash folder (Gradle `files-2.1/<g>/<a>/<v>/<hash>/`).
fn sources_jars(jar: &Path) -> Vec<PathBuf> {
let (Some(dir), Some(stem)) = (jar.parent(), jar.file_stem().and_then(|s| s.to_str())) else { return vec![] };
let name = format!("{stem}-sources.jar");
let mut out: Vec<PathBuf> = vec![dir.join(&name)];
if let Some(version_dir) = dir.parent()
&& version_dir.ancestors().any(|a| a.file_name().is_some_and(|n| n == "files-2.1"))
&& let Ok(entries) = std::fs::read_dir(version_dir)
{
out.extend(entries.flatten().map(|e| e.path().join(&name)));
}
out.retain(|p| p.is_file());
out
}
/// The source file of `class` (`pkg/Name`, `pkg/Outer$Inner`, `pkg/FileKt`) in `sources`.
fn source_entry(sources: &Path, class: &str) -> Option<(String, String)> {
let mut zip = zip::ZipArchive::new(std::fs::File::open(sources).ok()?).ok()?;
let (package, name) = class.rsplit_once('/').unwrap_or(("", class));
let outer = name.split('$').next().unwrap_or(name);
let dir = if package.is_empty() { String::new() } else { format!("{package}/") };
let mut candidates = vec![format!("{dir}{outer}.java"), format!("{dir}{outer}.kt")];
// Top-level Kotlin declarations compile to a `<File>Kt` facade class.
if let Some(file) = outer.strip_suffix("Kt").filter(|f| !f.is_empty()) {
candidates.push(format!("{dir}{file}.kt"));
}
let read = |zip: &mut zip::ZipArchive<std::fs::File>, entry: &str| {
let mut text = String::new();
zip.by_name(entry).ok()?.read_to_string(&mut text).ok()?;
Some(text)
};
for entry in &candidates {
if let Some(text) = read(&mut zip, entry) {
return Some((entry.clone(), text));
}
}
// A facade renamed with `@file:JvmName("…")`.
let kotlin_files: Vec<String> = zip
.file_names()
.filter_map(|n| n.ok().map(|n| n.into_owned()))
.filter(|n| n.ends_with(".kt") && n.strip_prefix(&dir).is_some_and(|rest| !rest.contains('/')))
.collect();
let jvm_name = format!("@file:JvmName(\"{outer}\")");
for entry in kotlin_files {
if let Some(text) = read(&mut zip, &entry)
&& text.contains(&jvm_name)
{
return Some((entry, text));
}
}
None
}
/// Where `name` is declared in a Kotlin or Java source `text` (the start of the
/// name), else the start of the file.
pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
const KEYWORDS: [&str; 9] = ["fun", "class", "interface", "object", "val", "var", "typealias", "enum", "record"];
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
let mut fallback = None;
for (line_no, line) in text.lines().enumerate() {
let mut from = 0;
while let Some(i) = line[from..].find(name) {
let start = from + i;
let end = start + name.len();
from = end;
let before = line[..start].chars().next_back();
let after = line[end..].chars().next();
if before.is_some_and(is_ident) || after.is_some_and(is_ident) {
continue;
}
let head = &line[..start];
let words: Vec<&str> = head.split(|c: char| !is_ident(c)).filter(|w| !w.is_empty()).collect();
let col = head.encode_utf16().count() as u32;
let range = Range {
start: Pos::new(line_no as u32, col),
end: Pos::new(line_no as u32, col + name.encode_utf16().count() as u32),
};
// Kotlin: `fun <T> Foo.name(`, `class Name`; Java: `… Type name(`.
if words.iter().any(|w| KEYWORDS.contains(w)) {
return range;
}
let java_member =
after == Some('(') && !head.trim_end().ends_with('.') && !head.trim().is_empty() && !head.contains('=');
if java_member && fallback.is_none() {
fallback = Some(range);
}
}
}
fallback.unwrap_or_default()
}
/// The identifier around `col` (UTF-16) of `line`.
pub(crate) fn identifier_at(line: &str, col: u32) -> Option<&str> {
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
let mut utf16 = 0u32;
let mut at = line.len();
for (i, c) in line.char_indices() {
if utf16 >= col {
at = i;
break;
}
utf16 += c.len_utf16() as u32;
}
let start =
line[..at].rfind(|c: char| !is_ident(c)).map_or(0, |i| i + line[i..].chars().next().map_or(1, char::len_utf8));
let end = line[at..].find(|c: char| !is_ident(c)).map_or(line.len(), |i| at + i);
let word = &line[start..end];
(!word.is_empty() && !word.starts_with(|c: char| c.is_ascii_digit())).then_some(word)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn jar(path: &Path, entries: &[(&str, &str)]) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut zip = zip::ZipWriter::new(std::fs::File::create(path).unwrap());
for (name, text) in entries {
zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(text.as_bytes()).unwrap();
}
zip.finish().unwrap();
}
const EXTENSIONS: &str = "package org.springframework.boot\n\nimport kotlin.reflect.KClass\n\n/**\n * Top-level function acting as a Kotlin shortcut allowing to write\n * `runApplication<Foo>(arg1, arg2)` instead of `SpringApplication.run(Foo::class.java, arg1, arg2)`.\n */\ninline fun <reified T : Any> runApplication(vararg args: String): ConfigurableApplicationContext =\n\t\tSpringApplication.run(T::class.java, *args)\n";
#[test]
fn parses_both_jar_uri_forms() {
for uri in [
"jar:///home/me/.m2/repository/b/spring-boot-3.5.16.jar!/org/springframework/boot/SpringApplicationExtensionsKt.class",
"jar:file:///home/me/.m2/repository/b/spring-boot-3.5.16.jar!/org/springframework/boot/SpringApplicationExtensionsKt.class",
] {
let e = parse(uri).unwrap();
if !cfg!(windows) {
assert_eq!(e.jar, PathBuf::from("/home/me/.m2/repository/b/spring-boot-3.5.16.jar"));
}
assert_eq!(e.entry, "org/springframework/boot/SpringApplicationExtensionsKt.class");
assert_eq!(e.uri_of(&e.jar, &e.entry), uri, "written back the same way");
}
let spaced = parse("jar:///tmp/my%20libs/a.jar!/A.class").unwrap();
assert!(spaced.jar.to_string_lossy().contains("my libs"));
assert_eq!(spaced.uri_of(&spaced.jar, "A.kt"), "jar:///tmp/my%20libs/a.jar!/A.kt");
assert_eq!(parse("jdt://contents/a.jar/A.class"), None);
assert_eq!(parse("jar:///no/entry.jar"), None);
}
#[test]
fn finds_the_source_of_each_kind_of_class_in_maven_and_gradle_caches() {
let tmp = tempfile::tempdir().unwrap();
let m2 = tmp.path().join("m2/org/springframework/boot/spring-boot/3.5.16");
let gradle = tmp.path().join("gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/3.5.16");
let sources: &[(&str, &str)] = &[
("org/springframework/boot/SpringApplicationExtensions.kt", EXTENSIONS),
("org/springframework/boot/SpringApplication.java", "public class SpringApplication {}"),
(
"org/springframework/boot/Renamed.kt",
"@file:JvmName(\"BootUtils\")\npackage org.springframework.boot\nfun util() {}",
),
("org/springframework/boot/Builder.kt", "class Builder"),
("Root.java", "class Root {}"),
];
jar(&m2.join("spring-boot-3.5.16.jar"), &[]);
jar(&m2.join("spring-boot-3.5.16-sources.jar"), sources);
// Gradle keeps each file under its own hash folder.
jar(&gradle.join("aaa/spring-boot-3.5.16.jar"), &[]);
jar(&gradle.join("bbb/spring-boot-3.5.16-sources.jar"), sources);
for binary in [m2.join("spring-boot-3.5.16.jar"), gradle.join("aaa/spring-boot-3.5.16.jar")] {
let uri = |class: &str| format!("jar://{}!/{class}", binary.to_string_lossy().replace('\\', "/"));
for (class, file) in [
("org/springframework/boot/SpringApplicationExtensionsKt.class", "SpringApplicationExtensions.kt"),
("org/springframework/boot/SpringApplication.class", "SpringApplication.java"),
("org/springframework/boot/SpringApplication$Running.class", "SpringApplication.java"),
("org/springframework/boot/BootUtils.class", "Renamed.kt"),
("org/springframework/boot/Builder.class", "Builder.kt"),
("Root.class", "Root.java"),
] {
let (source_uri, text) = class_source(&uri(class)).unwrap_or_else(|| panic!("{class} in {binary:?}"));
let dir = class.rsplit_once('/').map_or(String::new(), |(p, _)| format!("{p}/"));
assert!(source_uri.ends_with(&format!("-sources.jar!/{dir}{file}")), "{source_uri}");
assert_eq!(
parse(&source_uri).and_then(|e| read_entry(&e.jar, &e.entry)).as_deref(),
Some(text.as_str())
);
}
assert_eq!(class_source(&uri("org/springframework/boot/Missing.class")), None);
}
// No sources jar: nothing to show from here.
let lone = tmp.path().join("lone/x-1.jar");
jar(&lone, &[]);
assert_eq!(class_source(&format!("jar://{}!/X.class", lone.to_string_lossy().replace('\\', "/"))), None);
}
#[test]
fn locates_declarations_in_kotlin_and_java_sources() {
let at = |text: &str, name: &str| {
let r = declaration_range(text, name);
(r.start.line, r.start.col, r.end.col)
};
assert_eq!(at(EXTENSIONS, "runApplication"), (8, 29, 43), "the declaration, not the KDoc mention");
let java = "package a;\n\npublic class SpringApplication {\n public static ConfigurableApplicationContext run(Class<?> source, String... args) {\n return run(new Class<?>[] { source }, args);\n }\n}\n";
assert_eq!(at(java, "SpringApplication"), (2, 13, 30));
assert_eq!(at(java, "run"), (3, 49, 52), "the member, not the call in its body");
assert_eq!(at("val x = 1", "missing"), (0, 0, 0));
assert_eq!(at("// é\nfun ü() {}", "ü"), (1, 4, 5), "UTF-16 columns");
}
#[test]
fn identifier_under_the_caret() {
let line = " runApplication<Application>(*args)";
assert_eq!(identifier_at(line, 4), Some("runApplication"));
assert_eq!(identifier_at(line, 10), Some("runApplication"));
assert_eq!(identifier_at(line, 18), Some("runApplication"), "right after it");
assert_eq!(identifier_at(line, 20), Some("Application"));
assert_eq!(identifier_at("a + b", 2), None);
}
}
+3
Переглянути файл
@@ -60,6 +60,9 @@ pub fn title(uri: &str, decompiled: bool) -> String {
/// Where the document comes from, e.g. the jar path of a `jdt://` class.
pub fn description(uri: &str) -> Option<String> {
if scheme(uri) == "jar" {
return crate::library_source::parse(uri).map(|e| e.jar.to_string_lossy().into_owned());
}
if scheme(uri) != "jdt" {
return None;
}
+211 -1
Переглянути файл
@@ -1166,6 +1166,139 @@ async fn unmanaged_java_run_imports_sources_without_an_open_editor() {
assert!(state.notified("textDocument/didOpen").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn java_launch_serializes_the_classpath_with_the_build_lock() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let (_, _file) = h.open("Main.java", "public class Main {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
state.respond("java/buildWorkspace", json!(1));
// A launch with a build re-takes the lock after java_build has released it.
let info = tokio::time::timeout(
Duration::from_secs(30),
h.mgr.java_launch(&h.root, false, true, false, &Default::default()),
)
.await
.expect("java_launch deadlocked on the build lock")
.unwrap();
assert!(info.class_paths.is_empty());
// The delegated external build holds the lock while java_launch resolves the
// classpath; java_launch must not re-take it, or the launch would deadlock.
let guard = h.mgr.java_external_build(&h.root, &Default::default()).await.unwrap();
tokio::time::timeout(Duration::from_secs(30), h.mgr.java_launch(&h.root, false, false, true, &Default::default()))
.await
.expect("java_launch deadlocked on the delegated external build's lock")
.unwrap();
drop(guard);
let commands: Vec<_> = state
.requested("workspace/executeCommand")
.iter()
.filter_map(|p| p["command"].as_str().map(str::to_owned))
.collect();
assert!(commands.contains(&"java.project.getClasspaths".to_owned()));
}
#[tokio::test(flavor = "multi_thread")]
async fn open_java_files_are_checked_again_after_a_project_update() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let (_, a) = h.open("A.java", "class A {}");
let (_, b) = h.open("B.java", "class B {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
let refreshed = || {
let mut uris: Vec<Value> = state
.requested("workspace/executeCommand")
.iter()
.filter(|p| p["command"] == "java.project.refreshDiagnostics")
.map(|p| {
assert_eq!(p["arguments"][1], "thisFile");
p["arguments"][0].clone()
})
.collect();
uris.sort_by_key(|u| u.to_string());
uris
};
// Other status messages leave the documents alone.
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(refreshed().is_empty());
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
let mut expected = vec![json!(uri_of(&a)), json!(uri_of(&b))];
expected.sort_by_key(|u| u.to_string());
eventually(|| refreshed() == expected).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn library_classes_in_jars_open_as_their_source_or_decompiled() {
use std::io::Write;
let jar = |path: &Path, entries: &[(&str, &str)]| {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut zip = zip::ZipWriter::new(std::fs::File::create(path).unwrap());
for (name, text) in entries {
zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(text.as_bytes()).unwrap();
}
zip.finish().unwrap();
};
let repo = tempfile::tempdir().unwrap();
let dir = repo.path().join("org/springframework/boot/spring-boot/3.5.16");
let source = "package org.springframework.boot\n\ninline fun <reified T : Any> runApplication(vararg args: String) =\n SpringApplication.run(T::class.java, *args)\n";
jar(
&dir.join("spring-boot-3.5.16.jar"),
&[("org/springframework/boot/SpringApplicationExtensionsKt.class", "\u{0}")],
);
jar(
&dir.join("spring-boot-3.5.16-sources.jar"),
&[("org/springframework/boot/SpringApplicationExtensions.kt", source)],
);
let other = repo.path().join("acme/lib/1.0/lib-1.0.jar");
jar(&other, &[("acme/Thing.class", "\u{0}")]);
let jar_uri = |jar: &Path, entry: &str| format!("jar://{}!/{entry}", uri_of(jar).trim_start_matches("file://"));
let r = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}});
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({ "commands": ["decompile"] });
let h = harness_for("kotlin", "kt", &[("kotlin-lsp", caps)], &[]);
let (doc, _) = h.open("Main.kt", "fun main(args: Array<String>) {\n runApplication<App>(*args)\n}\n");
h.wait_status("kotlin-lsp", ServerStatus::Ready).await;
let s = h.launcher.state("kotlin-lsp");
// A class with a cached sources jar: navigation lands on the declaration in its source.
let class =
jar_uri(&dir.join("spring-boot-3.5.16.jar"), "org/springframework/boot/SpringApplicationExtensionsKt.class");
s.respond("textDocument/definition", json!({ "uri": class, "range": r(7, 43, 57) }));
let defs = h.mgr.goto(doc, Pos::new(1, 8), GotoKind::Definition).await.unwrap();
let sources =
jar_uri(&dir.join("spring-boot-3.5.16-sources.jar"), "org/springframework/boot/SpringApplicationExtensions.kt");
assert_eq!(
defs,
vec![ide_core::Location { path: sources.clone().into(), range: rng(2, 29, 2, 43), uri: Some(sources.clone()) }]
);
let vd = h.mgr.virtual_document(&sources).await.unwrap();
assert_eq!((vd.text.as_str(), vd.title.as_str(), vd.decompiled), (source, "SpringApplicationExtensions.kt", false));
assert_eq!(vd.language_id.as_str(), "kotlin");
// The class URI itself (from usages, say) shows the same source.
assert_eq!(h.mgr.virtual_document(&class).await.unwrap().text, source);
assert!(s.requested("workspace/executeCommand").is_empty(), "no server round trip for cached sources");
// No sources jar: the server's `decompile` command.
let thing = jar_uri(&other, "acme/Thing.class");
s.respond("textDocument/definition", json!({ "uri": thing, "range": r(0, 6, 11) }));
let defs = h.mgr.goto(doc, Pos::new(1, 8), GotoKind::Definition).await.unwrap();
assert_eq!(defs[0].uri.as_deref(), Some(thing.as_str()), "kept as the server returned it");
s.respond("workspace/executeCommand", json!({ "code": "package acme\n\nclass Thing", "language": "kotlin" }));
let vd = h.mgr.virtual_document(&thing).await.unwrap();
assert_eq!(vd.text, "package acme\n\nclass Thing");
let asked = s.requested("workspace/executeCommand");
assert_eq!(asked[0], json!({ "command": "decompile", "arguments": [thing] }));
}
#[tokio::test(flavor = "multi_thread")]
async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
// Preferred installed: the alternative is never started.
@@ -3001,7 +3134,84 @@ async fn configuration_extension_failure_preserves_native_java_navigation() {
"start": {"line": 0, "character": 1}, "end": {"line": 0, "character": 6}
}}),
);
let result = h.mgr.goto(doc, Pos::new(0, 2), GotoKind::Definition).await.unwrap();
let result = h.mgr.goto(doc, Pos::new(0, 12), GotoKind::Definition).await.unwrap();
assert_eq!(result.len(), 1);
assert_eq!(s.requested("workspace/executeCommand").len(), 1);
assert_eq!(s.requested("textDocument/definition").len(), 1);
}
/// The configuration command indexes the whole project, so Go to Definition (and
/// every Ctrl+hover probe) consults it only inside a key argument; ordinary Java
/// symbols in a Spring file go straight to JDT.
#[tokio::test(flavor = "multi_thread")]
async fn java_definition_consults_configuration_only_inside_key_arguments() {
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.configuration"]});
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
let s = h.launcher.state("jdtls");
let text = "class A {\n @Value(\"${app.port}\") int port;\n String a() { return env.getProperty(Keys.HOST) + x.getValue(); }\n}\n";
let (doc, path) = h.open("A.java", text);
h.wait_status("jdtls", ServerStatus::Ready).await;
s.respond("workspace/executeCommand", json!({"locations": [], "keys": [], "roots": []}));
s.respond(
"textDocument/definition",
json!({"uri": uri_of(&path), "range": {
"start": {"line": 0, "character": 6}, "end": {"line": 0, "character": 7}
}}),
);
// Field type, field name, method name, the lookup's receiver and name, another call.
for pos in [Pos::new(1, 24), Pos::new(1, 28), Pos::new(2, 9), Pos::new(2, 22), Pos::new(2, 28), Pos::new(2, 53)] {
assert_eq!(h.mgr.goto(doc, pos, GotoKind::Definition).await.unwrap().len(), 1, "{pos:?}");
}
assert!(s.requested("workspace/executeCommand").is_empty());
assert_eq!(s.requested("textDocument/definition").len(), 6);
// Inside a placeholder and a constant lookup key: configuration first, JDT as fallback.
for pos in [Pos::new(1, 13), Pos::new(2, 41)] {
h.mgr.goto(doc, pos, GotoKind::Definition).await.unwrap();
}
assert_eq!(s.requested("workspace/executeCommand").len(), 2);
}
/// JDT LS aborts its Maven import on Windows when the project holds a file with a
/// reserved device name (`nul` left by `2>nul`); the error names those files there
/// and stays silent elsewhere, where such names are ordinary files.
#[tokio::test(flavor = "multi_thread")]
async fn jdtls_import_failure_names_reserved_device_files_on_windows() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let s = h.launcher.state("jdtls");
std::fs::write(h.root.join("pom.xml"), "<project/>").unwrap();
// A file named `nul` cannot be created through the Win32 namespace; on Windows use the verbatim path.
let nul = if cfg!(windows) && !h.root.to_string_lossy().starts_with(r"\\?\") {
PathBuf::from(format!(r"\\?\{}", h.root.join("nul").display()))
} else {
h.root.join("nul")
};
std::fs::write(&nul, "54 bytes").unwrap();
h.open("A.java", "class A {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let failure = "Initialization failed | java.lang.IllegalArgumentException: Path must include project and resource name: /demo | at UnifiedTree.createChildNodeFromFileSystem(UnifiedTree.java:320)";
for _ in 0..2 {
s.peer().notify("window/logMessage", json!({ "type": 1, "message": failure })).unwrap();
}
s.peer().notify("window/showMessage", json!({ "type": 2, "message": "after" })).unwrap();
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b == "after")))
.await;
// The scan runs off the RPC thread; give it time to report.
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let failures: Vec<String> = h
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Notify { title, body: Some(b), .. } if title == "Java project import failed" => Some(b.clone()),
_ => None,
})
.collect();
if cfg!(windows) {
assert_eq!(failures.len(), 1, "reported once: {failures:?}");
assert!(failures[0].contains("nul"), "{failures:?}");
} else {
assert!(failures.is_empty(), "{failures:?}");
}
let _ = std::fs::remove_file(&nul);
}
+40
Переглянути файл
@@ -250,6 +250,46 @@ async fn ruff_next_to_basedpyright_end_to_end() {
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires pyrefly on PATH"]
async fn pyrefly_python_end_to_end() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let path = root.join("example.py");
let source = "def greet(name: str) -> str:\n return name\n\nresult = greet('Ada')\nbad: int = 'wrong'\n";
std::fs::write(&path, source).unwrap();
// Pyrefly only reports type errors in projects with a Pyrefly configuration.
std::fs::write(root.join("pyrefly.toml"), "").unwrap();
let mut python = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("python")).unwrap();
python.language_servers.retain(|server| server.name == "pyrefly");
assert_eq!(python.language_servers.len(), 1);
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![python]));
let doc = DocId::next();
mgr.did_open(doc, &path, &LanguageId::new("python"), 1, source);
retry("pyrefly ready", Duration::from_secs(30), || {
let status = last_status(&events, "pyrefly");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
panic!("pyrefly failed: {msg:?}");
}
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
let defs = retry("pyrefly definition", Duration::from_secs(30), || {
let mgr = mgr.clone();
async move { mgr.goto(doc, Pos::new(3, 10), GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
})
.await;
assert_eq!(defs[0].path, path);
assert_eq!(defs[0].range.start.line, 0);
retry("pyrefly diagnostics", Duration::from_secs(30), || {
let found = events.lock().iter().any(
|event| matches!(event, IdeEvent::Diagnostics { source, items, .. } if source == "pyrefly" && !items.is_empty()),
);
async move { found.then_some(()) }
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires rust-analyzer"]
async fn rust_analyzer_end_to_end() {
+2 -3
Переглянути файл
@@ -15,8 +15,7 @@ toml.workspace = true
thiserror.workspace = true
tracing.workspace = true
parking_lot.workspace = true
tempfile.workspace = true
zip.workspace = true
wasmtime = { version = "49.0.4", default-features = false, features = ["runtime", "cranelift", "component-model", "std", "parallel-compilation"] }
wasmtime-wasi = { version = "49.0.4", default-features = false, features = ["p2"] }
[dev-dependencies]
tempfile.workspace = true
+15
Переглянути файл
@@ -15,6 +15,7 @@
//! (dev plugins, loaded by [`PluginHost::sync_project`]).
mod manifest;
mod package;
mod runtime;
mod sandbox;
mod theme;
@@ -263,6 +264,20 @@ impl PluginHost {
self.info_of(&new_id)
}
/// Installs the package at `path`: a folder, its `plugin.toml`, or a `.zip` of the folder.
pub fn install_from_path(&self, path: &Path) -> IdeResult<PluginInfo> {
if package::is_zip(path) && path.is_file() {
// Outside the plugins directory: a crash must not leave a package that loads.
let unpacked = tempfile::Builder::new().prefix("openidea-plugin-").tempdir()?;
let root = package::unpack_zip(path, unpacked.path())?;
return self.install_from_dir(&root);
}
if path.file_name().is_some_and(|name| name == MANIFEST_FILE) && path.is_file() {
return self.install_from_dir(path.parent().unwrap_or(path));
}
self.install_from_dir(path)
}
/// Copies a plugin package (manifest + referenced files) into the plugins
/// directory, replacing an installed version with the same id.
pub fn install_from_dir(&self, src: &Path) -> IdeResult<PluginInfo> {
+74
Переглянути файл
@@ -0,0 +1,74 @@
//! Plugin packages on disk: a folder, its `plugin.toml`, or a `.zip` of the folder.
use crate::MANIFEST_FILE;
use ide_core::{IdeError, IdeResult};
use std::fs::{self, File};
use std::io::{self, BufReader, Read};
use std::path::{Path, PathBuf};
/// Far above any real package; stops a zip bomb before it fills the disk.
const MAX_ENTRIES: usize = 10_000;
const MAX_UNPACKED_BYTES: u64 = 1024 * 1024 * 1024;
pub(crate) fn is_zip(path: &Path) -> bool {
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip"))
}
fn invalid_zip(zip: &Path, reason: impl std::fmt::Display) -> IdeError {
IdeError::invalid(format!("{} is not a valid plugin archive: {reason}", zip.display()))
}
/// Unpacks `zip` into `dest` and returns the package folder inside it. Refuses the
/// whole archive when an entry would leave `dest` or is a symbolic link.
pub(crate) fn unpack_zip(zip: &Path, dest: &Path) -> IdeResult<PathBuf> {
let mut archive = zip::ZipArchive::new(BufReader::new(File::open(zip)?)).map_err(|e| invalid_zip(zip, e))?;
if archive.len() > MAX_ENTRIES {
return Err(invalid_zip(zip, format!("more than {MAX_ENTRIES} entries")));
}
let mut budget = MAX_UNPACKED_BYTES;
for i in 0..archive.len() {
let mut entry = archive.by_index(i).map_err(|e| invalid_zip(zip, e))?;
let name = entry.name().to_owned();
let Some(rel) = entry.enclosed_name() else {
return Err(invalid_zip(zip, format!("unsafe path {name:?}")));
};
if entry.is_symlink() {
return Err(invalid_zip(zip, format!("symbolic link {name:?}")));
}
let out = dest.join(rel);
if entry.is_dir() {
fs::create_dir_all(&out)?;
continue;
}
if let Some(parent) = out.parent() {
fs::create_dir_all(parent)?;
}
// One byte over the budget tells a full budget from a file that exactly fits.
let written =
io::copy(&mut (&mut entry).take(budget + 1), &mut File::create(&out)?).map_err(|e| invalid_zip(zip, e))?;
if written > budget {
return Err(invalid_zip(zip, "it unpacks to more than 1 GB"));
}
budget -= written;
}
package_root(dest).ok_or_else(|| {
IdeError::invalid(format!(
"{} is not an OpenIDEA plugin: no {MANIFEST_FILE} at its root or in its only folder",
zip.display()
))
})
}
/// `dir` itself, or its only folder as when a zip holds the package folder.
/// Archiver metadata (`__MACOSX`, dot files) does not count as a second folder.
fn package_root(dir: &Path) -> Option<PathBuf> {
if dir.join(MANIFEST_FILE).is_file() {
return Some(dir.to_path_buf());
}
let mut folders = fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).filter(|p| {
let name = p.file_name().unwrap_or_default().to_string_lossy();
p.is_dir() && !name.starts_with('.') && name != "__MACOSX"
});
let only = folders.next().filter(|_| folders.next().is_none())?;
only.join(MANIFEST_FILE).is_file().then_some(only)
}
+1 -1
Переглянути файл
@@ -89,7 +89,7 @@ pub struct CatalogPlugin {
pub authors: Vec<String>,
pub homepage: Option<String>,
pub change_notes: Option<String>,
/// Package directory; install with `install_from_dir(path)`.
/// Package directory; install with `install_from_path(path)`.
pub path: ide_core::IpcPath,
pub has_code: bool,
pub permissions: Vec<Permission>,
+91
Переглянути файл
@@ -8,6 +8,7 @@
use ide_plugin::*;
use parking_lot::Mutex;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
@@ -510,3 +511,93 @@ fn restricted_dev_plugin_has_no_activation_registration() {
f.host.sync_project(&f.project);
assert!(f.host.list(Some(&f.project)).plugins.is_empty());
}
/// Zips the files of `dir` under `prefix` (recursively).
fn add_dir(zip: &mut zip::ZipWriter<std::fs::File>, dir: &Path, prefix: &str) {
for entry in std::fs::read_dir(dir).unwrap().flatten() {
let name = format!("{prefix}{}", entry.file_name().to_string_lossy());
if entry.path().is_dir() {
add_dir(zip, &entry.path(), &format!("{name}/"));
} else {
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(&std::fs::read(entry.path()).unwrap()).unwrap();
}
}
}
fn zip_of(dir: &Path, prefix: &str, out: &Path) -> PathBuf {
let mut zip = zip::ZipWriter::new(std::fs::File::create(out).unwrap());
add_dir(&mut zip, dir, prefix);
zip.finish().unwrap();
out.to_path_buf()
}
#[test]
fn installs_zips_with_the_package_at_the_root_or_in_one_folder() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
for (name, prefix) in [("root.ZIP", ""), ("folder.zip", "hello-1.0/")] {
let zip = zip_of(&sample("hello"), prefix, &tmp.path().join(name));
let info = f.host.install_from_path(&zip).unwrap();
assert_eq!((info.id.as_str(), info.status), ("hello", PluginStatus::Active), "{:?}", info.error);
assert!(f.plugins_dir.join("hello/dist/plugin.wasm").is_file());
}
// Still runs from the installed copy, not the unpacked archive.
assert!(f.run("hello", "insert-date", None).unwrap().is_some());
}
#[test]
fn installs_from_a_manifest_or_a_folder() {
let f = fixture(Limits::default());
assert_eq!(f.host.install_from_path(&sample("hello").join("plugin.toml")).unwrap().id, "hello");
assert_eq!(f.host.install_from_path(&sample("hello")).unwrap().id, "hello");
}
#[test]
fn ignores_archiver_metadata_next_to_the_package_folder() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("mac.zip");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&out).unwrap());
add_dir(&mut zip, &sample("hello"), "hello/");
zip.start_file("__MACOSX/hello/._plugin.toml", zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(b"metadata").unwrap();
zip.finish().unwrap();
assert_eq!(f.host.install_from_path(&out).unwrap().id, "hello");
}
#[test]
fn refuses_zips_that_are_not_safe_plugin_packages() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let options = zip::write::SimpleFileOptions::default;
let no_manifest = tmp.path().join("idea-plugin.zip");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&no_manifest).unwrap());
zip.start_file("idea-plugin/lib/plugin.jar", options()).unwrap();
zip.finish().unwrap();
let error = f.host.install_from_path(&no_manifest).unwrap_err();
assert!(error.message.contains("no plugin.toml"), "{}", error.message);
let escape = tmp.path().join("escape.zip");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&escape).unwrap());
zip.start_file("../../evil.txt", options()).unwrap();
zip.write_all(b"evil").unwrap();
zip.finish().unwrap();
let error = f.host.install_from_path(&escape).unwrap_err();
assert!(error.message.contains("unsafe path"), "{}", error.message);
let link = tmp.path().join("link.zip");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&link).unwrap());
zip.add_symlink("plugin.toml", "/etc/passwd", options()).unwrap();
zip.finish().unwrap();
let error = f.host.install_from_path(&link).unwrap_err();
assert!(error.message.contains("symbolic link"), "{}", error.message);
let garbage = tmp.path().join("garbage.zip");
std::fs::write(&garbage, "not a zip").unwrap();
let error = f.host.install_from_path(&garbage).unwrap_err();
assert!(error.message.contains("not a valid plugin archive"), "{}", error.message);
assert!(!f.plugins_dir.join("hello").exists());
}
+128
Переглянути файл
@@ -33,6 +33,7 @@ pub(crate) fn detect_with_profiles(
detect_maven(root, excluded_poms, &mut out);
detect_go(root, &mut out);
detect_python(root, &mut out);
detect_ruby(root, &mut out);
cmake::detect(root, profiles, &mut out);
dotnet::detect(root, &mut out);
detect_make(root, &mut out);
@@ -905,6 +906,133 @@ fn detect_python(root: &Path, out: &mut Vec<RunConfig>) {
}
}
// ---------------------------------------------------------------------- ruby
/// Tasks a Rakefile defines statically: `task :name`, `task "name" => deps`,
/// `task name: [...]`, qualified by enclosing `namespace` blocks. `desc` lines are
/// skipped; a `Rake::TestTask` contributes `test`. `load`/`import`ed files are not followed.
pub(crate) fn rake_tasks(src: &str) -> Vec<String> {
let mut tasks = Vec::new();
let mut namespaces: Vec<String> = Vec::new();
let mut depth: Vec<bool> = Vec::new(); // per open block: whether it is a namespace
let name_of = |rest: &str| -> Option<String> {
let rest = rest.trim_start();
let (name, _) = if let Some(r) = rest.strip_prefix(':') {
r.split(|c: char| !(c.is_alphanumeric() || c == '_')).next().map(|n| (n.to_owned(), ()))?
} else if let Some(r) = rest.strip_prefix(['"', '\'']) {
r.split(['"', '\'']).next().map(|n| (n.to_owned(), ()))?
} else {
let n: String = rest.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
(!n.is_empty() && rest[n.len()..].starts_with(':')).then_some((n, ()))?
};
(!name.is_empty()).then_some(name)
};
for raw in src.lines() {
let line = raw.trim();
if line.starts_with('#') {
continue;
}
let opens = line.ends_with(" do") || line.contains(" do |") || line.contains(" do ") && !line.contains(" end");
if let Some(rest) = line.strip_prefix("namespace ")
&& let Some(ns) = name_of(rest)
{
namespaces.push(ns);
depth.push(true);
continue;
}
if let Some(rest) = line.strip_prefix("task ").or_else(|| line.strip_prefix("task("))
&& let Some(name) = name_of(rest)
{
let full = namespaces.iter().chain([&name]).cloned().collect::<Vec<_>>().join(":");
if !tasks.contains(&full) {
tasks.push(full);
}
}
if line.contains("Rake::TestTask.new") || line.contains("RSpec::Core::RakeTask.new") {
let name = name_of(line.split_once(".new").map(|(_, r)| r.trim_start_matches(['(', ' '])).unwrap_or(""))
.unwrap_or_else(|| if line.contains("RSpec") { "spec".into() } else { "test".into() });
let full = namespaces.iter().chain([&name]).cloned().collect::<Vec<_>>().join(":");
if !tasks.contains(&full) {
tasks.push(full);
}
}
if opens && !line.starts_with("namespace ") {
depth.push(false);
}
if (line == "end" || line.starts_with("end ") || line.starts_with("end#")) && depth.pop() == Some(true) {
namespaces.pop();
}
}
tasks
}
/// `bundle exec <tool>` when the project has a Gemfile, else the bare tool.
fn ruby_tool(root: &Path, tool: &str) -> (String, Vec<String>) {
if root.join("Gemfile").is_file() {
("bundle".into(), vec!["exec".into(), tool.into()])
} else {
(tool.into(), Vec::new())
}
}
fn ruby_config(
id: String,
name: String,
kind: &str,
(command, mut args): (String, Vec<String>),
extra: &[&str],
) -> RunConfig {
args.extend(extra.iter().map(|a| (*a).to_owned()));
let mut c = config(id, name, kind, &command, &[]);
c.args = args;
c
}
fn uses_rspec(root: &Path) -> bool {
root.join("spec").is_dir()
|| root.join(".rspec").is_file()
|| read(&root.join("Gemfile")).is_some_and(|g| g.contains("rspec"))
}
fn detect_ruby(root: &Path, out: &mut Vec<RunConfig>) {
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()) {
return;
}
if root.join("bin/rails").is_file() {
let mut c = ruby_config(
"rails:server".into(),
"rails server".into(),
"ruby",
("ruby".into(), Vec::new()),
&["bin/rails", "server"],
);
c.extras.folder = Some("Rails".into());
out.push(c);
}
if let Some(rakefile) = first_existing(root, &["Rakefile", "rakefile", "Rakefile.rb"])
&& let Some(src) = read(&rakefile)
{
for task in rake_tasks(&src) {
let mut c =
ruby_config(format!("rake:{task}"), format!("rake {task}"), "rake", ruby_tool(root, "rake"), &[&task]);
if task == "test" || task == "spec" || task.ends_with(":test") || task.ends_with(":spec") {
c = c.test();
}
c.extras.folder = Some("Rake".into());
out.push(c);
}
}
if uses_rspec(root) {
out.push(ruby_config("rspec".into(), "rspec".into(), "rspec", ruby_tool(root, "rspec"), &[]).test());
}
}
// ---------------------------------------------------------------- make / just
pub(crate) fn make_targets(src: &str) -> Vec<String> {
+66
Переглянути файл
@@ -728,3 +728,69 @@ fn cmake_profile_build_configures_only_without_a_cache() {
}
}
}
#[test]
fn ruby_projects_list_rake_tasks_rspec_and_rails() {
let rakefile = "\
require 'rake/testtask'
desc \"Build it\"
task :build do
sh 'make'
end
task \"lint\" => [:build]
task deploy: :build do |t|
puts t
end
namespace :db do
desc 'Migrate'
task :migrate, [:version] do |t, args|
puts args
end
namespace :schema do
task :load
end
end
Rake::TestTask.new do |t|
t.libs << 'test'
end
task default: :build
";
let dir = project(&[
("Gemfile", "source 'https://rubygems.org'\ngem 'rspec'\n"),
("Rakefile", rakefile),
("bin/rails", "#!/usr/bin/env ruby\n"),
("spec/a_spec.rb", ""),
]);
let c = detect(dir.path());
assert_eq!(
ids(&c),
[
"rails:server",
"rake:build",
"rake:lint",
"rake:deploy",
"rake:db:migrate",
"rake:db:schema:load",
"rake:test",
"rake:default",
"rspec"
]
);
assert_eq!(cmdline(find(&c, "rails:server")), "ruby bin/rails server");
assert_eq!(cmdline(find(&c, "rake:db:migrate")), "bundle exec rake db:migrate");
assert_eq!(find(&c, "rake:db:migrate").kind, "rake");
assert!(find(&c, "rake:test").is_test);
assert_eq!(cmdline(find(&c, "rspec")), "bundle exec rspec");
assert!(find(&c, "rspec").is_test);
assert_eq!(find(&c, "rake:build").extras.folder.as_deref(), Some("Rake"));
}
#[test]
fn ruby_without_bundler_runs_bare_tools() {
let dir = project(&[("Rakefile", "task :test\n")]);
let c = detect(dir.path());
assert_eq!(ids(&c), ["rake:test"]);
assert_eq!(cmdline(&c[0]), "rake test");
assert!(detect(project(&[("a.rb", "puts 1\n")]).path()).is_empty());
}
+69 -1
Переглянути файл
@@ -36,6 +36,12 @@ pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_python(root))
}
/// 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> {
setting_path(root, &s.languages.ruby.interpreter).or_else(|| crate::ruby::project_ruby(root))
}
/// The configured `node` executable's directory, else the `bin` of the Node.js the
/// project pins for mise / asdf.
pub(crate) fn node_dir(root: &Path, s: &Settings) -> Option<PathBuf> {
@@ -204,7 +210,7 @@ pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
}
}
const PYTHON_SERVERS: [&str; 6] = ["basedpyright", "pyright", "ty", "pylsp", "jedi-language-server", "ruff"];
const PYTHON_SERVERS: [&str; 7] = ["basedpyright", "pyright", "ty", "pyrefly", "pylsp", "jedi-language-server", "ruff"];
fn merge(base: &mut Value, layer: Value) {
match (base, layer) {
@@ -624,6 +630,7 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
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);
for c in configs.iter_mut() {
resolve_run_command(c, root, s);
@@ -709,6 +716,26 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
c.env.entry(key).or_insert(value);
}
}
"ruby" | "rake" | "rspec" => {
if let Some(ruby) = &ruby
&& let Some(bin) = crate::ruby::bin_dir_of(ruby)
{
// `ruby`, `bundle`, `rake`, `rspec` of the chosen interpreter when installed
// alongside it; the rest (a project `bin/rspec` binstub) stays as is.
let name = Path::new(&c.command).file_name().map(|n| n.to_string_lossy().into_owned());
if let Some(name) = name
&& matches!(name.as_str(), "ruby" | "bundle" | "rake" | "rspec" | "gem" | "irb")
&& !c.command.contains('/')
&& !c.command.contains('\\')
{
let exe = bin.join(exe(&name));
if exe.is_file() {
c.command = exe.to_string_lossy().into_owned();
}
}
path_dirs.push(bin);
}
}
"maven" | "tomcat" => {
if let Some(jdk) = &jdk {
c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());
@@ -742,6 +769,47 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
}
}
/// `config` as it should be saved: without what [`apply_to_run_configs`] derives from
/// settings, so a configuration read from the run list, edited and saved keeps following
/// Languages & Frameworks instead of freezing today's toolchain (and the IDE's whole
/// `PATH`) into `run.toml`. A value counts as derived when applying settings to the
/// configuration without it produces it again: an environment entry (`PATH`,
/// `VIRTUAL_ENV`, `JAVA_HOME`, `GOROOT`, …) or an absolute command its bare name
/// resolves to (the project interpreter, a toolchain's `cargo` / `go`, Maven's `mvn`).
pub fn without_derived(config: &RunConfig, root: &Path, s: &Settings) -> RunConfig {
let applied = |c: &RunConfig| {
let mut c = c.clone();
apply_to_run_configs(std::slice::from_mut(&mut c), root, s);
c
};
let mut out = config.clone();
// Until nothing changes: some entries are derived only once others are gone
// (the virtualenv's `PATH` is added only without `VIRTUAL_ENV`).
while let Some(key) = out
.env
.iter()
.find(|(key, value)| {
let mut probe = out.clone();
probe.env.remove(*key);
applied(&probe).env.get(*key) == Some(*value)
})
.map(|(key, _)| key.clone())
{
out.env.remove(&key);
}
let path = Path::new(&config.command);
if path.is_absolute()
&& let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned())
{
let mut probe = out.clone();
probe.command = name.clone();
if applied(&probe).command == config.command {
out.command = name;
}
}
out
}
fn sh_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
+4 -2
Переглянути файл
@@ -21,6 +21,7 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::TypeScript => typescript(root),
SdkKind::Jdk => jdk(),
SdkKind::Maven => maven(),
SdkKind::Ruby => crate::ruby::detect(root),
};
if let Some(root) = root {
pinned_first(&mut out, kind, root);
@@ -35,6 +36,7 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
SdkKind::Go => Some(Tool::Go),
SdkKind::Jdk => Some(Tool::Java),
SdkKind::Maven => Some(Tool::Maven),
SdkKind::Ruby => Some(Tool::Ruby),
SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript => None,
}
}
@@ -50,7 +52,7 @@ fn pinned_first(sdks: &mut Vec<Sdk>, kind: SdkKind, root: &Path) {
}
/// Runs `f` over `items` on scoped threads (version queries spawn processes).
fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Option<R> + Sync) -> Vec<R> {
pub(crate) fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Option<R> + Sync) -> Vec<R> {
std::thread::scope(|s| {
let handles: Vec<_> = items.iter().map(|item| s.spawn(|| f(item))).collect();
handles.into_iter().filter_map(|h| h.join().ok().flatten()).collect()
@@ -227,7 +229,7 @@ fn pyvenv_version(python: &Path) -> Option<String> {
})
}
fn subdirs(dir: &Path) -> Vec<PathBuf> {
pub(crate) fn subdirs(dir: &Path) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> =
std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
out.sort();
+2 -2
Переглянути файл
@@ -884,7 +884,7 @@ mod tests {
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
let data = |c: &LanguageServerConfig| c.args[c.args.iter().position(|a| a == "-data").unwrap() + 1].clone();
assert_ne!(data(&cfg), data(&plain), "a separate workspace, so everything is rebuilt with the agent");
let patched = Path::new("/managed/lombok-1.18.48-openidea.1.jar");
let patched = Path::new("/managed/lombok-1.18.48-openidea.2.jar");
let mut fixed = jdtls();
configure_jdtls(
&mut fixed,
@@ -1173,7 +1173,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.2.0.jar");
let extension = data_dir.join("java-usages-1.2.1.jar");
let bytes = include_bytes!("../../../plugins/java-usages/openidea-java-usages.jar");
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
clean_usages_bundles(data_dir, &extension);
+3
Переглянути файл
@@ -16,9 +16,11 @@ pub mod jdtls;
pub mod libraries;
pub mod locate;
pub mod lombok;
pub mod maven_profiles;
mod npm;
pub mod pinned;
pub mod python;
pub mod ruby;
mod vue;
use serde::{Deserialize, Serialize};
@@ -42,6 +44,7 @@ pub enum SdkKind {
Jdk,
/// Maven homes.
Maven,
Ruby,
}
/// One installed interpreter / toolchain.
+20 -1
Переглянути файл
@@ -54,6 +54,7 @@ const JAVA_MANIFESTS: &[&str] =
const NODE_MANIFESTS: &[&str] = &["package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lockb"];
const CARGO_MANIFESTS: &[&str] = &["Cargo.toml", "Cargo.lock", "rust-toolchain", "rust-toolchain.toml"];
const GO_MANIFESTS: &[&str] = &["go.mod", "go.sum", "go.work"];
const RUBY_MANIFESTS: &[&str] = &["Gemfile", "Gemfile.lock", ".ruby-version", ".tool-versions", "mise.toml"];
/// A Maven / Gradle dependency of the project, from the build model.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -70,7 +71,7 @@ pub struct BuildDependency {
/// `dependencies` (from the build model) are listed when their jars are in the local repositories.
pub fn project_libraries(root: &Path, settings: &Settings, dependencies: &[BuildDependency]) -> Vec<LibraryGroup> {
type Detect = fn(&Path, &Settings) -> Vec<LibraryGroup>;
let detectors: [Detect; 5] = [python_groups, jdk_groups, node_groups, rust_groups, go_groups];
let detectors: [Detect; 6] = [python_groups, jdk_groups, node_groups, rust_groups, go_groups, ruby_groups];
std::thread::scope(|s| {
let handles: Vec<_> = detectors.iter().map(|d| s.spawn(move || d(root, settings))).collect();
let deps = s.spawn(|| dependency_groups(root, settings, dependencies));
@@ -193,6 +194,24 @@ pub(crate) fn named_roots(roots: Vec<(String, PathBuf)>) -> Vec<LibraryRoot> {
.collect()
}
// ------------------------------------------------------------------ ruby
fn ruby_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, RUBY_MANIFESTS) else { return Vec::new() };
if !root.join("Gemfile").is_file() && !root.join(".ruby-version").is_file() {
return Vec::new();
}
let Some(ruby) = crate::apply::ruby_interpreter(root, s) else { return Vec::new() };
cached(root, "ruby", ruby.display().to_string(), &files, || {
let name = crate::ruby::ruby_sdk(&ruby, "system").map(|s| s.name).unwrap_or_else(|| "Ruby".into());
let (stdlib, gems) = crate::ruby::library_roots(&ruby, Some(root));
let mut out = Vec::new();
out.extend(group(name, "ruby", named_roots(stdlib)));
out.extend(group("Gems", "gems", named_roots(gems)));
out
})
}
// ------------------------------------------------------------------ jdk
fn jdk_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
+1 -1
Переглянути файл
@@ -507,7 +507,7 @@ mod tests {
let cache = repo.join("org/projectlombok/lombok/1.18.48");
fs::create_dir_all(&cache).unwrap();
fs::write(cache.join("lombok-1.18.48.jar"), b"official agent").unwrap();
let patched = PathBuf::from("/managed/lombok-1.18.48-openidea.1.jar");
let patched = PathBuf::from("/managed/lombok-1.18.48-openidea.2.jar");
let selected = lombok_agent(tmp.path(), None, Some(patched.clone()), Some(repo.clone()));
assert_eq!(selected.jar(), Some(patched.as_path()));
assert_eq!(selected.problem(), None);
+239
Переглянути файл
@@ -0,0 +1,239 @@
//! Maven profiles for the Java language server. jdtls (m2e) has no setting for the
//! profiles a project is imported with; it takes them from `<activeProfiles>` of the
//! user `settings.xml`. The profiles chosen in the Maven tool window are therefore
//! passed as a copy of the user's settings with those profiles activated.
use crate::apply::setting_path;
use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
const PREFIX: &str = "jdtls-maven-settings-";
/// Points jdtls at a user `settings.xml` activating `profiles` (`-P` entries of the
/// last Maven sync), written to `dir`. Through `settings`, so a running server
/// re-imports its Maven projects instead of restarting. `!id` entries can't be
/// expressed in `settings.xml` and are left to the POMs' own activation.
pub fn configure_jdtls(cfg: &mut LanguageServerConfig, root: &Path, s: &Settings, profiles: &[String], dir: &Path) {
if cfg.name != "jdtls" {
return;
}
let active: Vec<&str> =
profiles.iter().map(|p| p.trim()).filter(|p| !p.is_empty() && !p.starts_with('!')).collect();
let Some(file) = (!active.is_empty()).then(|| write_settings(root, s, &active, dir)).flatten() else {
remove_generated(dir, None);
return;
};
let layer = json!({ "java": { "configuration": { "maven": { "userSettings": file.to_string_lossy() } } } });
match &mut cfg.settings {
Some(settings) => merge(settings, layer),
None => cfg.settings = Some(layer),
}
}
/// The user's settings (Settings › Maven, else `~/.m2/settings.xml`) with `active`
/// added to `<activeProfiles>`. Named after its content: m2e reloads a settings file
/// only when the configured path changes.
fn write_settings(root: &Path, s: &Settings, active: &[&str], dir: &Path) -> Option<PathBuf> {
let user = setting_path(root, &s.languages.java.maven.user_settings)
.or_else(|| crate::home_dir().map(|h| h.join(".m2").join("settings.xml")));
let base = user.and_then(|f| std::fs::read_to_string(f).ok()).unwrap_or_else(|| "<settings>\n</settings>\n".into());
let Some(text) = with_active_profiles(&base, active) else {
tracing::warn!("Maven profiles not passed to jdtls: the user settings.xml has no <settings> element");
return None;
};
let mut hash = 0xcbf29ce484222325u64;
for byte in text.bytes() {
hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3);
}
let file = dir.join(format!("{PREFIX}{hash:016x}.xml"));
if !file.is_file() {
let written = std::fs::create_dir_all(dir).and_then(|()| std::fs::write(&file, &text));
if let Err(e) = written {
tracing::warn!("Maven profiles not passed to jdtls: {}: {e}", file.display());
return None;
}
}
remove_generated(dir, Some(&file));
Some(file)
}
/// Deletes the settings files written for earlier profile choices.
fn remove_generated(dir: &Path, keep: Option<&Path>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
let generated = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(PREFIX));
if generated && Some(path.as_path()) != keep {
let _ = std::fs::remove_file(path);
}
}
}
/// `text` (a `settings.xml`) with `ids` appended to its `<activeProfiles>`, created
/// when missing; `None` when there is no `<settings>` element to add it to.
pub fn with_active_profiles(text: &str, ids: &[&str]) -> Option<String> {
let entries: String = ids.iter().map(|id| format!(" <activeProfile>{}</activeProfile>\n", escape(id))).collect();
let masked = mask_comments(text);
if let Some(start) = find_tag(&masked, "<activeProfiles", 0) {
let end = start + masked[start..].find('>')?;
if masked[..end].ends_with('/') {
let element = format!("<activeProfiles>\n{entries} </activeProfiles>");
return Some(format!("{}{element}{}", &text[..start], &text[end + 1..]));
}
let close = end + masked[end..].find("</activeProfiles")?;
return Some(format!("{}\n{entries} {}", text[..close].trim_end(), &text[close..]));
}
let close = masked.rfind("</settings")?;
let element = format!(" <activeProfiles>\n{entries} </activeProfiles>\n");
Some(format!("{}\n{element}{}", text[..close].trim_end(), &text[close..]))
}
/// Start of the element `open` (`<name`), not a longer name sharing its prefix.
fn find_tag(masked: &str, open: &str, from: usize) -> Option<usize> {
let mut at = from;
while let Some(i) = masked[at..].find(open) {
let start = at + i;
let next = masked[start + open.len()..].chars().next();
if next.is_some_and(|c| c == '>' || c == '/' || c.is_whitespace()) {
return Some(start);
}
at = start + open.len();
}
None
}
/// `text` with comments and CDATA blanked out, byte offsets unchanged.
fn mask_comments(text: &str) -> String {
let mut out = text.as_bytes().to_vec();
let mut at = 0;
while at < text.len() {
let rest = &text[at..];
let (open, close) = match (rest.find("<!--"), rest.find("<![CDATA[")) {
(Some(c), Some(d)) if d < c => (d, "]]>"),
(Some(c), _) => (c, "-->"),
(None, Some(d)) => (d, "]]>"),
(None, None) => break,
};
let start = at + open;
let end = text[start..].find(close).map_or(text.len(), |i| start + i + close.len());
out[start..end].fill(b' ');
at = end;
}
String::from_utf8(out).unwrap_or_default()
}
fn escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}
fn merge(base: &mut Value, layer: Value) {
match (base, layer) {
(Value::Object(base), Value::Object(layer)) => {
for (k, v) in layer {
match base.get_mut(&k) {
Some(existing) => merge(existing, v),
None => {
base.insert(k, v);
}
}
}
}
(base, layer) => *base = layer,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn jdtls() -> LanguageServerConfig {
serde_json::from_value(json!({ "name": "jdtls", "command": "jdtls" })).unwrap()
}
fn user_settings(cfg: &LanguageServerConfig) -> Option<String> {
cfg.settings.as_ref()?.pointer("/java/configuration/maven/userSettings")?.as_str().map(Into::into)
}
#[test]
fn adds_profiles_to_every_shape_of_settings_xml() {
let ids = ["native", "本地"];
let added = "<activeProfile>native</activeProfile>\n <activeProfile>本地</activeProfile>";
for (text, keeps) in [
("<settings>\n</settings>\n", ""),
("<settings><mirrors><mirror><id>m</id></mirror></mirrors></settings>", "<mirror><id>m</id></mirror>"),
(
"<settings>\n <activeProfiles>\n <activeProfile>nexus</activeProfile>\n </activeProfiles>\n</settings>",
"<activeProfile>nexus</activeProfile>",
),
("<settings><activeProfiles/></settings>", ""),
("<settings><activeProfiles /></settings>", ""),
// Commented-out elements are not where the profiles go.
(
"<settings>\n<!-- <activeProfiles></activeProfiles> </settings> -->\n</settings>",
"<!-- <activeProfiles></activeProfiles> </settings> -->",
),
(
"<?xml version=\"1.0\"?>\n<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"><activeProfilesX/></settings>",
"<activeProfilesX/>",
),
] {
let out = with_active_profiles(text, &ids).unwrap_or_else(|| panic!("{text}"));
assert!(out.contains(added), "{text}\n→\n{out}");
assert!(out.contains(keeps), "{text}\n→\n{out}");
let out = if keeps.starts_with("<!--") { out.replace(keeps, "") } else { out };
assert_eq!(out.matches("<activeProfiles>").count(), 1, "{text}\n→\n{out}");
let close = out.find("</activeProfiles>").unwrap();
assert!(close < out.rfind("</settings>").unwrap(), "{out}");
assert!(out.find(added).unwrap() < close, "{out}");
}
assert_eq!(with_active_profiles("<settings/>", &ids), None);
assert!(with_active_profiles("<settings></settings>", &["a&b"]).unwrap().contains("a&amp;b"));
}
#[test]
fn jdtls_imports_with_the_synced_profiles() {
let tmp = tempfile::tempdir().unwrap();
let user = tmp.path().join("user-settings.xml");
std::fs::write(&user, "<settings><localRepository>/repo</localRepository></settings>").unwrap();
let mut s = Settings::default();
s.languages.java.maven.user_settings = user.to_string_lossy().into_owned();
let dir = tmp.path().join("build");
let profiles = |p: &[&str]| p.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let mut cfg = jdtls();
configure_jdtls(&mut cfg, tmp.path(), &s, &profiles(&["native", "!dev", "本地"]), &dir);
let first = user_settings(&cfg).expect("generated settings");
let text = std::fs::read_to_string(&first).unwrap();
assert!(text.contains("<localRepository>/repo</localRepository>"), "{text}");
assert!(
text.contains("<activeProfile>native</activeProfile>")
&& text.contains("<activeProfile>本地</activeProfile>")
);
assert!(!text.contains("dev"), "deactivations are not activations: {text}");
// Same choice → same file; another choice → another path (m2e reloads on a new path).
let mut again = jdtls();
configure_jdtls(&mut again, tmp.path(), &s, &profiles(&["native", "本地"]), &dir);
assert_eq!(user_settings(&again).as_deref(), Some(first.as_str()));
let mut other = jdtls();
configure_jdtls(&mut other, tmp.path(), &s, &profiles(&["pro"]), &dir);
let second = user_settings(&other).unwrap();
assert_ne!(second, first);
assert!(!Path::new(&first).exists(), "the previous file is removed");
// No profile (or only deactivations) → the user's settings as configured.
for none in [&[][..], &["!dev"][..]] {
let mut plain = jdtls();
configure_jdtls(&mut plain, tmp.path(), &s, &profiles(none), &dir);
assert_eq!(user_settings(&plain), None);
}
assert!(!Path::new(&second).exists());
let mut other_server: LanguageServerConfig =
serde_json::from_value(json!({ "name": "kotlin-lsp", "command": "kotlin-lsp" })).unwrap();
configure_jdtls(&mut other_server, tmp.path(), &s, &profiles(&["native"]), &dir);
assert_eq!(other_server.settings, None);
}
}
+237
Переглянути файл
@@ -0,0 +1,237 @@
//! Ruby interpreters: the ones a version manager installed (rbenv, rvm, chruby,
//! mise, asdf), Homebrew's, and the ones on `PATH`; the project's `.ruby-version`;
//! and the interpreter's standard library and Bundler gems for External Libraries.
use crate::discover::{par_map, subdirs};
use crate::exec::{executables_in, query, query_in, search_path};
use crate::{Sdk, exe, home_dir, pinned};
use ide_core::version_managers::{self, Tool};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::time::Duration;
const VERSION_TIMEOUT: Duration = Duration::from_secs(4);
const QUERY_TIMEOUT: Duration = Duration::from_secs(20);
fn var_path(key: &str) -> Option<PathBuf> {
ide_core::process::host_var_os(key).filter(|v| !v.is_empty()).map(PathBuf::from)
}
/// Where version managers keep one directory per Ruby, with the manager's name.
fn manager_roots() -> Vec<(PathBuf, &'static str)> {
let mut out = Vec::new();
let Some(home) = home_dir() else { return out };
out.push((var_path("RBENV_ROOT").unwrap_or_else(|| home.join(".rbenv")).join("versions"), "rbenv"));
out.push((var_path("rvm_path").unwrap_or_else(|| home.join(".rvm")).join("rubies"), "rvm"));
out.push((PathBuf::from("/usr/local/rvm/rubies"), "rvm"));
out.push((home.join(".rubies"), "chruby"));
out.push((PathBuf::from("/opt/rubies"), "chruby"));
out
}
/// `bin/ruby` of a Ruby install directory.
pub(crate) fn ruby_in_install(dir: &Path) -> Option<PathBuf> {
let p = dir.join("bin").join(exe("ruby"));
p.is_file().then_some(p)
}
/// Installed Rubies: version-manager installs, Homebrew, then `PATH` (shims excluded).
pub(crate) fn detect(root: Option<&Path>) -> Vec<Sdk> {
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
for (dir, manager) in manager_roots() {
found.extend(subdirs(&dir).into_iter().filter_map(|v| ruby_in_install(&v)).map(|p| (p, manager)));
}
for (dir, manager) in version_managers::installs(Tool::Ruby) {
found.extend(ruby_in_install(&dir).map(|p| (p, manager)));
}
for brew in ["/opt/homebrew/opt/ruby", "/usr/local/opt/ruby", "/home/linuxbrew/.linuxbrew/opt/ruby"] {
found.extend(ruby_in_install(Path::new(brew)).map(|p| (p, "homebrew")));
}
let dirs = std::env::split_paths(&search_path())
.filter(|d| !is_shims_dir(d) && !version_managers::is_shims_dir(d))
.collect::<Vec<_>>();
found.extend(executables_in("ruby", dirs.into_iter()).into_iter().map(|p| (p, "system")));
let mut seen = HashSet::new();
let candidates: Vec<(PathBuf, &'static str)> = found
.into_iter()
.filter(|(p, _)| p.is_file() && seen.insert(p.canonicalize().unwrap_or_else(|_| p.clone())))
.collect();
let mut out = par_map(&candidates, |(path, source)| ruby_sdk(path, source));
if let Some(root) = root
&& let Some(pinned) = pinned_ruby_version(root)
{
// The `.ruby-version` install first, like the project virtualenv for Python.
if let Some(i) = out.iter().position(|s| version_matches(s.version.as_deref().unwrap_or(""), &pinned)) {
let sdk = out.remove(i);
out.insert(0, sdk);
}
}
out
}
/// rbenv's and rvm's shim directories, which only forward to an install.
fn is_shims_dir(dir: &Path) -> bool {
dir.ends_with(".rbenv/shims") || dir.ends_with(".rvm/bin")
}
/// `ruby 3.3.1 (2024-04-23 revision …) [arm64-darwin23]` → `3.3.1`.
pub(crate) fn parse_version(out: &str) -> Option<String> {
out.strip_prefix("ruby ")?
.split_whitespace()
.next()
.map(|v| v.trim_end_matches(|c: char| c.is_ascii_alphabetic() || c == '-').to_owned())
}
pub(crate) fn ruby_sdk(path: &Path, source: &str) -> Option<Sdk> {
let version = query(path, &["--version"], VERSION_TIMEOUT).and_then(|v| parse_version(&v))?;
let short = version.split('.').take(2).collect::<Vec<_>>().join(".");
let name = match source {
"system" => format!("Ruby {short}"),
tool => format!("Ruby {short} ({tool})"),
};
Some(Sdk {
path: path.into(),
name,
version: Some(version),
source: source.to_owned(),
home: path.parent().and_then(Path::parent).map(Path::to_path_buf).map(Into::into),
extra: None,
})
}
/// The version `.ruby-version` pins (rbenv / rvm / chruby read it; `ruby-3.3.1` → `3.3.1`),
/// from `root` up, else the mise / asdf pin.
pub fn pinned_ruby_version(root: &Path) -> Option<String> {
let from_file = root.ancestors().find_map(|dir| {
let text = std::fs::read_to_string(dir.join(".ruby-version")).ok()?;
let v = text.lines().map(str::trim).find(|l| !l.is_empty() && !l.starts_with('#'))?;
Some(v.strip_prefix("ruby-").unwrap_or(v).to_owned())
});
from_file.or_else(|| pinned::pinned_version(root, Tool::Ruby))
}
/// Whether `version` (`3.3.1`) satisfies a pin (`3.3.1`, `3.3`, `3`).
pub(crate) fn version_matches(version: &str, pin: &str) -> bool {
version == pin || version.strip_prefix(pin).is_some_and(|rest| rest.starts_with('.'))
}
/// The Ruby for `root` without an explicit setting: the install matching
/// `.ruby-version` (version managers, then mise / asdf), else `ruby` on PATH.
pub fn project_ruby(root: &Path) -> Option<PathBuf> {
if let Some(pin) = pinned_ruby_version(root) {
let install = manager_roots()
.into_iter()
.flat_map(|(dir, _)| subdirs(&dir))
.chain(version_managers::installs(Tool::Ruby).into_iter().map(|(d, _)| d))
.find(|dir| {
let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
version_matches(name.strip_prefix("ruby-").unwrap_or(&name), &pin)
});
if let Some(ruby) = install.and_then(|d| ruby_in_install(&d)) {
return Some(ruby);
}
}
crate::exec::which("ruby")
}
/// `bin` directory of `ruby` and the gems it was installed with (`gem` and `bundle` next to it).
pub fn bin_dir_of(ruby: &Path) -> Option<PathBuf> {
ruby.parent().map(Path::to_path_buf)
}
type NamedRoots = Vec<(String, PathBuf)>;
/// Standard-library / site directories (`ruby/3.3.0`) and the gems Bundler resolves
/// for `root` (`rails-7.1.3`), each as `(name, path)`.
pub fn library_roots(ruby: &Path, root: Option<&Path>) -> (NamedRoots, NamedRoots) {
const PATHS: &str = "require 'rbconfig'; puts RbConfig::CONFIG['rubylibdir'], RbConfig::CONFIG['sitelibdir'], RbConfig::CONFIG['vendorlibdir']";
let mut stdlib = Vec::new();
let mut gems = Vec::new();
let file_name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
if let Some(text) = query(ruby, &["-e", PATHS], QUERY_TIMEOUT) {
for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) {
let path = PathBuf::from(line);
if path.is_dir() && !stdlib.iter().any(|(_, p)| *p == path) {
let parent = path.parent().map(file_name).unwrap_or_default();
stdlib.push((format!("{parent}/{}", file_name(&path)), path));
}
}
}
if let Some(root) = root.filter(|r| r.join("Gemfile").is_file()) {
let bin = bin_dir_of(ruby);
let bundle = bin.as_ref().map(|b| b.join(exe("bundle"))).filter(|b| b.is_file());
let path = bin.as_ref().map(|b| crate::exec::path_with(&[b.as_path()])).unwrap_or_default();
let env: &[(&str, &str)] = &[("PATH", &path)];
let text = match &bundle {
Some(b) => query_in(b, &["list", "--paths"], Some(root), env, QUERY_TIMEOUT),
None => query_in(ruby, &["-S", "bundle", "list", "--paths"], Some(root), env, QUERY_TIMEOUT),
};
for line in text.unwrap_or_default().lines().map(str::trim).filter(|l| !l.is_empty()) {
let path = PathBuf::from(line);
if path.is_dir() && path != root {
gems.push((file_name(&path), path));
}
}
}
(stdlib, gems)
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn includes_bundled_gems_installed_inside_the_project() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
let gem = root.join("vendor/bundle/ruby/4.0.0/gems/rake-13.4.0");
let external = dir.path().join("gems/rspec-3.13.2");
let bin = dir.path().join("bin");
for path in [&gem, &external, &bin] {
std::fs::create_dir_all(path).unwrap();
}
std::fs::write(root.join("Gemfile"), "gem 'rake'\ngem 'rspec'\n").unwrap();
for (name, output) in [
("ruby", String::new()),
("bundle", format!("{}\n{}\n{}", gem.display(), external.display(), root.display())),
] {
let path = bin.join(name);
std::fs::write(&path, format!("#!/bin/sh\nprintf '%s\\n' '{output}'\n")).unwrap();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let (_, gems) = library_roots(&bin.join("ruby"), Some(&root));
assert_eq!(gems, vec![("rake-13.4.0".into(), gem), ("rspec-3.13.2".into(), external)]);
}
#[test]
fn parses_ruby_version_output() {
assert_eq!(
parse_version("ruby 3.3.1 (2024-04-23 revision c56cd86388) [arm64-darwin23]").as_deref(),
Some("3.3.1")
);
assert_eq!(parse_version("ruby 3.4.0dev (2024-10-01) +PRISM [x86_64-linux]").as_deref(), Some("3.4.0"));
assert_eq!(parse_version("jruby 9.4.5.0"), None);
}
#[test]
fn version_pins_match_prefixes() {
assert!(version_matches("3.3.1", "3.3.1"));
assert!(version_matches("3.3.1", "3.3"));
assert!(!version_matches("3.31.1", "3.3"));
assert!(!version_matches("3.3.1", "3.3.10"));
}
#[test]
fn ruby_version_file_wins_over_managers() {
let dir = tempfile::tempdir().unwrap();
let project = dir.path().join("app/sub");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(dir.path().join("app/.ruby-version"), "ruby-3.2.2\n").unwrap();
assert_eq!(pinned_ruby_version(&project).as_deref(), Some("3.2.2"));
}
}
+82 -1
Переглянути файл
@@ -1,6 +1,6 @@
use crate::apply::{
apply_to_run_configs, configure_server, jdtls_jdk, maven_command, maven_options, project_jdk, python_interpreter,
terminal_activation, tsdk,
terminal_activation, tsdk, without_derived,
};
use crate::python::parse_pip_list;
use crate::{bin_dir, exe, venv_of};
@@ -1108,3 +1108,84 @@ fn go_modules_configure_gopls_in_place_and_commands_with_explicit_run_overrides(
configure_server(&mut cleared, tmp.path(), tmp.path(), &Settings::default());
assert_eq!(cleared.settings.unwrap()["env"], json!({}));
}
#[test]
fn saving_a_loaded_run_configuration_drops_what_settings_derived() {
if cfg!(windows) {
return; // Unix paths
}
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let touch = |rel: &str| {
let p = root.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(&p, "").unwrap();
p.to_string_lossy().into_owned()
};
let mut s = Settings::default();
s.languages.python.interpreter = fake_venv(root, ".venv").to_string_lossy().into_owned();
s.languages.node.interpreter = touch("node/bin/node");
touch("rustup/toolchains/stable/bin/cargo");
s.languages.rust.toolchain = root.join("rustup/toolchains/stable").to_string_lossy().into_owned();
touch("go/bin/go");
s.languages.go.goroot = root.join("go").to_string_lossy().into_owned();
s.languages.go.gopath = root.join("gopath").to_string_lossy().into_owned();
s.languages.go.modules.env = BTreeMap::from([("GOPROXY".into(), "https://proxy.example".into())]);
fake_jdk(&root.join("jdk17"));
s.languages.java.jdk = root.join("jdk17").to_string_lossy().into_owned();
touch("maven/bin/mvn");
s.languages.java.maven.home = root.join("maven").to_string_lossy().into_owned();
s.languages.ruby.interpreter = touch("ruby/bin/ruby");
touch("ruby/bin/bundle");
s.tools.insert("godot".into(), ide_core::settings::ToolSettings { path: touch("Godot/godot") });
let saved = |kind: &str, command: &str, args: &[&str], env: &[(&str, &str)]| {
let mut c = run(kind, command, args);
c.detected = false;
c.env = env.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
c
};
// As the user saved them: bare tools, only their own environment.
let configs = [
saved("python", "python", &["app.py"], &[]),
saved("pytest", ".venv/bin/pytest", &["-x"], &[("FOO", "1")]),
saved("npm", "npm", &["run", "dev"], &[]),
saved("cargo", "cargo", &["run"], &[]),
saved("go", "go", &["run", "."], &[]),
saved("go", "go", &["mod", "tidy"], &[("GOPROXY", "off")]),
saved("maven", "mvn", &["package"], &[]),
saved("tomcat", "catalina", &[], &[]),
saved("ruby", "ruby", &["app.rb"], &[]),
saved("rake", "bundle", &["exec", "rake"], &[("RAILS_ENV", "test")]),
saved("godot", "godot", &["--path", "."], &[]),
// The user's own values that merely look like derived ones stay.
saved("cargo", "/opt/rust/bin/cargo", &["build"], &[("PATH", "/custom/bin")]),
saved("maven", "mvn", &["verify"], &[("JAVA_HOME", "/other/jdk")]),
saved("python", "python", &["x.py"], &[("VIRTUAL_ENV", "/elsewhere/venv")]),
];
for user in configs {
let mut loaded = user.clone();
apply_to_run_configs(std::slice::from_mut(&mut loaded), root, &s);
assert_ne!(loaded, user, "{} {}: settings apply to it", user.kind, user.command);
let stored = without_derived(&loaded, root, &s);
assert_eq!(stored, user, "{} {}: saved as the user left it", user.kind, user.command);
let mut reloaded = stored;
apply_to_run_configs(std::slice::from_mut(&mut reloaded), root, &s);
assert_eq!(reloaded, loaded, "{} {}: runs the same after a save", user.kind, user.command);
}
// Another bare name for the interpreter comes back as the interpreter's own.
let mut loaded = saved("python", "python3", &["app.py"], &[]);
apply_to_run_configs(std::slice::from_mut(&mut loaded), root, &s);
assert_eq!(without_derived(&loaded, root, &s).command, exe("python"));
// A saved configuration follows a later interpreter change instead of a frozen PATH.
let mut loaded = saved("ruby", "ruby", &["app.rb"], &[]);
apply_to_run_configs(std::slice::from_mut(&mut loaded), root, &s);
let mut next = without_derived(&loaded, root, &s);
s.languages.ruby.interpreter = touch("ruby2/bin/ruby");
apply_to_run_configs(std::slice::from_mut(&mut next), root, &s);
let ruby2 = root.join("ruby2/bin");
assert_eq!(next.command, ruby2.join("ruby").to_string_lossy());
assert!(next.env["PATH"].starts_with(&*ruby2.to_string_lossy()), "{}", next.env["PATH"]);
}
+20 -4
Переглянути файл
@@ -18,7 +18,8 @@ use std::time::SystemTime;
pub use words::{MIN_WORD_CHARS, WordSpan, words};
/// Where a region's words come from; strings and comments understand escapes.
/// Where a region's words come from; strings understand escapes, comments and
/// prose skip backslash commands (`\brief`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RegionKind {
Comment,
@@ -421,15 +422,22 @@ fn capitalize(s: &str) -> String {
/// blocks and inline code spans.
pub fn prose_regions(text: &str) -> Vec<Region> {
let mut out = Vec::new();
let mut fence: Option<&str> = None;
// The open fence: its character and length.
let mut fence: Option<(char, usize)> = None;
let mut offset = 0;
for line in text.split_inclusive('\n') {
let start = offset;
offset += line.len();
let trimmed = line.trim_start();
let marker = ["```", "~~~"].into_iter().find(|m| trimmed.starts_with(m));
let marker = ['`', '~'].into_iter().find_map(|c| {
let n = trimmed.len() - trimmed.trim_start_matches(c).len();
(n >= 3).then_some((c, n))
});
match (fence, marker) {
(Some(open), Some(m)) if m == open => {
// CommonMark: a closing fence uses the same character, is at least as
// long as the opening one and has no info string, so a ```` fence can
// show a ``` block.
(Some((open, open_len)), Some((c, n))) if c == open && n >= open_len && trimmed[n..].trim().is_empty() => {
fence = None;
continue;
}
@@ -720,6 +728,14 @@ mod tests {
assert_eq!(spans, ["Some prose ", " here\n", "more\n"]);
}
#[test]
fn markdown_fences_close_on_a_matching_fence_only() {
let text = "Example:\n````markdown\n```rust\nfn wrng() {}\n```\n````\nmore\n~~~\n```\nnot clsed\n~~~~\nend\n";
let regions = prose_regions(text);
let spans: Vec<_> = regions.iter().map(|r| &text[r.start..r.end]).collect();
assert_eq!(spans, ["Example:\n", "more\n", "end\n"]);
}
#[test]
fn cancellation() {
let s = Speller::default();
+35 -5
Переглянути файл
@@ -17,7 +17,11 @@ pub struct WordSpan {
/// Words of `text[start..end]` in order, as absolute byte ranges.
pub fn words(text: &str, start: usize, end: usize, kind: RegionKind, out: &mut Vec<WordSpan>) {
let Some(slice) = text.get(start..end) else { return };
let escapes = !matches!(kind, RegionKind::Name);
let escapes = match kind {
RegionKind::Name => Escapes::None,
RegionKind::String => Escapes::Char,
RegionKind::Comment | RegionKind::Prose => Escapes::Word,
};
let mut chunk_start = None;
for (i, c) in slice.char_indices().chain(std::iter::once((slice.len(), ' '))) {
if c.is_whitespace() {
@@ -30,6 +34,18 @@ pub fn words(text: &str, start: usize, end: usize, kind: RegionKind, out: &mut V
}
}
/// What a `\` hides from the spell checker.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Escapes {
/// Identifiers have no escapes.
None,
/// String literals: the escape letter (`\n`, `\t`), the rest of the word is text.
Char,
/// Comments and prose: the whole word, a Doxygen / TeX command (`\brief`,
/// `\param`) or an escape quoted in a comment (`\n`).
Word,
}
/// URLs, e-mail addresses and the like are not prose.
fn skip_chunk(chunk: &str) -> bool {
if chunk.contains("://") || chunk.starts_with("www.") {
@@ -41,7 +57,7 @@ fn skip_chunk(chunk: &str) -> bool {
}
}
fn chunk(slice: &str, from: usize, to: usize, escapes: bool, base: usize, out: &mut Vec<WordSpan>) {
fn chunk(slice: &str, from: usize, to: usize, escapes: Escapes, base: usize, out: &mut Vec<WordSpan>) {
let text = &slice[from..to];
if skip_chunk(text) {
return;
@@ -57,9 +73,15 @@ fn chunk(slice: &str, from: usize, to: usize, escapes: bool, base: usize, out: &
if let Some(s) = run.take() {
token(text, s, i, base + from, out);
}
// `\n`, `\t`, `é`: the escape letter is not part of the next word.
if escapes && c == '\\' {
chars.next();
if c == '\\' {
match escapes {
Escapes::None => {}
// `\n`, `\t`, `é`: the escape letter is not part of the next word.
Escapes::Char => {
chars.next();
}
Escapes::Word => while chars.next_if(|&(_, c)| c.is_alphanumeric() || c == '_').is_some() {},
}
}
}
if let Some(s) = run {
@@ -164,6 +186,14 @@ mod tests {
assert_eq!(split("// 中文注释 naïve", RegionKind::Comment), ["naïve"]);
}
#[test]
fn skips_backslash_commands_in_comments() {
assert_eq!(split("/// \\brief Returns the sum.", RegionKind::Comment), ["Returns", "the", "sum"]);
assert_eq!(split("@see \\ref Foo, \\param[in] count", RegionKind::Comment), ["see", "Foo", "count"]);
assert_eq!(split("prints \\nthe line", RegionKind::Comment), ["prints", "line"]);
assert_eq!(split("\\emph{word} text", RegionKind::Prose), ["word", "text"]);
}
#[test]
fn keeps_apostrophes_inside_words() {
assert_eq!(split("'don't' shouldn't", RegionKind::Comment), ["don't", "shouldn't"]);
+13 -2
Переглянути файл
@@ -540,6 +540,15 @@ impl Tools {
if managed || self.method_missing(spec.method).is_some() { fallback } else { spec.method }
}
/// [`Method::label`], naming the installer that will actually run: a virtualenv is
/// made with uv when it is on `PATH` (see `install_venv`).
fn method_label(&self, method: Method) -> &'static str {
match method {
Method::PipVenv { .. } if self.which("uv").is_some() => "uv (virtualenv)",
m => m.label(),
}
}
/// Requirement check for installing `spec` right now.
fn unavailable_reason(&self, spec: &ToolSpec) -> Option<String> {
self.method_missing(self.install_method(spec))
@@ -624,7 +633,7 @@ impl Tools {
status,
path: path.map(Into::into),
version,
install_method: Some(self.install_method(spec).label().to_string()),
install_method: Some(self.method_label(self.install_method(spec)).to_string()),
can_install: unavailable_reason.is_none() && !bundled,
unavailable_reason,
can_uninstall,
@@ -796,7 +805,9 @@ impl Tools {
let result = (|| {
std::fs::create_dir_all(&self.root)?;
let method = self.install_method(spec);
emit(InstallEvent::Line { text: format!("Installing {} via {}…", spec.display, method.label()) });
emit(InstallEvent::Line {
text: format!("Installing {} via {}…", spec.display, self.method_label(method)),
});
match method {
Method::Bundled { .. } => {
bundled::install(&self.root, spec)?;
+18 -5
Переглянути файл
@@ -233,6 +233,17 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://docs.astral.sh/ty/",
needs: &[],
},
ToolSpec {
name: "pyrefly",
display: "Pyrefly (Python)",
kind: LanguageServer,
commands: &["pyrefly"],
method: Method::PipVenv { package: "pyrefly" },
fallback: None,
version: ver("pyrefly"),
homepage: "https://pyrefly.org",
needs: &[],
},
ToolSpec {
name: "ruff",
display: "Ruff",
@@ -626,13 +637,15 @@ pub static TOOLS: &[ToolSpec] = &[
display: "Lombok (jdtls agent)",
kind: Plugin,
commands: &["lombok.jar"],
// Equinox removed getModuleClassLoader(boolean), breaking lombok.config lookup.
// Return to Maven Central once an official release includes lombok#4059.
// Equinox removed getModuleClassLoader(boolean), breaking lombok.config lookup (lombok#4059);
// ECJ 3.46.200 keeps the constructor call in a constructor's statements, which
// @SneakyThrows / @NonNull must not wrap or precede (lombok#4089).
// Return to Maven Central once an official release includes both.
// Source commit, build instructions and checksum: plugins/lombok/README.md.
method: Method::Bundled {
filename: "lombok-1.18.48-openidea.1.jar",
version: "1.18.48-openidea.1",
bytes: include_bytes!("../../../plugins/lombok/lombok-1.18.48-openidea.1.jar"),
filename: "lombok-1.18.48-openidea.2.jar",
version: "1.18.48-openidea.2",
bytes: include_bytes!("../../../plugins/lombok/lombok-1.18.48-openidea.2.jar"),
},
fallback: None,
version: V,
+23 -3
Переглянути файл
@@ -56,9 +56,9 @@ fn bundled_lombok_replaces_legacy_installs_on_every_platform_without_downloads()
let info = tools.info("lombok", &[]).unwrap();
let path = managed_bundle(env.root.parent().unwrap(), "lombok").unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("1.18.48-openidea.1"));
assert_eq!(info.version.as_deref(), Some("1.18.48-openidea.2"));
assert_eq!(info.path, Some(path.clone().into()));
assert_eq!(path.file_name().unwrap(), "lombok-1.18.48-openidea.1.jar");
assert_eq!(path.file_name().unwrap(), "lombok-1.18.48-openidea.2.jar");
assert!(!info.can_install && !info.can_uninstall);
assert_eq!(tools.unavailable_reason(registry::find("lombok").unwrap()), None);
assert_eq!(fs::read(&legacy).unwrap(), b"old official agent", "other windows may still use it");
@@ -130,6 +130,11 @@ fn everything_missing_on_an_empty_system() {
assert_eq!(ty.command, "ty");
assert_eq!(ty.install_method.as_deref(), Some("pip (virtualenv)"));
assert!(ty.languages.iter().any(|language| language == "Python"));
let pyrefly = find(&list, "pyrefly");
assert_eq!(pyrefly.status, ToolStatus::Missing);
assert_eq!(pyrefly.command, "pyrefly");
assert_eq!(pyrefly.install_method.as_deref(), Some("pip (virtualenv)"));
assert!(pyrefly.languages.iter().any(|language| language == "Python"));
let angular = find(&list, "angular-language-server");
assert_eq!(angular.command, "ngserver");
assert_eq!(angular.install_method.as_deref(), Some("npm"));
@@ -150,7 +155,7 @@ fn everything_missing_on_an_empty_system() {
fn interchangeable_servers_list_their_alternatives() {
let env = Env::new();
let list = env.tools().list(&langs());
let python = ["basedpyright", "pyright", "ty"];
let python = ["basedpyright", "pyright", "ty", "pyrefly"];
for name in python {
assert_eq!(find(&list, name).alternatives, python);
}
@@ -161,6 +166,21 @@ fn interchangeable_servers_list_their_alternatives() {
assert!(find(&list, "rust-analyzer").alternatives.is_empty());
}
#[cfg(unix)]
#[test]
fn python_servers_name_uv_when_it_makes_the_virtualenv() {
let env = Env::new();
env.script(&env.sys, "uv", "exit 0");
let list = env.tools().list(&langs());
for name in ["basedpyright", "ty", "ruff"] {
let tool = find(&list, name);
assert_eq!(tool.install_method.as_deref(), Some("uv (virtualenv)"), "{name}");
assert!(tool.can_install, "{name}: uv alone is enough");
}
// debugpy's private copy is always made by `python -m pip`.
assert_eq!(find(&list, "debugpy").install_method.as_deref(), Some("pip (private copy)"));
}
#[cfg(unix)]
#[test]
fn detects_tools_on_path_with_versions() {
+3
Переглянути файл
@@ -297,6 +297,9 @@ pub struct ShelvedChangeList {
pub time_ms: f64,
/// Branch checked out when the changes were shelved.
pub branch: Option<String>,
/// Repository owning the patch; absent in legacy shelves.
#[serde(default)]
pub repo: Option<ide_core::IpcPath>,
/// Repository-relative paths.
pub files: Vec<ChangedFile>,
}
+26 -5
Переглянути файл
@@ -19,6 +19,8 @@ struct Info {
#[serde(default)]
branch: Option<String>,
files: Vec<crate::ChangedFile>,
#[serde(default)]
repo: Option<ide_core::IpcPath>,
}
fn now_ms() -> f64 {
@@ -67,6 +69,7 @@ pub fn list(shelf: &Path) -> IdeResult<Vec<ShelvedChangeList>> {
name: id.clone(),
time_ms: 0.0,
branch: None,
repo: None,
files: std::fs::read_to_string(dir.join(PATCH))
.map(|p| {
crate::patch::parse_patch(&p)
@@ -81,6 +84,7 @@ pub fn list(shelf: &Path) -> IdeResult<Vec<ShelvedChangeList>> {
name: info.name,
time_ms: info.time_ms,
branch: info.branch,
repo: info.repo,
files: crate::patch::parse_patch(&std::fs::read_to_string(dir.join(PATCH))?)
.into_iter()
.map(|f| crate::ChangedFile { path: f.path, kind: f.kind, old_path: f.old_path })
@@ -96,6 +100,11 @@ pub fn patch_of(shelf: &Path, id: &str) -> IdeResult<String> {
Ok(std::fs::read_to_string(entry_dir(shelf, id)?.join(PATCH))?)
}
/// The repository captured when the shelf was made; legacy shelves used the primary repository.
pub fn repository(shelf: &Path, id: &str) -> IdeResult<Option<PathBuf>> {
Ok(read_info(&entry_dir(shelf, id)?).and_then(|info| info.repo).map(|repo| repo.into_path_buf()))
}
pub fn delete(shelf: &Path, id: &str) -> IdeResult<()> {
std::fs::remove_dir_all(entry_dir(shelf, id)?)?;
Ok(())
@@ -107,8 +116,13 @@ pub fn rename(shelf: &Path, id: &str, name: &str) -> IdeResult<()> {
return Err(IdeError::invalid("name must not be empty"));
}
let dir = entry_dir(shelf, id)?;
let mut info =
read_info(&dir).unwrap_or(Info { name: String::new(), time_ms: now_ms(), branch: None, files: vec![] });
let mut info = read_info(&dir).unwrap_or(Info {
name: String::new(),
time_ms: now_ms(),
branch: None,
repo: None,
files: vec![],
});
info.name = name.to_string();
std::fs::write(dir.join(INFO), serde_json::to_vec_pretty(&info).map_err(|e| IdeError::internal(e.to_string()))?)?;
Ok(())
@@ -134,7 +148,13 @@ pub(crate) fn shelve(r: &Repo, shelf: &Path, name: &str, rel_paths: &[String]) -
}
let dir = shelf.join(&id);
std::fs::create_dir_all(&dir)?;
let info = Info { name: name.to_string(), time_ms: now_ms(), branch: r.branch_info()?.head, files: files.clone() };
let info = Info {
name: name.to_string(),
time_ms: now_ms(),
branch: r.branch_info()?.head,
files: files.clone(),
repo: Some(r.root().to_path_buf().into()),
};
let write = || -> IdeResult<()> {
std::fs::write(dir.join(PATCH), patch.as_bytes())?;
std::fs::write(
@@ -148,7 +168,7 @@ pub(crate) fn shelve(r: &Repo, shelf: &Path, name: &str, rel_paths: &[String]) -
return Err(e);
}
revert_files(r, &files)?;
Ok(ShelvedChangeList { id, name: info.name, time_ms: info.time_ms, branch: info.branch, files })
Ok(ShelvedChangeList { id, name: info.name, time_ms: info.time_ms, branch: info.branch, repo: info.repo, files })
}
/// Restores `files` to HEAD in both index and working tree; files absent from HEAD are removed.
@@ -318,7 +338,7 @@ pub fn diff_files(r: &Repo, shelf: &Path, id: &str) -> IdeResult<Vec<ShelfDiffFi
}
/// Import into the shelf without applying to the working tree.
pub fn import_patch(shelf: &Path, name: &str, patch: &str) -> IdeResult<()> {
pub fn import_patch(shelf: &Path, name: &str, patch: &str, repo: Option<&Path>) -> IdeResult<()> {
let files = crate::patch::parse_patch(patch);
if files.is_empty() || sections(patch).len() != files.len() {
return Err(IdeError::invalid("no file changes found in the patch"));
@@ -334,6 +354,7 @@ pub fn import_patch(shelf: &Path, name: &str, patch: &str) -> IdeResult<()> {
name: name.to_string(),
time_ms: now_ms(),
branch: None,
repo: repo.map(|r| r.to_path_buf().into()),
files: files
.into_iter()
.map(|f| crate::ChangedFile { path: f.path, kind: f.kind, old_path: f.old_path })
+3 -3
Переглянути файл
@@ -614,7 +614,7 @@ fn shelf_diff_and_scoped_operations_preserve_siblings() {
assert!(!shelf::list(&shelf).unwrap()[0].files.iter().any(|f| f.path == "b.txt"));
shelf::delete_path(&shelf, &entry.id, Some(QUOTED)).unwrap();
assert!(shelf::selected_patch(&shelf, &entry.id, Some("a.txt")).is_ok());
shelf::import_patch(&shelf, "imported", &patch).unwrap();
shelf::import_patch(&shelf, "imported", &patch, None).unwrap();
assert_eq!(shelf::list(&shelf).unwrap().len(), 2);
assert_eq!(fx.read("a.txt"), "local edits\n");
}
@@ -629,7 +629,7 @@ fn shelf_imported_rename_diff_and_last_file_delete() {
fx.git(&["reset", "--hard", "HEAD"]);
let repo = fx.repo();
let shelf = fx._tmp.path().join("shelf");
shelf::import_patch(&shelf, "rename", &patch).unwrap();
shelf::import_patch(&shelf, "rename", &patch, None).unwrap();
let id = &shelf::list(&shelf).unwrap()[0].id;
let diffs = shelf::diff_files(&repo, &shelf, id).unwrap();
assert_eq!(diffs.len(), 1);
@@ -655,7 +655,7 @@ fn shelf_new_renames_keep_self_contained_sides_and_plain_imports_keep_scope() {
assert_eq!(diffs.iter().find(|f| f.path == "old.txt").unwrap().before.as_deref(), Some("renamed content\n"));
assert_eq!(diffs.iter().find(|f| f.path == "new.txt").unwrap().after.as_deref(), Some("renamed content\n"));
let plain = "--- a/one.txt\n+++ b/one.txt\n@@ -1 +1 @@\n--- removed\n+++ added\n--- a/two.txt\n+++ b/two.txt\n@@ -1 +1 @@\n-old\n+new\n";
shelf::import_patch(&shelf, "plain", plain).unwrap();
shelf::import_patch(&shelf, "plain", plain, None).unwrap();
let selected = shelf::selected_patch(&shelf, "plain", Some("one.txt")).unwrap();
assert!(selected.contains("--- removed\n+++ added"));
assert!(!selected.contains("two.txt"));
+219 -35
Переглянути файл
@@ -5,12 +5,15 @@
//! that skips excluded / git-ignored directories (Linux, where a recursive
//! inotify watch would register every directory of `node_modules` and
//! `target` and exhaust `max_user_watches`).
//!
//! When the OS watcher cannot start (inotify limits used up, a file system
//! without change notifications), the same directories are polled instead.
use crate::FsBatch;
use crate::rules::{ExcludeMatcher, GitignoreStack};
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink};
use notify_debouncer_full::notify::event::{ModifyKind, RenameMode};
use notify_debouncer_full::notify::{self, EventKind, RecommendedWatcher, RecursiveMode, Watcher as _};
use notify_debouncer_full::notify::{self, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, WatcherKind};
use notify_debouncer_full::{DebounceEventResult, DebouncedEvent, Debouncer, NoCache, new_debouncer_opt};
use parking_lot::{Condvar, Mutex, RwLock};
use std::collections::{BTreeMap, BTreeSet, HashSet};
@@ -23,6 +26,8 @@ use std::time::{Duration, Instant};
const DEBOUNCE: Duration = Duration::from_millis(100);
/// Upper bound on how long a continuous stream of events is held back.
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);
/// How directories are registered with the OS.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -43,6 +48,7 @@ impl Default for WatchMode {
}
type OnChange = Box<dyn Fn(&FsBatch) + Send + Sync>;
type Emit = Arc<dyn Fn(&FsBatch) + Send + Sync>;
/// Debounced watcher. Emits `IdeEvent::FsChanged` to `sink` and invokes
/// `on_change` (used by the index) with the same batch. Stops when dropped;
@@ -51,12 +57,14 @@ pub struct Watcher {
inner: Inner,
excludes: SharedExcludes,
rules: Arc<GitignoreStack>,
polling: Option<String>,
}
type SharedExcludes = Arc<RwLock<ExcludeMatcher>>;
enum Inner {
Recursive(#[allow(dead_code)] Debouncer<RecommendedWatcher, NoCache>),
Polling(#[allow(dead_code)] Debouncer<PollWatcher, NoCache>),
PerDirectory { state: Arc<DirState>, thread: Option<JoinHandle<()>> },
}
@@ -76,7 +84,7 @@ impl Watcher {
let filter = EventFilter::new(root.clone(), &excludes);
let shared = filter.excludes.clone();
let rules = filter.gitignore.clone();
let emit = move |batch: &FsBatch| {
let emit: Emit = Arc::new(move |batch: &FsBatch| {
// VCS-metadata-only batches (`batch.vcs`) carry no worktree paths:
// consumers that refresh on any `fsChanged` would reschedule purely
// from the backend's own `.git/index` write.
@@ -91,13 +99,21 @@ impl Watcher {
sink.emit(IdeEvent::ExcludedDirsChanged { dirs: batch.excluded_dirs.iter().map(Into::into).collect() });
}
on_change(batch);
});
let (inner, polling) = match Self::start_native(&root, filter.clone(), emit.clone(), mode) {
Ok(inner) => (inner, None),
// Rather than failing to open the project, keep it in sync a little later.
Err(e) => {
tracing::warn!("{e}; polling {} for changes instead", root.display());
(Self::start_polling(&root, filter, emit, mode)?, Some(e.message))
}
};
let inner = match mode {
WatchMode::Recursive => Self::start_recursive(root, filter, emit, RecursiveMode::Recursive),
WatchMode::Flat => Self::start_recursive(root, filter, emit, RecursiveMode::NonRecursive),
WatchMode::PerDirectory => Self::start_per_directory(root, filter, emit),
}?;
Ok(Self { inner, excludes: shared, rules })
Ok(Self { inner, excludes: shared, rules, polling })
}
/// Why changes are polled for instead of reported by the OS; `None` when they are.
pub fn polling(&self) -> Option<&str> {
self.polling.as_deref()
}
/// Replaces the exclude globs (Settings › Project Structure / File Types
@@ -116,21 +132,53 @@ impl Watcher {
/// Number of OS-level watches (1 in recursive and flat mode).
pub fn watch_count(&self) -> usize {
match &self.inner {
Inner::Recursive(_) => 1,
Inner::Recursive(_) | Inner::Polling(_) => 1,
Inner::PerDirectory { state, .. } => state.watched.lock().len(),
}
}
fn start_recursive(
root: PathBuf,
fn start_native(root: &Path, filter: EventFilter, emit: Emit, mode: WatchMode) -> IdeResult<Inner> {
let config = notify::Config::default();
match mode {
WatchMode::Recursive => {
Self::start_debounced(root, filter, emit, RecursiveMode::Recursive, config).map(Inner::Recursive)
}
WatchMode::Flat => {
Self::start_debounced(root, filter, emit, RecursiveMode::NonRecursive, config).map(Inner::Recursive)
}
WatchMode::PerDirectory => Self::start_per_directory::<RecommendedWatcher>(root, filter, emit, config),
}
}
/// Polls per directory unless flat: a recursive poll would rescan
/// `node_modules` and `target` every round.
fn start_polling(root: &Path, filter: EventFilter, emit: Emit, mode: WatchMode) -> IdeResult<Inner> {
let config = notify::Config::default().with_poll_interval(POLL_INTERVAL);
match mode {
WatchMode::Flat => {
Self::start_debounced(root, filter, emit, RecursiveMode::NonRecursive, config).map(Inner::Polling)
}
WatchMode::Recursive | WatchMode::PerDirectory => {
Self::start_per_directory::<PollWatcher>(root, filter, emit, config)
}
}
}
fn start_debounced<W: notify::Watcher>(
root: &Path,
filter: EventFilter,
emit: impl Fn(&FsBatch) + Send + 'static,
emit: Emit,
recursive: RecursiveMode,
) -> IdeResult<Inner> {
config: notify::Config,
) -> IdeResult<Debouncer<W, NoCache>> {
let polled = W::kind() == WatcherKind::PollWatcher;
// No file-id cache: building it walks and stats the whole tree before `watch` returns,
// which made opening large projects block for seconds. Renames arrive as remove + create.
let handler = move |result: DebounceEventResult| match result {
Ok(events) => {
Ok(mut events) => {
if polled {
events.retain(|e| !is_dir_touch(&e.event));
}
let (batch, _) = filter.batch_detailed(&events);
if !batch.is_empty() {
emit(&batch);
@@ -142,18 +190,19 @@ impl Watcher {
}
}
};
let mut debouncer =
new_debouncer_opt::<_, RecommendedWatcher, _>(DEBOUNCE, None, handler, NoCache, notify::Config::default())
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
debouncer.watch(&root, recursive).map_err(|e| io_error(format!("cannot watch {}: {e}", root.display())))?;
Ok(Inner::Recursive(debouncer))
let mut debouncer = new_debouncer_opt::<_, W, _>(DEBOUNCE, None, handler, NoCache, config)
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
debouncer.watch(root, recursive).map_err(|e| io_error(format!("cannot watch {}: {e}", root.display())))?;
Ok(debouncer)
}
fn start_per_directory(
root: PathBuf,
fn start_per_directory<W: notify::Watcher + Send + 'static>(
root: &Path,
filter: EventFilter,
emit: impl Fn(&FsBatch) + Send + 'static,
emit: Emit,
config: notify::Config,
) -> IdeResult<Inner> {
let polled = W::kind() == WatcherKind::PollWatcher;
let state = Arc::new(DirState {
filter,
watcher: Mutex::new(None),
@@ -163,10 +212,11 @@ impl Watcher {
stop: AtomicBool::new(false),
});
let weak: Weak<DirState> = Arc::downgrade(&state);
let watcher = RecommendedWatcher::new(
let watcher = W::new(
move |event: notify::Result<notify::Event>| {
let Some(state) = weak.upgrade() else { return };
match event {
Ok(event) if polled && is_dir_touch(&event) => {}
Ok(event) => {
state.queue.lock().push((event, Instant::now()));
state.wake.notify_one();
@@ -174,12 +224,12 @@ impl Watcher {
Err(e) => tracing::warn!("file watcher: {e}"),
}
},
notify::Config::default(),
config,
)
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
*state.watcher.lock() = Some(watcher);
*state.watcher.lock() = Some(Box::new(watcher));
let mut created = Vec::new();
state.watch_tree(&root, false, &mut created);
state.watch_tree(root, false, &mut created);
if state.watched.lock().is_empty() {
return Err(io_error(format!("cannot watch {}", root.display())));
}
@@ -187,7 +237,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(&*emit))
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?
};
Ok(Inner::PerDirectory { state, thread: Some(thread) })
@@ -212,11 +262,17 @@ fn io_error(msg: String) -> IdeError {
IdeError::new(ide_core::error::ErrorKind::Io, msg)
}
/// A directory's own mtime moving as entries come and go: polling sees it, the
/// OS watchers report only the entries (also seen, through that directory's watch).
fn is_dir_touch(event: &notify::Event) -> bool {
matches!(event.kind, EventKind::Modify(_)) && event.paths.iter().all(|p| p.is_dir())
}
/// State of the per-directory strategy, shared with the notify callback
/// (weakly) and the debounce thread.
struct DirState {
filter: EventFilter,
watcher: Mutex<Option<RecommendedWatcher>>,
watcher: Mutex<Option<Box<dyn notify::Watcher + Send>>>,
watched: Mutex<HashSet<PathBuf>>,
queue: Mutex<Vec<(notify::Event, Instant)>>,
wake: Condvar,
@@ -277,6 +333,15 @@ impl DirState {
self.watch_tree(path, true, &mut discovered);
}
}
// VCS metadata directories (`.git`, `.git/worktrees/<name>`) need
// watches too: a worktree registered in the main gitdir writes its
// entry below `.git/worktrees`, and the events in a gitdir created
// 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.watch_tree(path, false, &mut discovered);
}
}
for path in &batch.removed {
self.unwatch_tree(path);
}
@@ -387,6 +452,7 @@ fn merge(prev: Option<Change>, next: Change) -> Change {
}
}
#[derive(Clone)]
pub(crate) struct EventFilter {
root: PathBuf,
excludes: SharedExcludes,
@@ -415,15 +481,29 @@ impl EventFilter {
let idx = comps.iter().position(|c| *c == ".git")?;
let rest = &comps[idx + 1..];
Some(match rest {
[one] => *one == "HEAD" || *one == "index" || *one == "packed-refs",
[first, ..] => *first == "refs" && !rest.last().is_some_and(|l| l.to_string_lossy().ends_with(".lock")),
[] => false,
// `refs` and `worktrees` are directories whose creation is itself a
// registration event (`git init`, the first `git worktree add`);
// they must surface even though the depth below them is handled
// separately.
[one] => matches!(one.to_str(), Some("HEAD" | "index" | "packed-refs" | "refs" | "worktrees" | "info")),
[first, ..] => {
let metadata = *first == "refs"
// Linked-worktree gitdirs: a worktree added or removed below
// the project writes its HEAD here.
|| *first == "worktrees";
metadata && !rest.last().is_some_and(|l| l.to_string_lossy().ends_with(".lock"))
}
// The `.git` path itself: a linked worktree's `.git` is a plain
// file (gitfile), and it is the only marker a new worktree writes
// inside its own directory.
[] => true,
})
}
/// Whether a directory deserves its own watch in per-directory mode: not
/// excluded or git-ignored; inside `.git` only the directory itself and
/// `refs/` (HEAD, index and refs are what VCS refresh needs).
/// excluded or git-ignored; inside `.git` the directory itself, `refs/`
/// and `worktrees/` (HEAD, index, refs and worktree metadata are what VCS
/// refresh needs).
pub fn should_watch_dir(&self, dir: &Path) -> bool {
let Ok(rel) = dir.strip_prefix(&self.root) else { return false };
if rel.as_os_str().is_empty() {
@@ -435,6 +515,7 @@ impl EventFilter {
return match rest.as_slice() {
[] => true,
[first, ..] if *first == "refs" => true,
[first, ..] if *first == "worktrees" => true,
[only] => *only == "info",
_ => false,
};
@@ -690,7 +771,18 @@ mod tests {
assert_eq!(g(".git/refs/heads/main"), Some(true));
assert_eq!(g(".git/refs/heads/main.lock"), Some(false));
assert_eq!(g(".git/objects/aa/bb"), Some(false));
assert_eq!(g(".git"), Some(false));
// The `.git` path itself: a repo dir, or a linked worktree's gitfile.
assert_eq!(g(".git"), Some(true));
assert_eq!(g("wt/.git"), Some(true));
// Linked-worktree gitdir metadata below the main repository.
assert_eq!(g(".git/worktrees/wt/HEAD"), Some(true));
assert_eq!(g(".git/worktrees/wt/index.lock"), Some(false));
// The depth-1 directories themselves: `git init` or the first
// `git worktree add` creates them in an already-watched gitdir.
assert_eq!(g(".git/refs"), Some(true));
assert_eq!(g(".git/worktrees"), Some(true));
assert_eq!(g(".git/info"), Some(true));
assert_eq!(g(".git/objects"), Some(false));
}
#[test]
@@ -744,6 +836,9 @@ mod tests {
assert!(!w("build") && w("src/build"));
assert!(w(".git") && w(".git/refs") && w(".git/refs/heads") && w(".git/info"));
assert!(!w(".git/objects") && !w(".git/objects/ab") && !w(".git/logs"));
// Linked-worktree gitdirs are watched so worktrees added below the
// project while it is open are discovered.
assert!(w(".git/worktrees") && w(".git/worktrees/wt") && w(".git/worktrees/wt/rebase-merge"));
assert!(!filter.should_watch_dir(Path::new("/elsewhere")));
// Excludes are replaced in place (Watcher::set_excludes).
*filter.excludes.write() = ExcludeMatcher::new(&["gen".into()]);
@@ -753,7 +848,7 @@ mod tests {
fn watcher_state(w: &Watcher) -> &DirState {
match &w.inner {
Inner::PerDirectory { state, .. } => state,
Inner::Recursive(_) => panic!("not per-directory"),
Inner::Recursive(_) | Inner::Polling(_) => panic!("not per-directory"),
}
}
@@ -861,6 +956,51 @@ mod tests {
assert_eq!(batches.lock().len(), n, "no events after drop");
}
#[test]
fn per_directory_mode_follows_worktree_registrations() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
for d in ["wt", ".git/refs/heads"] {
std::fs::create_dir_all(root.join(d)).unwrap();
}
// The worktree's gitfile is written before any watch on the worktree
// directory could register it — the same window a real
// `git worktree add` runs into.
std::fs::write(root.join("wt/.git"), "gitdir: ../.git/worktrees/wt\n").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::new(),
sink,
Box::new(move |b| batches.lock().push(b.clone())),
WatchMode::PerDirectory,
)
.unwrap()
};
// Registering the worktree in the main gitdir surfaces as VCS metadata
// (the deepest directory itself may be created before its parent gains
// a watch, so `.git/worktrees` is the event that reliably fires)...
std::fs::create_dir_all(root.join(".git/worktrees/wt")).unwrap();
assert!(
wait_for(&batches, |b| b.iter().any(|b| b.vcs.contains(&root.join(".git/worktrees")))),
"{:?}",
batches.lock()
);
// ...and the registered gitdir gains a watch, so writes inside it are
// seen even though nothing reported the directory itself.
std::thread::sleep(Duration::from_millis(200));
std::fs::write(root.join(".git/worktrees/wt/HEAD"), "ref: refs/heads/topic\n").unwrap();
assert!(
wait_for(&batches, |b| b.iter().any(|b| b.vcs.contains(&root.join(".git/worktrees/wt/HEAD")))),
"{:?}",
batches.lock()
);
drop(watcher);
}
#[test]
fn flat_mode_reports_the_roots_own_entries_only() {
let tmp = tempfile::tempdir().unwrap();
@@ -886,4 +1026,48 @@ mod tests {
std::thread::sleep(Duration::from_millis(300));
assert!(!all_paths(&batches.lock()).contains(&root.join("sub/deep.txt")));
}
/// The fallback used when the OS watcher cannot start.
fn polling_watcher(root: &Path, excludes: Vec<String>, batches: Arc<Mutex<Vec<FsBatch>>>) -> Watcher {
let filter = EventFilter::new(root.to_path_buf(), &excludes);
let (excludes, rules) = (filter.excludes.clone(), filter.gitignore.clone());
let emit: Emit = Arc::new(move |b: &FsBatch| batches.lock().push(b.clone()));
let inner = Watcher::start_polling(root, filter, emit, WatchMode::default()).unwrap();
Watcher { inner, excludes, rules, polling: Some("cannot start file watcher".into()) }
}
#[test]
fn polling_skips_excluded_dirs_and_follows_new_ones() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
for d in ["src/a", "node_modules/x"] {
std::fs::create_dir_all(root.join(d)).unwrap();
}
let batches: Arc<Mutex<Vec<FsBatch>>> = Arc::default();
let watcher = polling_watcher(&root, vec!["**/node_modules".into()], batches.clone());
// root, src, src/a
assert_eq!(watcher.watch_count(), 3);
std::fs::write(root.join("node_modules/x/z.js"), "x").unwrap();
std::fs::write(root.join("src/a/f.rs"), "x").unwrap();
std::fs::create_dir_all(root.join("src/new/inner")).unwrap();
std::fs::write(root.join("src/new/inner/g.rs"), "x").unwrap();
assert!(
wait_for(&batches, |b| {
let paths = all_paths(b);
paths.contains(&root.join("src/a/f.rs")) && paths.contains(&root.join("src/new/inner/g.rs"))
}),
"{:?}",
batches.lock()
);
let paths = all_paths(&batches.lock());
assert!(!paths.iter().any(|p| p.starts_with(root.join("node_modules"))), "{paths:?}");
// Folders whose entries changed aren't reported as modified, as with inotify.
assert!(!paths.contains(&root.join("src")) && !paths.contains(&root.join("src/a")), "{paths:?}");
assert_eq!(watcher.watch_count(), 5);
// Later writes inside a new folder are seen through its own poll.
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"))));
}
}
+71 -11
Переглянути файл
@@ -173,7 +173,12 @@ async fn read_head(sock: &mut TcpStream) -> std::io::Result<Option<Request>> {
}
enum Response {
File { path: PathBuf, len: u64 },
/// `path` is the resolved file to open; `mime` comes from the requested name.
File {
path: PathBuf,
len: u64,
mime: &'static str,
},
Redirect(String),
Error(u16, &'static str),
}
@@ -191,9 +196,9 @@ async fn serve(mut sock: TcpStream, shared: &Shared, port: u16) -> std::io::Resu
};
let mut out = String::new();
match &response {
Response::File { path, len } => {
Response::File { len, mime, .. } => {
out.push_str("HTTP/1.1 200 OK\r\n");
out.push_str(&format!("Content-Type: {}\r\nContent-Length: {len}\r\n", content_type(path)));
out.push_str(&format!("Content-Type: {mime}\r\nContent-Length: {len}\r\n"));
}
Response::Redirect(to) => {
out.push_str(&format!("HTTP/1.1 301 Moved Permanently\r\nLocation: {to}\r\nContent-Length: 0\r\n"));
@@ -233,10 +238,12 @@ async fn resolve(shared: &Shared, target: &str) -> Response {
return NOT_FOUND;
}
let Some(key) = segments.next().and_then(dec) else { return NOT_FOUND };
let Some(mut file) = shared.roots.read().get(&key).cloned() else { return NOT_FOUND };
let mut trailing_slash = true;
let Some(root) = shared.roots.read().get(&key).cloned() else { return NOT_FOUND };
let Ok(real_root) = tokio::fs::canonicalize(&root).await else { return NOT_FOUND };
let mut file = root;
// `/<token>/<key>` names a directory too: it redirects like any other.
let trailing_slash = path.ends_with('/');
for seg in segments {
trailing_slash = seg.is_empty();
if seg.is_empty() {
continue;
}
@@ -245,19 +252,29 @@ async fn resolve(shared: &Shared, target: &str) -> Response {
_ => return NOT_FOUND,
}
}
let Ok(meta) = tokio::fs::metadata(&file).await else { return NOT_FOUND };
let Some(real) = confined(&real_root, &file).await else { return NOT_FOUND };
let Ok(meta) = tokio::fs::metadata(&real).await else { return NOT_FOUND };
if meta.is_dir() {
// Relative URLs in an index page resolve against the directory.
if !trailing_slash {
return Response::Redirect(format!("{path}/"));
}
file.push("index.html");
return match tokio::fs::metadata(&file).await {
Ok(m) if m.is_file() => Response::File { path: file, len: m.len() },
let index = file.join("index.html");
let Some(real_index) = confined(&real_root, &index).await else { return NOT_FOUND };
return match tokio::fs::metadata(&real_index).await {
Ok(m) if m.is_file() => Response::File { path: real_index, len: m.len(), mime: content_type(&index) },
_ => NOT_FOUND,
};
}
Response::File { path: file, len: meta.len() }
Response::File { path: real, len: meta.len(), mime: content_type(&file) }
}
/// `path` with every symlink resolved, if it still lies inside `real_root` (already
/// canonical). Rejecting `..` segments is not enough: a project can commit symlinks
/// that point anywhere on disk.
async fn confined(real_root: &Path, path: &Path) -> Option<PathBuf> {
let real = tokio::fs::canonicalize(path).await.ok()?;
real.starts_with(real_root).then_some(real)
}
fn dec(s: &str) -> Option<String> {
@@ -330,6 +347,10 @@ mod tests {
let base = url.trim_end_matches("/web/index.html");
assert!(get(&format!("{base}/web/sub/a%20b.js"), None).await.contains("text/javascript"));
assert!(get(&format!("{base}/web"), None).await.contains("Location: /"));
// The served root itself, so relative URLs of its index page resolve inside it.
let page = get(base, None).await;
let root_path = base.trim_start_matches("http://").split_once('/').unwrap().1;
assert!(page.starts_with("HTTP/1.1 301") && page.contains(&format!("Location: /{root_path}/\r\n")), "{page}");
assert!(get(&format!("{base}/web/"), None).await.ends_with("<h1>hi</h1>"));
assert!(get(&format!("{base}/../secret.txt"), None).await.starts_with("HTTP/1.1 404"));
assert!(get(&format!("{base}/%2e%2e/secret.txt"), None).await.starts_with("HTTP/1.1 404"));
@@ -340,6 +361,45 @@ mod tests {
assert!(get(&url, Some("evil.example:80")).await.starts_with("HTTP/1.1 403"));
}
#[cfg(unix)]
#[tokio::test]
async fn symlinks_cannot_escape_the_served_root() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("repo");
std::fs::create_dir_all(root.join("site/escape")).unwrap();
std::fs::create_dir_all(root.join("site/assets")).unwrap();
std::fs::write(root.join("site/index.html"), "<h1>hi</h1>").unwrap();
std::fs::write(root.join("site/assets/app.js"), "export {}").unwrap();
std::fs::write(root.join("site/raw"), "<p>raw</p>").unwrap();
std::fs::write(dir.path().join("secret.txt"), "outside").unwrap();
symlink("index.html", root.join("site/inside.html")).unwrap();
symlink("assets", root.join("site/lib")).unwrap();
symlink("raw", root.join("site/raw.html")).unwrap();
symlink("../../secret.txt", root.join("site/leak.txt")).unwrap();
symlink("../..", root.join("site/up")).unwrap();
symlink("/", root.join("site/fsroot")).unwrap();
symlink("../../../secret.txt", root.join("site/escape/index.html")).unwrap();
let server = WebServer::new();
let url = server.url_for(Some(&root), &root.join("site/index.html")).await.unwrap();
let base = url.trim_end_matches("index.html");
let page = get(&format!("{base}inside.html"), None).await;
assert!(page.starts_with("HTTP/1.1 200") && page.ends_with("<h1>hi</h1>"), "{page}");
let page = get(&format!("{base}lib/app.js"), None).await;
assert!(page.starts_with("HTTP/1.1 200") && page.contains("text/javascript"), "{page}");
// The type follows the requested name, not the link target.
let page = get(&format!("{base}raw.html"), None).await;
assert!(page.contains("text/html") && page.ends_with("<p>raw</p>"), "{page}");
let secret = dir.path().join("secret.txt");
let via_fsroot = format!("fsroot{}", secret.display());
for escape in ["leak.txt", "up/secret.txt", via_fsroot.as_str(), "escape/"] {
let page = get(&format!("{base}{escape}"), None).await;
assert!(page.starts_with("HTTP/1.1 404"), "{escape}: {page}");
}
}
#[tokio::test]
async fn files_outside_the_project_get_their_own_root() {
let dir = tempfile::tempdir().unwrap();
+25 -5
Переглянути файл
@@ -821,6 +821,17 @@ impl Documents {
/// Re-checks open file buffers, including files outside the watched roots.
/// Call from a blocking worker; unchanged files only need their metadata.
pub fn sync_from_disk(&self) {
self.sync_open_documents(false);
}
/// Refreshes clean buffers after an IDE operation rewrites files. Such an
/// operation can preserve both file length and the timestamp's millisecond.
/// The open document's selected codec is retained.
pub fn sync_after_disk_change(&self) {
self.sync_open_documents(true);
}
fn sync_open_documents(&self, force_clean: bool) {
let slots: Vec<Slot> = self.registry.lock().docs.values().map(|e| e.slot.clone()).collect();
let paths: Vec<PathBuf> = slots
.iter()
@@ -830,13 +841,17 @@ impl Documents {
.then(|| st.path.clone())
})
.collect();
self.on_disk_changed(&paths);
self.reload_from_disk(&paths, force_clean);
}
/// Re-reads from disk after an external change. Clean documents reload
/// silently; dirty ones are left alone and reported via `IdeEvent::Notify`.
/// Changes matching our own last save are ignored.
pub fn on_disk_changed(&self, paths: &[PathBuf]) {
self.reload_from_disk(paths, false);
}
fn reload_from_disk(&self, paths: &[PathBuf], force_clean: bool) {
for path in paths {
let Some(id) = self.by_path(path) else { continue };
let result = self.with_doc(id, |st| {
@@ -845,7 +860,7 @@ impl Documents {
}
let Ok(meta) = std::fs::metadata(&st.path) else { return Ok(()) };
let mtime = ide_vfs::mtime_ms(&meta);
if mtime == st.disk_mtime && meta.len() == st.disk_len {
if mtime == st.disk_mtime && meta.len() == st.disk_len && (!force_clean || st.dirty) {
return Ok(());
}
if st.dirty {
@@ -863,9 +878,14 @@ impl Documents {
});
return Ok(());
}
let defaults = self.file_defaults();
let loaded = Self::load_with_defaults(&st.path, &defaults)?;
st.native_to_ascii = defaults.native_to_ascii_for(&st.path);
let loaded = if force_clean {
Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?
} else {
let defaults = self.file_defaults();
let loaded = Self::load_with_defaults(&st.path, &defaults)?;
st.native_to_ascii = defaults.native_to_ascii_for(&st.path);
loaded
};
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
if loaded.binary || st.binary {
+31
Переглянути файл
@@ -57,6 +57,37 @@ fn fixture() -> Fixture {
Fixture { _tmp: tmp, root, docs, events, rec }
}
#[test]
fn own_disk_changes_preserve_the_open_documents_encoding() {
let f = fixture();
let path = f.root.join("query.sql");
let original = "SELECT '中文';\r\n";
fs::write(&path, ide_vfs::encode(original, "gbk", false).unwrap()).unwrap();
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = "gbk".into();
f.docs.set_file_defaults(defaults.clone());
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "gbk");
defaults.project_fallback = "windows-1252".into();
f.docs.set_file_defaults(defaults);
f.docs.sync_after_disk_change();
let unchanged = f.docs.snapshot(doc.id).unwrap();
assert_eq!(unchanged.text, doc.text);
assert_eq!(unchanged.encoding, "gbk");
assert!(!unchanged.dirty);
let changed = "SELECT '世界';\r\n";
let bytes = ide_vfs::encode(changed, "gbk", false).unwrap();
fs::write(&path, &bytes).unwrap();
f.docs.sync_after_disk_change();
let reloaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!(reloaded.text, changed.replace("\r\n", "\n"));
assert_eq!(reloaded.encoding, "gbk");
assert_eq!(reloaded.line_ending, LineEnding::CrLf);
assert!(!reloaded.dirty);
f.docs.save_all().unwrap();
assert_eq!(fs::read(&path).unwrap(), bytes);
}
fn change(from: u32, to: u32, insert: &str) -> ChangeSet {
ChangeSet { changes: vec![TextChange { from, to, insert: insert.into() }] }
}
+2 -2
Переглянути файл
@@ -109,8 +109,8 @@ There is no build step. The package *is* the folder.
1. Copy `templates/theme-plugin` and rename `id`, `name` and the theme files.
2. Edit the colours. Keep `kind` truthful (`light` for light backgrounds).
3. **Install:** *Settings › Plugins › ⚙ › Install Plugin from Disk…* (or the
*Install Plugin from Disk…* action) and pick the package folder. The
manifest and the files it references are copied to
*Install Plugin from Disk…* action) and pick the package's `plugin.toml`, or
a `.zip` of the folder. The manifest and the files it references are copied to
`<app-data>/plugins/<id>/`.
4. **Apply:** in *Settings › Plugins*, select the plugin and press *Apply* next
to the theme. *Use Default Theme* switches back.
+1 -1
Переглянути файл
@@ -28,7 +28,7 @@ The specialized Maven/Gradle tool-window model still describes the workspace dir
Open two project windows, then use **Window → Merge All Project Windows**. The project tabs occupy their own row below the main toolbar. Click a tab or use **Next/Previous Project Tab** to switch; drag tabs to reorder them. The default shortcuts are ⌥⌘PageDown/PageUp on macOS and Ctrl+Alt+PageDown/PageUp on Windows/Linux.
Use the tab's close button to close that project, or **Move Tab to New Window** to detach the current tab. Closing uses the existing unsaved-changes guard. Quit visits project windows in sequence so a hidden project's prompt is visible. Groups restore when **Reopen last project** is enabled.
Use the tab's close button to close that project, or **Move Tab to New Window** to detach the current tab. Right-click a tab for **Close Other Tabs**, **Close Tabs to the Left** and **Close Tabs to the Right**, which close the projects one at a time and keep the clicked tab; cancelling one project's unsaved-changes prompt leaves it and the rest open. The same commands are in the Command Palette and can be assigned shortcuts. Closing uses the existing unsaved-changes guard. Quit visits project windows in sequence so a hidden project's prompt is visible. Groups restore when **Reopen last project** is enabled.
The grouping model lives in `ide-workspace`, independently of project ownership. The desktop adapter keeps each member's WebView and backend services alive, presents the selected window at the group's position/size, and hides its peers. This is an application-drawn tab strip, not the macOS native tab strip. Its persistence is application-local in `window-groups.json`. Language servers, terminals, editor buffers and settings remain independent between group members.
+21
Переглянути файл
@@ -82,3 +82,24 @@ test("preserves all lines in a drag selection across virtual windows", async ({
expect(text).toContain("output 250\noutput 251");
expect(text).toContain("output 284");
});
test("Select All takes the whole buffer, not just the mounted rows", async ({ page }) => {
const log = await consoleOutput(page);
await page.evaluate(() => {
(window as unknown as { copied: string[] }).copied = [];
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText: async (text: string) => (window as unknown as { copied: string[] }).copied.push(text) },
});
});
await log.focus();
await page.keyboard.press("Meta+A");
// Selection stays inside the console: nothing from the workbench behind it is selected.
const selected = await page.evaluate(() => window.getSelection()?.toString() ?? "");
expect(selected).not.toContain("Project");
await page.keyboard.press("Meta+C");
const [copied] = await page.evaluate(() => (window as unknown as { copied: string[] }).copied);
expect(copied?.split("\n")).toHaveLength(500);
expect(copied).toContain("output 0\n");
expect(copied).toMatch(/output 499$/);
});
+19
Переглянути файл
@@ -28,3 +28,22 @@ test("the scrollbar thumb drags even where overview marks cover it (#752)", asyn
await page.mouse.move(x, box.y + box.height - 20);
await expect(editor.locator(".cm-openidea-overview")).not.toHaveClass(/cm-openidea-overview-onThumb/);
});
test("the scrollbar thumb shows over a mark the height of the lane (#1014)", async ({ workbench: page }) => {
const editor = await openFromTree(page, "build.gradle.kts");
await editor.locator(".cm-content").click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText(Array.from({ length: 400 }, (_, i) => `val mark${i} = ${i}`).join("\n"));
await page.keyboard.press("Meta+f");
await page.getByRole("textbox", { name: "Find" }).fill("mark");
await expect(editor.locator(".cm-openidea-overviewMark").first()).toBeVisible();
const thumb = editor.locator(".cm-openidea-overviewThumb");
await expect(thumb).toBeVisible();
// Drawn last in the lane, so it paints over every mark.
expect(await thumb.evaluate((t) => t.nextElementSibling)).toBeNull();
const scroller = editor.locator(".cm-scroller");
const top = async () => (await thumb.boundingBox())!.y;
const before = await top();
await scroller.evaluate((s) => (s.scrollTop = s.scrollHeight));
await expect.poll(top).toBeGreaterThan(before + 100);
});
+47
Переглянути файл
@@ -0,0 +1,47 @@
import { expect, test } from "@playwright/test";
test("local terminal stores clipboard media and pastes one shell-quoted argument", async ({ page }) => {
await page.goto("/");
const observed = await page.evaluate(async () => {
const ipcPath = "/src/platform/ipc.ts";
const sessionPath = "/src/features/terminal/session.ts";
const { commands } = await import(ipcPath);
const { TerminalSession } = await import(sessionPath);
Object.defineProperty(window, "__TAURI_INTERNALS__", {
configurable: true,
value: { transformCallback: () => 1 },
});
const stored: { id: number; data: number[]; mime: string }[] = [];
const writes: string[] = [];
commands.termSpawn = async () => ({ status: "ok", data: { id: 838, title: "pwsh", pid: 1 } });
commands.clipboardFileList = async () => ({ status: "ok", data: [] });
commands.termStoreImage = async (id: number, data: number[], mime: string) => {
stored.push({ id, data, mime });
return { status: "ok", data: "C:\\Temp\\a'b c\\image.png" };
};
commands.termWrite = async (_id: number, data: string) => writes.push(data);
commands.termResize = async () => undefined;
commands.termKill = async () => undefined;
const container = document.createElement("div");
container.style.cssText = "position:fixed;inset:0;z-index:99999";
document.body.append(container);
const session = new TerminalSession({ key: "clipboard", cwd: "C:/Temp", onChange() {}, onFocus() {} });
try {
session.attach(container);
await session.start();
const transfer = new DataTransfer();
transfer.items.add(new File([new Uint8Array([137, 80, 78, 71])], "image.png", { type: "image/png" }));
const event = new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: transfer });
container.querySelector("textarea")!.dispatchEvent(event);
const deadline = Date.now() + 5000;
while (!writes.length && Date.now() < deadline) await new Promise((resolve) => requestAnimationFrame(resolve));
return { stored, writes, claimed: event.defaultPrevented };
} finally {
session.dispose();
container.remove();
}
});
expect(observed.claimed).toBe(true);
expect(observed.stored).toEqual([{ id: 838, data: [137, 80, 78, 71], mime: "image/png" }]);
expect(observed.writes).toEqual(["'C:\\Temp\\a''b c\\image.png'"]);
});
+1
Переглянути файл
@@ -5,6 +5,7 @@ const config: KnipConfig = {
project: [
"src/**/*.{ts,tsx,css}",
"!src/editor/core/cm/angular/parser.terms.ts",
"!src/editor/core/cm/jsp/parser.terms.ts",
"scripts/**/*.ts",
"perf/**/*.ts",
"e2e/**/*.ts",
+6
Переглянути файл
@@ -0,0 +1,6 @@
id = "erb"
name = "ERB"
extensions = ["erb", "html.erb", "rhtml", "js.erb", "text.erb", "xml.erb", "json.erb"]
block-comment = ["<%#", "%>"]
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "ERB"
+6
Переглянути файл
@@ -0,0 +1,6 @@
id = "jsp"
name = "JSP"
extensions = ["jsp", "jspx", "jspf", "jsph", "tag", "tagf", "tagx"]
block-comment = ["<%--", "--%>"]
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "JSP"
+8
Переглянути файл
@@ -40,6 +40,14 @@ args = ["server"]
root-markers = ["ty.toml", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"]
install-hint = "uv tool install ty (or: pip install ty)"
[[language-servers]]
name = "pyrefly"
fallback = true
command = "pyrefly"
args = ["lsp"]
root-markers = ["pyrefly.toml", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"]
install-hint = "uv tool install pyrefly (or: pip install pyrefly)"
# Lint, format, organize imports and fix all next to the type checker, in
# projects configured for Ruff (formatting is Ruff's alone: basedpyright has none).
[[language-servers]]
+2
Переглянути файл
@@ -19,6 +19,7 @@
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p scripts --noEmit",
"gen:bindings": "cargo test -p openidea --test export_bindings",
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
"gen:jsp-grammar": "lezer-generator src/editor/core/cm/jsp/jsp.grammar --typeScript -o src/editor/core/cm/jsp/parser.ts",
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
"theme:import-intellij": "node scripts/theme/import-intellij-theme.ts",
"dev:app": "node scripts/tauri.ts dev --config src-tauri/tauri.dev.conf.json",
@@ -39,6 +40,7 @@
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-java": "^6.0.2",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/language": "^6.13.1",
"@codemirror/language-data": "^6.5.2",
+8 -5
Переглянути файл
@@ -53,14 +53,17 @@ files for disk discovery. It does not guess a global association from matching
text in unrelated projects.
Indexing is lazy. The first explicit navigation/search builds a compact snapshot;
ordinary typing, code-lens probes and bulk scoped reference analysis do not start indexing. At most eight project snapshots are
ordinary typing, code-lens probes, bulk scoped reference analysis, and Java Go to Definition / Ctrl+hover outside a `@Value` or property-lookup argument (checked with the bundled tree-sitter grammar) do not start indexing. At most eight project snapshots are
retained, with a shared 100,000-association retention cap. Records contain property names, element handles and source locations;
ASTs and bindings are discarded after indexing. A lexical prefilter avoids AST
construction for ordinary Java units, but every accepted association is resolved
semantically. Warm requests reuse the snapshot. Java model/reconcile changes
invalidate it conservatively, including dependent-type changes; open working-copy
content fingerprints also prevent stale answers before reconciliation. This is
**snapshot invalidation**, not a fully incremental Java semantic index.
semantically. Warm requests reuse the snapshot. Java model changes (sources on
disk, classpath, archives) invalidate it conservatively, including dependent-type
changes; a fingerprint of working copies with unsaved changes covers edits before
they are saved. Opening or closing an editor, reconciling, building, and non-Java
resource changes (configuration files are parsed by the client; metadata files are
checked by timestamp) keep it. This is **snapshot invalidation**, not a fully
incremental Java semantic index.
Metadata/JAR timestamps are checked before reuse. The client caches parsed disk
configuration files by modification time and size (at most 100,000 cached keys), overlays open buffers, and
+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.2.0
Bundle-Version: 1.2.1
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
Loaded 100 of 262 files, more files were not shown because too many files have changed in this diff. Show more