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

...
Автор SHA1 Повідомлення Дата
l0ng-ai df46735e82 chore: Regenerate bindings 2026-10-25 00:44:21 +08:00
l0ng-ai fb3d42b76d feat: Align editor, workbench, run/debug and VCS interactions with IntelliJ IDEA
Keymap
- Let AltGr characters through instead of firing Ctrl+Alt shortcuts (Windows/Linux)
- Double Shift: strict press/release timing, ignored while typing or after Shift+click
- Chords wait 2s and swallow an unmatched second stroke
- Drop CodeMirror defaults that clash with IDEA keys; ⌘Enter is Split Line, add
  Scroll to Center and Code Block Start/End
- Add missing IDEA defaults (⌃J, ⌘Y, ⇧⌘C, ⌥⌘Y, ⇧⌘M, F9 Resume, ⌘R Rerun, …)

Editor
- Tab inserts at the caret; smart Backspace to the proper indent; Enter continues
  a `//` comment; per-language line comment placement
- Back/Forward records navigations only; ⌘F searches the selected text
- In-place rename; ⌃Space inserts a sole candidate; commit characters only for a
  focused lookup; usage highlighting survives edits; ⌥Enter offers fixes from the
  caret line; ⌘-hover shows declaration info only for navigable targets

Workbench
- Tool windows: primary and split area per side, six Move To anchors, layout migration
- ⌘W closes tool window content; Shift+Esc from the editor; closing a tab
  activates the left neighbour; preview tab and tab limit follow IDEA defaults
- Switcher lists open editors and tool windows; Recent Files Delete removes items
- Search Everywhere tab/scope behaviour; popups close when the window deactivates
- Project view: Copy/Move dialogs on paste, skippable usage search on delete,
  new-file input cancels on blur; Settings search Esc clears the filter
- Status bar breadcrumbs open a children popup; notification timeouts

Run / Debug / Build / Terminal
- Run asks to stop a running single-instance config; Rerun restarts silently;
  "Allow multiple instances" option
- Run chooser: Enter runs, Shift debugs, F4/Delete/digits
- Type into the console for stdin; Stop covers debug sessions
- Log (Shift+click) and temporary (Alt+click) breakpoints; independent suspend/log
  options; Evaluate prefill and history; changed-value highlighting; expandable hints
- Build window opens on failure and jumps to the first error
- Terminal confirms closing a busy tab and lets IDE shortcuts through

VCS
- Correct ours/theirs labels during rebase, cherry-pick and revert
- Smart/Force Checkout; remote branch checkout updates the local branch
- Partial commit by changed block; inline before-commit check results
- F7 continues into the next file; Rollback Lines; Commit and Push; Amend message swap
- Branch delete with Restore; force push confirmation; editable push target;
  update summary with the incoming commits
2026-10-25 00:35:33 +08:00
l0ng-ai 68dcea409c feat(nav): Complete file paths and flag unresolved web file references
Path completion in href/src/url()/@import, Markdown links and path-like strings, folders first. HTML and CSS paths that name no file get a 'Cannot resolve file' warning. File references resolve in the backend like IDEA's: relative to the file, /-rooted against the project and resource roots.
2026-10-24 23:28:20 +08:00
l0ng-ai 87b463990c feat(nav): Follow links, file paths and CSS references with Go to Declaration
Go to Declaration and Cmd-click said "Cannot find declaration" on HTML href/src, CSS url() and @import, Markdown links and CSS selectors: language servers expose paths as document links, not definitions, and none resolves class/id to selectors.

- ide-lsp: textDocument/documentLink (lsp_document_links), resolving links that lack a target.
- Editor: when the server has no definition, follow its document links, then URLs and quoted / Markdown / url() paths in any language. Server file links are checked to exist; root-relative paths also resolve against resource roots. Cmd-hover underlines the whole link.
- ide-language: tree-sitter web references (class / id attributes, href="#id", var(--x)) and .class / #id / --var definitions from stylesheets and <style> elements, indexed as symbols. web_goto looks them up by exact name (ProjectIndex::symbols_named), using the open document's unsaved text.
- Detect public/ of package.json modules as a resource root (Vite, Next, CRA serve it at /).
2026-10-24 22:58:23 +08:00
l0ng-ai 046fd37064 fix(ui): Match PyCharm project view, matched tags and text weight
- Project widget initials follow IDEA's AvatarUtils.initials ("idea" → "I").
- "Show directories with changed descendants" is off by default, as in IDEA.
- FileEntry gains `excluded`: only excluded folders get the excluded icon and
  dimming; git-ignored ones keep the plain icon and the ignored colour.
- `.github` folders get IDEA's GitHub folder icon.
- Matched tag names are never bold and use their own background
  (MATCHED_TAG_NAME); matched braces are bold in dark schemes only.
- Revert Greyscale antialiasing to `antialiased` for UI and editor; `auto`
  rendered text heavier than PyCharm.

Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 22:56:48 +08:00
l0ng-ai cacddee19d feat(web): Open HTML in browsers with a built-in server; add Emmet
- ide-web: built-in static server on 127.0.0.1 that serves project files,
  plus detection and launching of installed browsers.
- Open In › Browser in the editor, project view and tab menus; browser bar
  and built-in preview beside HTML editors; ⌃⇧R opens the default browser.
- Emmet: Tab expansion in markup editors and Update Tag with Emmet.

Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 22:16:28 +08:00
l0ng-ai c8cea62eab fix(editor): Match PyCharm syntax colours and text weight
Greyscale antialiasing mapped to `-webkit-font-smoothing: antialiased`,
which drops macOS stem darkening, so editor and UI text rendered thinner
and syntax colours looked lighter than PyCharm's. Use `auto` instead.

Align lezer tag mappings with PyCharm's Light scheme:
- HTML/XML: `<!doctype>` is plain text (documentMeta is a sub-tag of meta).
- CSS/SCSS/Sass: property names use the attribute colour; values and units
  the attribute-value colour; class, id, pseudo, colour and url() the tag colour.
- YAML: keys are keywords.
- Markdown: quotes are strings with keyword markers, link destinations
  italic function colour, titles strings, horizontal rules keywords.

Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 22:16:16 +08:00
l0ng-ai 4a2d5c9599 chore: v0.1.12
Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 18:26:59 +08:00
l0ng-ai 059f25f13e feat(java): Separate the jdtls JDK and add Settings for New Projects (#21)
- Languages & Frameworks › Java › Language Server › JDK (languages.java.jdtlsJdk) runs jdtls on its own JDK, like IDEA's JDK for importer; the project keeps compiling and running with the Project JDK.
- Toolchain pages get the Global / This project switch (default This project); Global shows and edits the global layer.
- File › New Projects Setup › Settings for New Projects… edits only the global layer, which new projects inherit.
- Configuration errors (launch_error) show as "Not started" instead of "Crashed".

Fixes #18
Fixes #19

Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 18:26:31 +08:00
@鹿таl0ng-ai a765959d48 fix(process): Spawn child processes without a console window (#17)
- The IDE is a GUI-subsystem binary, so Windows allocated a fresh console
  window for every console-subsystem child it started: one black window per
  language server, per settings-driven restart, per debug adapter and per
  toolchain probe, titled with the child's own path. Closing it killed the
  child, which is how editing the language-server settings broke highlighting.
- Peer::spawn, the spawn point for every language server, wired stdio but never
  passed CREATE_NO_WINDOW. The rustup-proxy probe, the DAP adapter, debugpy
  probe, runInTerminal and cargo spawns, the SDK probes, the run-configuration
  probes, the coverage exporter and tool diagnostics/downloads (curl, tar) had
  the same gap, while git, cargo builds, gh, docker and run configurations
  passed the flag inline — five copies of the magic constant, six subsystems
  without it.
- Add ide_core::process::{CREATE_NO_WINDOW, hide_console_window} as the single
  definition, route every spawn through it (tokio commands via as_std_mut()) and
  fold the inline copies into it.
- Verified locally on Windows with a console-detached harness: a plain spawn
  reports a visible console window (GetConsoleWindow + IsWindowVisible), the
  patched Peer::spawn reports a console without a window. cargo check, cargo
  clippy --all-targets and the affected test suites (249 tests) are green.

Co-authored-by: l0ng-ai <[email protected]>
2026-10-24 16:57:34 +08:00
l0ng-ai efbb48c3cb chore: v0.1.11 2026-10-24 16:32:25 +08:00
l0ng-ai bb9486c758 fix(app): Stop console tools from opening cmd windows on Windows (#20)
Release builds use the GUI subsystem, so a console child spawned without
CREATE_NO_WINDOW gets its own console window. git, gh, docker, builds and
run configurations already set the flag; language servers, SDK and tool
probes, debug adapters, tool downloads, coverage export and perf did not.
Add ide_core::process::no_window and use it at every remaining spawn.

Fixes #16
2026-10-24 16:31:50 +08:00
l0ng-ai 5c0c3a009c docs: Keep the demo video as the README's only hero 2026-10-24 14:50:08 +08:00
l0ng-ai ef667f6e21 chore: v0.1.10 2026-10-24 14:48:53 +08:00
l0ng-ai 81b43a52b4 docs: Trim the README to a link row, screenshots and the benchmark 2026-10-24 14:48:31 +08:00
l0ng-ai 0bb730039d feat(search): Bring Search Everywhere closer to IDEA's popup
- All tab interleaves classes, files, symbols, actions and text by match
  degree, keeping each source's own order; Enter waits for every source
  except a text search the top row already beats.
- Preview pane under the list (remembered toggle), reusing CodePreview.
- "/" lists scope commands; "/files q" switches scope and searches q.
- Per-tab search history: magnifier dropdown and ⌥↑ / ⌥↓.
- Text hits: syntax colouring, IDEA's boxed-T icon, dimmed repeated file
  names, collapsed indentation.
- Flat scope chooser, IDEA header icons, wider popup with a stable list
  height; the list shrinks so the footer stays visible.
2026-10-24 14:47:45 +08:00
l0ng-ai 709e1eb855 docs: Drop the feature list from the README 2026-10-24 14:46:31 +08:00
l0ng-ai 4473324822 docs: Recapture the README editor screenshot with a focused window 2026-10-24 14:45:35 +08:00
l0ng-ai 5d5b3e4791 docs: Recapture README screenshots with the native window frame 2026-10-24 14:36:44 +08:00
l0ng-ai c5b4b71e30 docs: Lay out README screenshots as a hero plus an even pair 2026-10-24 14:34:29 +08:00
l0ng-ai 0e299ad936 docs: Add download links, screenshots and a feature list to the README 2026-10-24 14:31:17 +08:00
Richardтаl0ng-ai 5b8e0b9659 feat(i18n): 新增简体中文界面翻译 (#15)
* feat(i18n): 新增简体中文界面翻译

* test(i18n): 补充中文界面截图与端到端验证

* fix(i18n): Translate notifications and usages through catalog templates

Move the hard-coded Chinese notification patterns into source-text
templates (`{name} failed`) applied at render time, so text follows
locale switches and stays English under en. Use useTx in Search
Everywhere and add its missing zh strings.

* chore: Drop i18n screenshots

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-10-24 14:14:43 +08:00
l0ng-ai 3d8a6f07b4 feat(app): Enable signed auto-updates from GitHub releases
Configure the updater public key and the releases/latest latest.json
endpoint, and build updater artifacts so tauri-action uploads signatures
and latest.json. Check for updates once per app start (release builds
only) and offer Install and Restart when one is available.
2026-10-24 14:13:12 +08:00
l0ng-ai 99b4f8bdf6 fix(terminal): Render with xterm's DOM renderer
The WebGL renderer rasterizes each glyph against its cell background, so
text over the selection came out at a visibly lighter weight than the
rest and looked like a different font. The DOM renderer draws text like
the editor does, selected or not.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 13:42:07 +08:00
l0ng-ai 86f1f666d7 chore: v0.1.9
Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 13:15:41 +08:00
l0ng-ai be49490153 feat(terminal): Align the terminal with IDEA's tabs, menu and settings
- ⌘T (Ctrl+Shift+T on Windows) opens a terminal tab while the terminal
  has focus; elsewhere the key keeps its IDE action.
- The tab bar's ▾ menu lists installed shells under "New Predefined
  Session" (login shell, shell integration) and links to Settings.
- Settings › Tools › Terminal: pick the shell path from the installed
  shells or browse for one, "Move focus to the Editor with Escape",
  fallback font, column width and a link to the Terminal keymap.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 13:02:52 +08:00
l0ng-ai 1f5fcb477d fix(terminal): Default to the account's login shell
$SHELL is inherited from whatever launched the app, so starting it from a
terminal running bash opened bash even when the login shell is zsh. Read
the passwd entry first and fall back to $SHELL.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 12:36:40 +08:00
l0ng-ai 1bb454bd2f fix(terminal): Match the xterm scrollbar to the IDE's
Style xterm's own scrollbar slider with the scrollbar tokens, narrow it to
10px and blend the overview ruler border into the background.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 12:36:40 +08:00
l0ng-ai f38f63e397 test(e2e): Drive the Language Servers page through its list and details
The page is no longer a table: pick the tool in the list, then act in
its details pane. Fixes the Frontend CI failures since v0.1.7.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 12:11:21 +08:00
l0ng-ai 08d87c3903 chore: v0.1.8 2026-10-24 11:47:57 +08:00
l0ng-ai 1652866769 fix(workbench): Drag tool window stripe buttons with pointer events
With the window's native file drop enabled, the webview never receives
dragover / drop for HTML5 drags that start inside it, so stripe buttons
could not be moved. Track the drag with pointer events instead: a ghost
follows the pointer, the drop line shows the target, Escape cancels, and
an empty right stripe appears as a drop target while dragging.
2026-10-24 11:47:02 +08:00
l0ng-ai be5a6f62ad feat(editor): JetBrains-style line-number gutter context menu
Right-click on the gutter now shows Annotate with Git Blame, Add/Remove
Bookmark, Soft-Wrap, Configure Soft Wraps, an Appearance submenu and
Configure Gutter Icons, contributed through a new "editorGutter" menu
group. A breakpoint line still opens the breakpoint popover.
2026-10-24 11:38:08 +08:00
l0ng-ai f5e8d77dcf chore: v0.1.7
Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:34:42 +08:00
l0ng-ai c3ea376899 feat(tools): Install 15 more language servers and debug adapters
Release downloads: buf, clojure-lsp, texlab, neocmakelsp, LemMinX, Perl
Navigator, kotlin-language-server, kotlin-debug-adapter and netcoredbg;
Open VSX: bash-debug and php-debug (run through node). Two new methods:
`gem` (ruby-lsp, solargraph), installed into the tool's folder and
launched with GEM_HOME, and `dotnet tool` (csharp-ls, fsautocomplete),
launched with DOTNET_ROOT so a Homebrew / user-local .NET is found.
Tools declare the runtime they need (Java, Node.js, Perl).

Each was installed from its real source and started on macOS arm64.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai fde075457b feat(editor): Tree-sitter highlighting for Zig, Nix, Make, GraphQL and HCL
Every grammar-only language now gets colours: Zig, Nix and Make from the
queries their crates ship, GraphQL and HCL (Terraform) from our own, as
those crates ship none.

Grammar queries follow two conventions, so the precedence is set per
grammar: nvim-style (the later pattern wins) or tree-sitter CLI style
(the first one wins, Nix). nvim's `#lua-match?` is evaluated; patterns
with predicates we cannot evaluate no longer match unconditionally,
which coloured every Zig identifier as a constant.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai 135723bca6 feat(tools): Install ElixirLS and its debugger, checking for Elixir first
ElixirLS ships one platform-independent zip of launcher scripts that
build the server with the project's Elixir / OTP on first start. Both
the language server and the debug adapter are installed from it, each
linked to its own launcher (language_server / debug_adapter).

Tools can now declare runtimes they need on PATH; Install stays
disabled with the reason ("Elixir is required") until they are found.

The Elixir debug adapter is renamed elixir-ls-debugger so it no longer
shares the server's tool name.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai 03a660354c feat(tools): Custom language server paths and a list/details Language Servers page
Servers and debug adapters could only be found on PATH or in the IDE's
tools folder; the only way to pick another executable (a version that
matches the project's Elixir/OTP, a local build) was an undocumented
languages/*.toml override. `tools.<command>.path` now names the
executable to launch: language servers (configure_server, restarted on
change), debug sessions and the tool list honour it, the latter
reporting a Custom status with its version or why the path is unusable.

The Language Servers page is laid out like Plugins: a compact list
grouped by availability on the left, the selected tool's command, path,
location, version, install actions and hints on the right.

A debugger named like its language server (ElixirLS's elixir-ls /
elixir-ls-debugger) was folded into the server's row and never listed;
it now gets a row of its own.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai 1572fc36ea feat(editor): Highlight languages without a CodeMirror mode from tree-sitter
Elixir files opened as plain text: highlighting only came from
@codemirror/language-data, which has no Elixir mode. Grammars now carry
their own highlights.scm; `doc_highlights` folds its captures into a small
kind vocabulary (inner nodes and later patterns win, interpolation clears
the string colour), memoised per document version on the incremental
tree. The editor maps kinds onto Lezer tags, so colours follow the active
scheme, and requests them only when no CodeMirror mode exists.

Enabled for Elixir; other grammar-only languages need their query wired.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 11:26:31 +08:00
l0ng-ai 4f74f22624 fix(ui): Size Select popups to the widest option and truncate the PR repo name
Virtualised list rows are absolutely positioned, so the popup only took the
trigger's width and cut short labels like "Merged". The Pull Requests header
now keeps the repository on one line with an ellipsis and a tooltip.
2026-10-24 10:02:13 +08:00
l0ng-ai 1309ce10e4 chore: v0.1.6 2026-10-24 09:21:16 +08:00
l0ng-ai 49be259232 fix(ui): Show the full SDK name in selects and shorten Windows home paths
A long detail (an installation path) was not cut, so it pushed the option label out
(e.g. "Eclipse Adopti…", the Maven name hidden) and scrolled the popup sideways. The
label now keeps its width and the detail is cut with an ellipsis (full path in the
tooltip, detail text translated). Paths under C:/Users/<name> are shown as ~/…
2026-10-24 09:11:58 +08:00
l0ng-ai 6a8016b888 fix(vcs): Keep submodule entries out of Rollback and refresh the log of another repository
- Rollback no longer offers a submodule's own entry: it cannot be reverted from the
  enclosing repository (it did nothing while reporting "Rolled back 1 file"). Rolling
  back only that entry explains how to revert it instead.
- A selected change is rolled back alone; only folders take the changes below them, so
  selecting a submodule's entry no longer pulls in the uncommitted files inside it.
- The Git log loads the branches of the newly selected repository, so it reloads when
  that repository's refs move (a new branch showed up only after a manual refresh).
2026-10-24 09:11:58 +08:00
l0ng-ai b8f422d451 fix(vcs): Route a nested repository's own entry to the enclosing one and harden multi-root
Review fixes for several repositories in one project:

- A path equal to a nested repository's root (a submodule's entry, an untracked
  clone) belongs to the enclosing repository, in the backend and the Commit view.
  It was routed to the nested repository as ".", so Rollback ran `git restore` and
  `git clean` over the whole submodule and Commit staged everything in it.
- Repository-scoped commands take the repository root exactly and fail when it is
  gone instead of running in an enclosing repository; path-based ones resolve the
  file's repository (Project::with_repo_of).
- The rescan on a repository appearing or going watches `.git/HEAD`: the watcher
  never reports a `.git` path itself, so the old check never fired.
- Status skips a repository that cannot be read; refresh falls back to the primary
  repository when the selected one is gone instead of failing every time.
- Commit and Compare-with-Local diffs resolve repository-relative paths against the
  selected repository's root, not the project root.
- Update Project and Fetch go on after a failing repository and report the failures
  together; Update skips repositories with a detached HEAD or no upstream.
- The Push dialog leaves out a repository that cannot be read.
- Shelve and patches fail clearly for changes of a nested repository instead of
  leaving them out silently (they still support the main repository only).
- Fix the repository discovery test on Windows (path separators); Chinese text for
  the new strings.
2026-10-23 23:15:09 +08:00
l0ng-ai c868ec8b68 fix(java): Apply the Maven settings to jdtls and Lombok, find more Maven installs
Review fixes for the Project JDK / Maven settings:

- jdtls gets the user settings.xml as java.configuration.maven.userSettings, so the
  editor resolves dependencies through the same mirrors and servers as sync and builds.
- The configured local repository (else <localRepository> of the chosen settings.xml)
  is where the static POM model looks for parent POMs / BOMs and where the Lombok
  agent is looked for.
- Maven discovery finds mvn.cmd on PATH on Windows and the homes Maven Wrapper 3.3+
  downloads (dists/<name>/<hash> without a nested folder).
- A Project JDK pointing at the JDK's bin directory is accepted.
- Detected run configurations reload when language settings change, so Maven and
  Gradle runs use the new JDK, Maven home and options.
- Chinese text for the new settings.
2026-10-23 23:15:09 +08:00
l0ng-ai 059a5193ff feat(vcs): Support several git repositories in one project (multi-root)
Only the repository containing the project root was known, so nested clones and
submodules (or a folder of side-by-side service repositories) showed no changes and
could not be committed or pushed. The project now has IDEA's VCS roots: the enclosing
repository plus those found below the project (scanned in the background, rescanned when
a .git appears or goes). Status covers all of them; path-based commands go to the file's
repository and repository-scoped ones take the selected repository.

The Commit view groups changes by repository and commits each one with included changes;
the branch widget names the selected repository and switches between them; Update Project
and Fetch run in every repository; Push lists every repository with outgoing commits; a
repository that stops in a merge or rebase is selected so Continue / Abort act on it.

Closes #12
2026-10-23 23:15:09 +08:00
l0ng-ai 0f7008391c feat(java): Add Project JDK and Maven home / settings.xml / local repository settings
The JDK was always picked automatically (JAVA_HOME, PATH, the usual install dirs, by the
module's Java version) and Maven was the project's mvnw or mvn on PATH, with no way to
override either. languages.java.jdk (Languages & Frameworks › Java › Project JDK) now sets
the default jdtls runtime, the JDK of Run/Debug and JAVA_HOME for Maven and Gradle;
languages.java.maven (Build Tools › Maven) sets the Maven home, -s and
-Dmaven.repo.local for sync, builds, tool-window goals and detected run configurations.
JDKs and Maven installations are detected for the pickers.

Closes #13
2026-10-23 23:15:09 +08:00
l0ng-ai c59f93988b feat(vcs): PyCharm-style Commit view and one shared message dialog
- workbench/messages: one promise-based ask/confirm/confirmChecked/showError
  host replaces the per-feature confirm dialogs (app, services, vcs,
  project tree, keymap, run, database, find, LSP choice popup).
- Commit tool window: Commit | Shelf | Stash tabs as the title, IDEA's
  toolbar (Update Project, View Options, Select Opened File), Unversioned
  collapsed, Commit / Commit and Push on one row, empty-message error.
- Commit Options popup: author, sign-off, before-commit checks, Git hooks;
  vcs_commit takes CommitOptions (--author, --no-verify).
- Remove from Recent Projects asks first; refused history rewrites show an
  error dialog.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 22:59:06 +08:00
l0ng-ai 76d33f0306 feat(ui): IDEA-style message dialogs, project widget popup and Chinese UI text
Message dialogs: `Dialog` gets an `icon` (question / info / warning / error)
that renders IDEA's alert layout: no title bar, a 32px icon, bold title,
text, checkbox under it. Every confirmation helper (prompt, VCS, services,
project tree, keymap, LSP choices, run, database, Replace All) uses it. Open
Project matches IDEA: "This Window" is the default and has focus. The Code
Analysis and TODO commit checks default to Review.

Project widget: the title bar project button opens a popup like IDEA's
ProjectWidget, with Open… / Clone Repository…, the projects open in other
windows (new `window_open_projects` command) and recent projects, filtered by
typing.

Chinese UI: UI text stays written in English and is translated through a
source-text catalog (`locales/text/zh.json`, about 2300 strings). The UI
primitives (buttons, checkboxes, selects, tabs, dialogs, menus, tooltips,
toasts, settings labels and hints) translate the strings they are given.
Action titles and categories are localised in the registry, and static JSX
text uses `<T>`, so text follows a locale switch without a reload. The
Settings window now syncs the locale too. Settings search matches both
languages.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 22:18:50 +08:00
l0ng-ai cd55bc8f7f chore: v0.1.5 2026-10-23 21:38:02 +08:00
l0ng-ai deec86fab9 refactor(perf): Remove the Memory Usage settings page
It was a live metrics view, not a setting, and duplicated the memory
indicator's popup, its status bar toggle and Clear Caches.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 21:35:02 +08:00
l0ng-ai 29e89f2525 fix(app): Give the Settings window a plain loader and make the splash bar progress
The Settings window loads the same page as project windows, so it showed the
launch splash with the logo. It now shows only the bar, after 400 ms.

The bar's sliding animation was switched off under reduced motion, leaving a
static 40% fill. It is now a fake progress that eases towards ~90% and fills
to 100% before the splash fades out.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 21:31:57 +08:00
l0ng-ai b1bb4a69cd fix(app): Keep the dark theme's background under a fast window resize
splash.css painted html light and only switched body to dark, so the page
canvas showed the light colour wherever a live resize outran relayout.
Leave html unpainted so the canvas takes body's themed background.

Also set the webview's background (not just the native window's) on a
theme change; it otherwise kept the colour the window was created with.
2026-10-23 21:29:45 +08:00
l0ng-ai ee99b3641f fix(ui): Hide the focus outline around dropdown popups
The global :focus-visible rule loads after the module CSS and has the same
specificity, so it overrode `outline: none` on the focused listbox wrapper
and drew a square blue frame inside the Select popup.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 21:23:06 +08:00
l0ng-ai 19aee5f262 fix(app): Never show the webview's native context menu (#11)
Right-clicks the app doesn't handle itself, such as on code-lens or inlay
widgets inside the editor or in text fields, fell through to WebKit's own
menu, whose Reload item reloads the whole app. Block it everywhere; the
app's own menus already call preventDefault before this guard runs.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 20:02:58 +08:00
496 змінених файлів з 24157 додано та 4275 видалено

No files matched your search

Створено
+43 -26
Переглянути файл
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-analysis"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -3976,7 +3976,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -3991,7 +3991,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"dunce",
"serde",
@@ -4003,7 +4003,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ide-core",
"ide-run",
@@ -4017,7 +4017,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4034,7 +4034,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -4054,7 +4054,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ide-core",
"libc",
@@ -4067,7 +4067,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4081,7 +4081,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ide-core",
"parking_lot",
@@ -4099,7 +4099,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"blake3",
"criterion",
@@ -4121,7 +4121,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"futures",
"ide-core",
@@ -4136,7 +4136,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"blake3",
"criterion",
@@ -4188,7 +4188,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"futures",
"globset",
@@ -4211,7 +4211,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ide-core",
"ide-language",
@@ -4229,7 +4229,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ide-core",
"ide-run",
@@ -4242,7 +4242,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4260,7 +4260,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"dunce",
"ide-core",
@@ -4277,7 +4277,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"criterion",
"globset",
@@ -4296,7 +4296,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ide-core",
"ide-language",
@@ -4311,7 +4311,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"ide-core",
"libc",
@@ -4324,7 +4324,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"criterion",
"ide-core",
@@ -4336,7 +4336,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"flate2",
"hex",
@@ -4356,7 +4356,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"dunce",
"gix",
@@ -4373,7 +4373,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"chardetng",
"dunce",
@@ -4391,9 +4391,25 @@ dependencies = [
"trash",
]
[[package]]
name = "ide-web"
version = "0.1.12"
dependencies = [
"ide-core",
"open",
"parking_lot",
"percent-encoding",
"serde",
"specta",
"tempfile",
"tokio",
"tracing",
"uuid",
]
[[package]]
name = "ide-workspace"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"blake3",
"dunce",
@@ -5817,7 +5833,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.4"
version = "0.1.12"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -5844,6 +5860,7 @@ dependencies = [
"ide-tools",
"ide-vcs",
"ide-vfs",
"ide-web",
"ide-workspace",
"parking_lot",
"serde",
+2 -1
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.4"
version = "0.1.12"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -32,6 +32,7 @@ ide-coverage = { path = "crates/ide-coverage" }
ide-profiler = { path = "crates/ide-profiler" }
ide-http = { path = "crates/ide-http" }
ide-db = { path = "crates/ide-db" }
ide-web = { path = "crates/ide-web" }
# serialization & IPC typing
serde = { version = "1", features = ["derive"] }
+9 -1
Переглянути файл
@@ -9,13 +9,21 @@
The IDE you know, rebuilt in Rust.
</p>
<p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Download</b></a>
&nbsp;·&nbsp;
<a href="#benchmark">Benchmark</a>
&nbsp;·&nbsp;
<a href="#build">Build</a>
</p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
OpenIDEA brings the IntelliJ IDEA way of working — its keymap, its tool windows,
its search-everything habits — to a native app with a Rust core.
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
for 60+ languages.
for 60+ languages. Builds for macOS, Windows and Linux.
## Benchmark
+1 -1
Переглянути файл
@@ -19,7 +19,7 @@ fn main() {
eprintln!("synced in {:?}: {r:?}", started.elapsed());
}
let started = std::time::Instant::now();
let model = ide_build::load(&root, &cache);
let model = ide_build::load(&root, &cache, None);
println!("{}", serde_json::to_string_pretty(&model).unwrap());
eprintln!("loaded in {:?}", started.elapsed());
}
+3 -2
Переглянути файл
@@ -225,6 +225,7 @@ fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<
}
let step = |p: &maven::MavenProject, extra: &[String]| {
let mut s = BuildStep::new(&p.command, &["-B", "-Dstyle.color=never"], &subdir(root, &p.dir), Format::Maven);
s.args.extend(p.options.iter().cloned());
s.args.extend(extra.iter().cloned());
s.args.extend(goals.iter().map(|g| (*g).to_owned()));
s.env = p.env.clone();
@@ -671,7 +672,7 @@ mod tests {
);
write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
write(&root, "core/src/main/java/A.java", "class A {}");
let model = crate::load(&root, &tmp.path().join("cache"));
let model = crate::load(&root, &tmp.path().join("cache"), None);
let p = plan(&root, &model, BuildKind::Build, None).unwrap();
assert_eq!(p.system, BuildSystem::Maven);
assert_eq!(p.title, "demo");
@@ -685,7 +686,7 @@ mod tests {
let g = tmp.path().join("g");
write(&g, "settings.gradle", "include 'app'");
write(&g, "app/build.gradle", "apply plugin: 'java'");
let model = crate::load(&g, &tmp.path().join("cache2"));
let model = crate::load(&g, &tmp.path().join("cache2"), None);
let p = plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java"))).unwrap();
assert_eq!(p.system, BuildSystem::Gradle);
assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
+6 -5
Переглянути файл
@@ -18,7 +18,7 @@ pub use sync::{SyncOptions, SyncProgress, sync_gradle, sync_maven};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::Path;
use std::path::{Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -36,9 +36,10 @@ pub struct BuildModel {
}
/// Static model of the builds under `root`, merged with the sync results cached in `cache_dir`.
pub fn load(root: &Path, cache_dir: &Path) -> BuildModel {
/// Parent POMs are looked up in `maven_repo` (the configured local repository), else the default one.
pub fn load(root: &Path, cache_dir: &Path, maven_repo: Option<PathBuf>) -> BuildModel {
let maven = maven::is_maven_project(root).then(|| {
let mut m = maven::load(root);
let mut m = maven::load_with_repo(root, maven_repo.or_else(maven::default_local_repo));
sync::apply_maven_cache(root, cache_dir, &mut m);
m
});
@@ -68,10 +69,10 @@ mod tests {
let cache = tmp.path().join("cache");
let root = tmp.path().join("p");
std::fs::create_dir_all(root.join("svc")).unwrap();
assert_eq!(load(&root, &cache), BuildModel::default());
assert_eq!(load(&root, &cache, None), BuildModel::default());
std::fs::write(root.join("svc/pom.xml"), "<project><artifactId>svc</artifactId></project>").unwrap();
std::fs::write(root.join("build.gradle"), "").unwrap();
let m = load(&root, &cache);
let m = load(&root, &cache, None);
assert_eq!(m.maven.unwrap().projects[0].pom, "svc/pom.xml");
assert_eq!(m.gradle.unwrap().projects[0].path, ":");
assert!(affects_build(Path::new("a/pom.xml")) && affects_build(Path::new("settings.gradle.kts")));
+4 -1
Переглянути файл
@@ -92,6 +92,8 @@ pub struct MavenProject {
pub java_version: Option<u32>,
/// Maven launcher: the nearest `mvnw` up to the project root (absolute), else `mvn`.
pub command: String,
/// Options before the goals (`-s`, `-Dmaven.repo.local=`); filled in by the shell from settings.
pub options: Vec<String>,
/// Environment for runs (`JAVA_HOME` of the matching JDK); filled in by the shell.
pub env: BTreeMap<String, String>,
}
@@ -410,7 +412,7 @@ struct Resolver {
}
/// `~/.m2/repository`, or `<localRepository>` from `~/.m2/settings.xml`.
fn default_local_repo() -> Option<PathBuf> {
pub(crate) fn default_local_repo() -> Option<PathBuf> {
let m2 = dirs::home_dir()?.join(".m2");
if let Some(settings) = std::fs::read_to_string(m2.join("settings.xml")).ok().and_then(|t| xml::parse(&t))
&& let Some(repo) = settings.text_of("localRepository")
@@ -924,6 +926,7 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option<PathBuf>) -> MavenM
profiles: pom.profiles.iter().map(|p| p.id.clone()).collect(),
java_version: jv,
command: wrapper(root, &dir),
options: Vec::new(),
env: BTreeMap::new(),
});
for m in modules.into_iter().rev() {
+1 -6
Переглянути файл
@@ -52,12 +52,7 @@ pub(crate) fn run(
use std::os::unix::process::CommandExt;
command.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
ide_core::process::no_window(&mut command);
let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {program}: {e}")))?;
let (tx, rx) = mpsc::channel::<(Stream, String)>();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
+7 -1
Переглянути файл
@@ -29,6 +29,10 @@ pub struct SyncOptions {
pub profiles: Vec<String>,
/// Extra environment (`JAVA_HOME`).
pub env: BTreeMap<String, String>,
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
pub maven_command: Option<String>,
/// Maven options before the goals (`-s`, `-Dmaven.repo.local=`).
pub maven_options: Vec<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -184,6 +188,7 @@ pub fn sync_maven(
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
let _ = std::fs::remove_file(&effective);
let mut args: Vec<String> = vec!["-B".into(), "-fae".into(), "-Dstyle.color=never".into()];
args.extend(options.maven_options.iter().cloned());
if options.offline {
args.push("-o".into());
}
@@ -194,7 +199,8 @@ pub fn sync_maven(
args.push(format!("-Doutput={}", effective.to_string_lossy()));
args.push("dependency:tree".into());
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let out = run(&top.command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
let command = options.maven_command.as_deref().unwrap_or(&top.command);
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
if let Some((name, i, total)) = maven_building(line) {
let fraction = (i.saturating_sub(1) as f32 / total.max(1) as f32).min(1.0);
progress(SyncProgress { message: format!("Building model of {name}"), fraction: Some(fraction) });
+15 -9
Переглянути файл
@@ -102,7 +102,7 @@ pub struct BreadcrumbsSettings {
impl Default for BreadcrumbsSettings {
fn default() -> Self {
Self { show: false, placement: "bottom".into(), disabled_languages: Vec::new() }
Self { show: true, placement: "bottom".into(), disabled_languages: Vec::new() }
}
}
@@ -130,10 +130,10 @@ impl Default for CompletionSettings {
case_sensitivity: "first".into(),
auto_popup: true,
insert_on_special_keys: false,
show_documentation: true,
show_documentation: false,
documentation_delay: 500,
parameter_info: true,
parameter_info_delay: 300,
parameter_info_delay: 1000,
}
}
}
@@ -192,9 +192,9 @@ impl Default for EditorTabsSettings {
show_close_button: true,
preview_tab: true,
open_at_end: false,
tab_limit: 10,
closing_policy: "unchanged".into(),
activate_on_close: "mru".into(),
tab_limit: 30,
closing_policy: "lru".into(),
activate_on_close: "left".into(),
}
}
}
@@ -214,7 +214,7 @@ pub struct SmartKeysSettings {
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
pub reformat_on_paste: String,
pub smart_indent: bool,
/// Backspace › Unindent: `nearest` indent position | `none`.
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
pub backspace_unindent: String,
}
@@ -226,10 +226,10 @@ impl Default for SmartKeysSettings {
pair_brackets: true,
pair_quotes: true,
surround_selection: true,
tab_out_of_pair: false,
tab_out_of_pair: true,
reformat_on_paste: "indentBlock".into(),
smart_indent: true,
backspace_unindent: "nearest".into(),
backspace_unindent: "autoindent".into(),
}
}
}
@@ -314,6 +314,12 @@ pub struct LanguageCodeStyle {
pub indent: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hard_wrap_at: Option<u32>,
/// Comment Code › Line comment at first column.
#[serde(skip_serializing_if = "Option::is_none")]
pub line_comment_at_first_column: Option<bool>,
/// Comment Code › Add a space at line comment start.
#[serde(skip_serializing_if = "Option::is_none")]
pub line_comment_add_space: Option<bool>,
}
/// Editor › Code Style (General tab + per-language overrides).
+3
Переглянути файл
@@ -106,6 +106,9 @@ pub enum ServerStatus {
Crashed,
Stopped,
Missing,
/// Not started: its configuration can't launch it (e.g. no JDK new enough);
/// the message says what to change, and a settings change retries.
Misconfigured,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+1
Переглянути файл
@@ -10,6 +10,7 @@ pub mod event;
pub mod ids;
pub mod ignored;
pub mod ipc_path;
pub mod process;
pub mod project_dir;
pub mod settings;
pub mod text;
+20
Переглянути файл
@@ -0,0 +1,20 @@
//! Child-process helpers shared by every crate that spawns tools.
use std::process::Command;
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
/// with other flags. Prefer [`no_window`] otherwise.
pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
/// Keeps a console child (java, node, curl, a language server, ...) from
/// opening its own console window on Windows. Release builds use the GUI
/// subsystem, so without this every spawn flashes a `cmd` window. A no-op
/// elsewhere. For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
pub fn no_window(cmd: &mut Command) -> &mut Command {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(CREATE_NO_WINDOW);
}
cmd
}
+39
Переглянути файл
@@ -37,6 +37,23 @@ pub struct Settings {
pub terminal: TerminalSettings,
pub actions_on_save: ActionsOnSaveSettings,
pub external_tools: Vec<ExternalTool>,
/// Language servers / debug adapters at a user-chosen location, by the
/// command the language definition launches (`elixir-ls`, `codelldb`).
pub tools: BTreeMap<String, ToolSettings>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ToolSettings {
/// Executable to launch instead of the managed / `PATH` one; empty = auto-detect.
pub path: String,
}
impl Settings {
/// The configured executable for `command`, if any (`~/` not yet expanded).
pub fn tool_path(&self, command: &str) -> Option<&str> {
self.tools.get(command).map(|t| t.path.trim()).filter(|p| !p.is_empty())
}
}
impl Default for Settings {
@@ -59,6 +76,7 @@ impl Default for Settings {
terminal: TerminalSettings::default(),
actions_on_save: ActionsOnSaveSettings::default(),
external_tools: Vec::new(),
tools: BTreeMap::new(),
}
}
}
@@ -401,9 +419,30 @@ pub struct GoSettings {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct JavaSettings {
/// Project JDK home; empty = per module, the installed JDK matching the
/// Java version it targets.
pub jdk: String,
/// JDK home the Java language server (jdtls) runs on, apart from the project
/// JDK (IDEA's "JDK for importer"); empty = the project JDK when new enough,
/// else the first installed one that is.
pub jdtls_jdk: String,
/// Extra JVM options for the Java language server (jdtls), space-separated
/// (VS Code's `java.jdt.ls.vmargs`).
pub jdtls_vm_args: String,
/// Build Tools › Maven.
pub maven: MavenSettings,
}
/// Build Tools › Maven.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct MavenSettings {
/// Maven home (or its `mvn` executable); empty = the project's `mvnw`, else `mvn` on `PATH`.
pub home: String,
/// User `settings.xml` (`-s`); empty = `~/.m2/settings.xml`.
pub user_settings: String,
/// Local repository (`-Dmaven.repo.local`); empty = from `settings.xml`.
pub local_repository: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
+11 -1
Переглянути файл
@@ -24,7 +24,8 @@ pub struct VcsSettings {
impl Default for VcsSettings {
fn default() -> Self {
Self {
show_dirty_directories: true,
// IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default.
show_dirty_directories: false,
limit_history: true,
history_limit: 1000,
git: GitSettings::default(),
@@ -241,6 +242,8 @@ pub struct TerminalSettings {
pub shell_integration: bool,
pub highlight_hyperlinks: bool,
pub option_as_meta: bool,
/// Escape moves focus to the editor instead of reaching the shell.
pub escape_to_editor: bool,
/// `block` | `underline` | `bar`.
pub cursor_shape: String,
pub cursor_blink: bool,
@@ -249,6 +252,10 @@ pub struct TerminalSettings {
pub font_size: f32,
/// Multiple of the cell height.
pub line_height: f32,
/// Font tried for glyphs the main font lacks; empty = none.
pub fallback_font_family: String,
/// Multiple of the cell width.
pub column_width: f32,
}
impl Default for TerminalSettings {
@@ -267,12 +274,15 @@ impl Default for TerminalSettings {
shell_integration: true,
highlight_hyperlinks: true,
option_as_meta: false,
escape_to_editor: false,
cursor_shape: "block".into(),
cursor_blink: true,
use_editor_font: true,
font_family: "JetBrains Mono".into(),
font_size: 13.0,
line_height: 1.0,
fallback_font_family: String::new(),
column_width: 1.0,
}
}
}
+1 -1
Переглянути файл
@@ -204,7 +204,7 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
let (program, args) =
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
let out = Command::new(program)
let out = ide_core::process::no_window(&mut Command::new(program))
.args(args)
.current_dir(cwd)
.envs(env)
+1
Переглянути файл
@@ -287,6 +287,7 @@ mod tests {
detected: true,
is_test: true,
debug_adapter: None,
allow_parallel: false,
}
}
+4 -1
Переглянути файл
@@ -233,7 +233,9 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
return Ok(()); // Reported as a missing adapter when it is started.
};
let probe = Command::new(&python)
let mut probe = Command::new(&python);
ide_core::process::no_window(probe.as_std_mut());
let probe = probe
.args(["-c", "import debugpy.adapter"])
.current_dir(&spec.cwd)
.stdin(Stdio::null())
@@ -335,6 +337,7 @@ impl AdapterLauncher for ProcessLauncher {
None => spec.args.clone(),
};
let mut cmd = Command::new(&binary);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(&args)
.envs(spec.env.iter().map(|(k, v)| (k, v)))
.current_dir(&spec.cwd)
+1
Переглянути файл
@@ -55,6 +55,7 @@ pub async fn build(
) -> IdeResult<PathBuf> {
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
let mut cmd = tokio::process::Command::new(cargo);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(args)
.arg("--message-format=json-render-diagnostics")
.current_dir(cwd)
+14
Переглянути файл
@@ -522,6 +522,17 @@ impl DebugManager {
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
/// Events of the session (including cargo build output) go to `owner` only.
pub async fn start(&self, config: LaunchConfig, owner: SessionOwner) -> IdeResult<DebugSessionId> {
self.start_with(config, owner, |_| None).await
}
/// [`start`](Self::start) with the adapter executable chosen by `custom_command`
/// (the configured command → a user-chosen executable, from settings).
pub async fn start_with(
&self,
config: LaunchConfig,
owner: SessionOwner,
custom_command: impl FnOnce(&str) -> Option<String>,
) -> IdeResult<DebugSessionId> {
let mut arguments = launch_arguments(&config)?;
let cwd = config
.cwd
@@ -531,6 +542,9 @@ impl DebugManager {
let dbg = adapter::find_config(&self.languages, &config.adapter)
.ok_or_else(|| IdeError::unavailable(format!("unknown debug adapter `{}`", config.adapter)))?;
let mut spec = adapter::resolve(&dbg, cwd.clone());
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy).
if config.adapter == "debugpy" {
let python = match arguments.get("python") {
+1
Переглянути файл
@@ -390,6 +390,7 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
return Err("runInTerminal without args".into());
};
let mut cmd = tokio::process::Command::new(program);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(rest).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
if let Some(cwd) = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()) {
cmd.current_dir(cwd);
+1 -5
Переглянути файл
@@ -25,11 +25,7 @@ fn prepare(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
ide_core::process::no_window(cmd);
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
+1 -5
Переглянути файл
@@ -25,11 +25,7 @@ fn prepare(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
ide_core::process::no_window(cmd);
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
+25
Переглянути файл
@@ -121,6 +121,11 @@ impl ProjectIndex {
matching::find_symbols(&d, &matching::Recents { paths: &recent }, query, filter, limit)
}
/// Symbols named exactly `name` (of `kind`, if given): `.card` selectors for `class="card"`.
pub fn symbols_named(&self, name: &str, kind: Option<SymbolKind>, limit: usize) -> Vec<SymbolMatch> {
matching::symbols_named(&self.shared.data.read(), name, kind, limit)
}
/// Incrementally re-indexes changed paths (called from the vfs watcher).
/// Cheap: the work is queued for the indexing thread.
pub fn update(&self, changed: &[PathBuf], removed: &[PathBuf]) {
@@ -154,6 +159,26 @@ impl ProjectIndex {
self.shared.enqueue(Job::SaveRecent);
}
/// Drops a file from Recent Files (Delete in the ⌘E popup).
pub fn remove_recent(&self, path: &Path) {
let path = match path.to_str() {
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
_ => match self.normalize(path) {
Some(p) => p,
None => return,
},
};
{
let mut r = self.shared.recent.lock();
let before = r.len();
r.retain(|p| p != &path);
if r.len() == before {
return;
}
}
self.shared.enqueue(Job::SaveRecent);
}
/// Recently opened files, most recent first.
pub fn recent_files(&self) -> Vec<PathBuf> {
self.shared.recent.lock().clone()
+28
Переглянути файл
@@ -7,6 +7,7 @@
use crate::data::{FileEntry, IndexData, char_mask};
use crate::{FileMatch, SymbolFilter, SymbolMatch};
use ide_core::SymbolKind;
use nucleo_matcher::{Config, Matcher, Utf32Str, Utf32String};
use rayon::prelude::*;
use std::cell::RefCell;
@@ -419,6 +420,33 @@ pub(crate) fn find_symbols(
.collect()
}
/// Symbols named exactly `name` (and of `kind`, when given), by path then position.
pub(crate) fn symbols_named(data: &IndexData, name: &str, kind: Option<SymbolKind>, limit: usize) -> Vec<SymbolMatch> {
let mask = char_mask(name);
let mut out: Vec<SymbolMatch> = data
.files
.iter()
.flatten()
.flat_map(|e| {
e.symbols.iter().filter(|s| s.mask == mask && &*s.name == name && kind.is_none_or(|k| s.kind == k)).map(
move |s| SymbolMatch {
name: s.name.to_string(),
kind: s.kind,
container: s.container.as_deref().map(str::to_owned),
path: e.path.clone().into(),
rel_path: e.rel.to_string(),
range: s.range,
score: 0,
indices: Vec::new(),
},
)
})
.collect();
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path).then_with(|| a.range.cmp(&b.range)));
out.truncate(limit);
out
}
#[cfg(test)]
mod tests {
use super::*;
+22
Переглянути файл
@@ -192,7 +192,11 @@ fn persistence_skips_unchanged_files_on_reopen() {
assert_eq!(idx.status().files, 8);
assert_eq!(symbols(&idx, "OrderController", SymbolFilter::Types)[0], "OrderController");
assert_eq!(idx.recent_files(), vec![fx.root.join("web/app.py")]);
idx.remove_recent(&fx.root.join("web/app.py"));
assert!(idx.recent_files().is_empty());
assert!(idx.wait_idle(WAIT));
}
assert!(fx.open().recent_files().is_empty(), "removal is persisted");
std::thread::sleep(Duration::from_millis(20));
fx.write("src/main.rs", "fn main() {}\nfn renamed_fn() {}\n");
std::fs::remove_file(fx.root.join("docs/maintenance.md")).unwrap();
@@ -381,3 +385,21 @@ fn synthetic_index_answers_queries() {
assert!(!s.find_symbols("PaySe", SymbolFilter::All, 20).is_empty());
assert!(s.find_symbols("PaySe", SymbolFilter::Types, 20).iter().all(|m| m.kind == SymbolKind::Class));
}
#[test]
fn css_selectors_are_found_by_exact_name() {
let f = Fixture::new(&[
("web/a.css", ".card { --gap: 1px }\n.cardigan {}\n"),
("web/b.scss", ".list { .card { } }\n"),
("web/index.html", "<style>.card{}</style>\n<div class=\"card\"></div>\n"),
]);
let idx = f.open();
let found: Vec<(String, u32)> = idx
.symbols_named(".card", Some(SymbolKind::Class), 10)
.into_iter()
.map(|m| (m.rel_path, m.range.start.line))
.collect();
assert_eq!(found, vec![("web/a.css".into(), 0), ("web/b.scss".into(), 0), ("web/index.html".into(), 0)]);
assert_eq!(idx.symbols_named("--gap", None, 10).len(), 1);
assert!(idx.symbols_named(".card", Some(SymbolKind::Field), 10).is_empty());
}
+1
Переглянути файл
@@ -241,6 +241,7 @@ impl Peer {
) -> std::io::Result<Self> {
use std::process::Stdio;
let mut cmd = tokio::process::Command::new(command);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(args)
.current_dir(cwd)
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
+49
Переглянути файл
@@ -0,0 +1,49 @@
; GraphQL highlighting (the grammar crate ships no query). Later patterns win.
(comment) @comment
(description (string_value) @comment.doc)
(string_value) @string
(int_value) @number
(float_value) @number
[(boolean_value) (null_value)] @keyword
(enum_value (name) @constant)
(variable) @variable
(argument (name) @variable.parameter)
(input_value_definition (name) @variable.parameter)
(object_field (name) @property)
(field (name) @property)
(alias (name) @property)
(field_definition (name) @property)
(enum_value_definition (enum_value (name) @constant))
(named_type (name) @type)
(object_type_definition (name) @type)
(interface_type_definition (name) @type)
(union_type_definition (name) @type)
(enum_type_definition (name) @type)
(input_object_type_definition (name) @type)
(scalar_type_definition (name) @type)
(object_type_extension (name) @type)
(interface_type_extension (name) @type)
(union_type_extension (name) @type)
(enum_type_extension (name) @type)
(input_object_type_extension (name) @type)
(scalar_type_extension (name) @type)
(operation_definition (name) @function)
(fragment_name (name) @function)
(directive_definition (name) @attribute)
(directive (name) @attribute)
"@" @attribute
(directive_location) @constant
(operation_type) @keyword
[
"query" "mutation" "subscription" "fragment" "on" "type" "interface" "union"
"enum" "input" "scalar" "schema" "extend" "implements" "directive" "repeatable"
] @keyword
["(" ")" "[" "]" "{" "}"] @punctuation.bracket
[":" "=" "|" "&" "!" "..."] @punctuation.delimiter
+29
Переглянути файл
@@ -0,0 +1,29 @@
; HCL / Terraform highlighting (the grammar crate ships no query). Later patterns win.
(comment) @comment
(string_lit) @string
(quoted_template) @string
(heredoc_template) @string
[(heredoc_start) (heredoc_identifier)] @string.special
(template_literal) @string
(numeric_lit) @number
[(bool_lit) (null_lit)] @keyword
(identifier) @variable
(attribute (identifier) @property)
(object_elem key: (expression (variable_expr (identifier) @property)))
(get_attr (identifier) @property)
(function_call (identifier) @function)
; `resource "aws_instance" "web" {`
(block (identifier) @keyword)
(block (string_lit (template_literal) @type))
(template_interpolation) @embedded
[(template_interpolation_start) (template_interpolation_end)] @punctuation.special
[(template_directive_start) (template_directive_end) (strip_marker)] @punctuation.special
["for" "in" "if" "else" "endfor" "endif"] @keyword
(operation) @operator
["!" "!=" "%" "&&" "*" "+" "-" "/" "<" "<=" "==" ">" ">=" "||" "?" "=>"] @operator
["=" ":" "," "."] @punctuation.delimiter
["(" ")" "[" "]" "{" "}" "[*]" ".*"] @punctuation.bracket
+4 -1
Переглянути файл
@@ -12,7 +12,10 @@ use std::collections::BTreeMap;
mod registry;
mod syntax;
pub use registry::LanguageRegistry;
pub use syntax::{MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, TreeError};
pub use syntax::{
CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache,
SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError, WebReference, WebReferenceKind,
};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
#[derive(Clone, Debug, Serialize, Deserialize)]
+20 -1
Переглянути файл
@@ -5,7 +5,10 @@
//! Structure / folding / Extend Selection on a large file cost an incremental
//! parse instead of a full one.
use super::{Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, TreeError, folding, outline, parse_cancellable, selection};
use super::{
Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxHighlights, TreeError, folding, highlight, outline,
parse_cancellable, selection,
};
use crate::FoldRange;
use ide_core::{DocId, LanguageId, OutlineItem, Range};
use ide_text::ByteEdit;
@@ -59,6 +62,7 @@ struct Memo {
key: Option<(u32, LanguageId)>,
outline: Option<Arc<Vec<OutlineItem>>>,
folding: Option<Arc<Vec<FoldRange>>>,
highlights: Option<Arc<Vec<u32>>>,
}
impl Memo {
@@ -211,6 +215,21 @@ impl SyntaxCache {
)
}
/// Highlighting from the grammar's own query; empty without one.
pub fn highlights(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> SyntaxHighlights {
SyntaxHighlights::new(self.memoized(
doc,
lang,
version,
|m| &mut m.highlights,
|| {
self.with_tree(doc, lang, version, text, |g, tree, text| {
Some(highlight::highlights(g.highlight_query()?, tree, text))
})
},
))
}
/// `compute()` once per document version; `None` (no grammar / query) is not memoized.
fn memoized<T: Clone>(
&self,
+53
Переглянути файл
@@ -9,6 +9,8 @@ pub(crate) struct Spec {
pub language: LanguageFn,
/// `queries/<name>/outline.scm`; see `queries/README.md` for the capture vocabulary.
pub outline: &'static str,
/// The grammar's `highlights.scm`, for languages without a CodeMirror mode.
pub highlights: Option<Highlights>,
/// Node kinds folded when they span several lines (in addition to every
/// bracket-delimited node, which is folded generically).
pub fold_nodes: &'static [&'static str],
@@ -20,6 +22,21 @@ pub(crate) struct Spec {
pub constructors: &'static [&'static str],
}
/// A highlights query and how its patterns rank against each other.
pub(crate) struct Highlights {
pub query: &'static str,
/// For the same node, the first matching pattern wins (tree-sitter CLI /
/// GitHub queries) instead of the last one (nvim / Zed queries).
pub first_wins: bool,
}
/// Our own `queries/<name>/highlights.scm`, for grammars that ship none.
macro_rules! highlights {
($name:literal) => {
include_str!(concat!("../../queries/", $name, "/highlights.scm"))
};
}
macro_rules! outline {
($name:literal) => {
include_str!(concat!("../../queries/", $name, "/outline.scm"))
@@ -33,6 +50,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "rust",
language: tree_sitter_rust::LANGUAGE,
outline: outline!("rust"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["use_declaration", "extern_crate_declaration"],
@@ -42,6 +60,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "typescript",
language: tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
outline: outline!("typescript"),
highlights: None,
fold_nodes: &["template_string"],
fold_bodies: NONE,
imports: &["import_statement"],
@@ -51,6 +70,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "tsx",
language: tree_sitter_typescript::LANGUAGE_TSX,
outline: outline!("typescript"),
highlights: None,
fold_nodes: &["template_string", "jsx_element"],
fold_bodies: NONE,
imports: &["import_statement"],
@@ -60,6 +80,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "javascript",
language: tree_sitter_javascript::LANGUAGE,
outline: outline!("javascript"),
highlights: None,
fold_nodes: &["template_string", "jsx_element"],
fold_bodies: NONE,
imports: &["import_statement"],
@@ -69,6 +90,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "python",
language: tree_sitter_python::LANGUAGE,
outline: outline!("python"),
highlights: None,
fold_nodes: &["string"],
fold_bodies: &["block"],
imports: &["import_statement", "import_from_statement", "future_import_statement"],
@@ -78,6 +100,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "go",
language: tree_sitter_go::LANGUAGE,
outline: outline!("go"),
highlights: None,
fold_nodes: &["raw_string_literal"],
fold_bodies: NONE,
imports: &["import_declaration"],
@@ -87,6 +110,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "java",
language: tree_sitter_java::LANGUAGE,
outline: outline!("java"),
highlights: None,
fold_nodes: &["text_block"],
fold_bodies: NONE,
imports: &["import_declaration"],
@@ -96,6 +120,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "kotlin",
language: tree_sitter_kotlin_ng::LANGUAGE,
outline: outline!("kotlin"),
highlights: None,
fold_nodes: &["string_literal"],
fold_bodies: NONE,
imports: &["import"],
@@ -105,6 +130,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "scala",
language: tree_sitter_scala::LANGUAGE,
outline: outline!("scala"),
highlights: None,
fold_nodes: &["string"],
fold_bodies: &["indented_block", "template_body"],
imports: &["import_declaration"],
@@ -114,6 +140,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "c",
language: tree_sitter_c::LANGUAGE,
outline: outline!("c"),
highlights: None,
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def"],
fold_bodies: NONE,
imports: &["preproc_include"],
@@ -123,6 +150,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "cpp",
language: tree_sitter_cpp::LANGUAGE,
outline: outline!("cpp"),
highlights: None,
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def", "raw_string_literal"],
fold_bodies: NONE,
imports: &["preproc_include", "using_declaration"],
@@ -132,6 +160,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "csharp",
language: tree_sitter_c_sharp::LANGUAGE,
outline: outline!("csharp"),
highlights: None,
fold_nodes: &["preproc_region", "raw_string_literal", "verbatim_string_literal"],
fold_bodies: NONE,
imports: &["using_directive"],
@@ -141,6 +170,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "swift",
language: tree_sitter_swift::LANGUAGE,
outline: outline!("swift"),
highlights: None,
// Control-flow statements hold `{ statements }` without a block node of their own.
fold_nodes: &[
"multi_line_string_literal",
@@ -160,6 +190,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "ruby",
language: tree_sitter_ruby::LANGUAGE,
outline: outline!("ruby"),
highlights: None,
fold_nodes: &[
"method",
"singleton_method",
@@ -185,6 +216,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "php",
language: tree_sitter_php::LANGUAGE_PHP,
outline: outline!("php"),
highlights: None,
fold_nodes: &["heredoc", "nowdoc"],
fold_bodies: NONE,
imports: &["namespace_use_declaration"],
@@ -194,6 +226,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "lua",
language: tree_sitter_lua::LANGUAGE,
outline: outline!("lua"),
highlights: None,
fold_nodes: &[
"function_declaration",
"function_definition",
@@ -212,6 +245,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "dart",
language: tree_sitter_dart::LANGUAGE,
outline: outline!("dart"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import_or_export", "library_name", "part_directive", "part_of_directive"],
@@ -221,6 +255,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "zig",
language: tree_sitter_zig::LANGUAGE,
outline: outline!("zig"),
highlights: Some(Highlights { query: tree_sitter_zig::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
@@ -230,6 +265,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "elixir",
language: tree_sitter_elixir::LANGUAGE,
outline: outline!("elixir"),
highlights: Some(Highlights { query: tree_sitter_elixir::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: &["do_block", "anonymous_function", "string", "sigil"],
fold_bodies: NONE,
imports: NONE,
@@ -239,6 +275,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "haskell",
language: tree_sitter_haskell::LANGUAGE,
outline: outline!("haskell"),
highlights: None,
// `bind`: equations without arguments (`main = do …`).
fold_nodes: &["function", "bind", "data_type", "newtype", "class", "instance", "signature"],
fold_bodies: NONE,
@@ -249,6 +286,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "ocaml",
language: tree_sitter_ocaml::LANGUAGE_OCAML,
outline: outline!("ocaml"),
highlights: None,
fold_nodes: &[
"value_definition",
"type_definition",
@@ -266,6 +304,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "ocaml_interface",
language: tree_sitter_ocaml::LANGUAGE_OCAML_INTERFACE,
outline: outline!("ocaml_interface"),
highlights: None,
fold_nodes: &["module_definition", "module_type_definition", "signature", "type_definition"],
fold_bodies: NONE,
imports: &["open_module"],
@@ -275,6 +314,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "bash",
language: tree_sitter_bash::LANGUAGE,
outline: outline!("bash"),
highlights: None,
fold_nodes: &["do_group", "if_statement", "case_statement", "heredoc_body"],
fold_bodies: NONE,
imports: NONE,
@@ -284,6 +324,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "html",
language: tree_sitter_html::LANGUAGE,
outline: outline!("html"),
highlights: None,
fold_nodes: &["element", "script_element", "style_element"],
fold_bodies: NONE,
imports: NONE,
@@ -293,6 +334,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "xml",
language: tree_sitter_xml::LANGUAGE_XML,
outline: outline!("xml"),
highlights: None,
fold_nodes: &["element", "CDSect"],
fold_bodies: NONE,
imports: NONE,
@@ -302,6 +344,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "css",
language: tree_sitter_css::LANGUAGE,
outline: outline!("css"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import_statement"],
@@ -311,6 +354,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "json",
language: tree_sitter_json::LANGUAGE,
outline: outline!("json"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
@@ -320,6 +364,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "yaml",
language: tree_sitter_yaml::LANGUAGE,
outline: outline!("yaml"),
highlights: None,
fold_nodes: &["block_mapping_pair", "block_sequence_item", "block_scalar"],
fold_bodies: NONE,
imports: NONE,
@@ -329,6 +374,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "toml",
language: tree_sitter_toml_ng::LANGUAGE,
outline: outline!("toml"),
highlights: None,
fold_nodes: &["table", "table_array_element", "string"],
fold_bodies: NONE,
imports: NONE,
@@ -338,6 +384,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "markdown",
language: tree_sitter_md::LANGUAGE,
outline: outline!("markdown"),
highlights: None,
fold_nodes: &["section", "fenced_code_block", "list", "block_quote", "html_block"],
fold_bodies: NONE,
imports: NONE,
@@ -347,6 +394,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "hcl",
language: tree_sitter_hcl::LANGUAGE,
outline: outline!("hcl"),
highlights: Some(Highlights { query: highlights!("hcl"), first_wins: false }),
fold_nodes: &["block", "heredoc_template"],
fold_bodies: NONE,
imports: NONE,
@@ -356,6 +404,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "nix",
language: tree_sitter_nix::LANGUAGE,
outline: outline!("nix"),
highlights: Some(Highlights { query: tree_sitter_nix::HIGHLIGHTS_QUERY, first_wins: true }),
fold_nodes: &["let_expression", "indented_string_expression"],
fold_bodies: NONE,
imports: NONE,
@@ -365,6 +414,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "proto",
language: tree_sitter_proto::LANGUAGE,
outline: outline!("proto"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import"],
@@ -374,6 +424,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "graphql",
language: tree_sitter_graphql::LANGUAGE,
outline: outline!("graphql"),
highlights: Some(Highlights { query: highlights!("graphql"), first_wins: false }),
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
@@ -383,6 +434,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "make",
language: tree_sitter_make::LANGUAGE,
outline: outline!("make"),
highlights: Some(Highlights { query: tree_sitter_make::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: &["rule", "conditional", "define_directive"],
fold_bodies: NONE,
imports: &["include_directive"],
@@ -392,6 +444,7 @@ pub(crate) static SPECS: &[Spec] = &[
name: "cmake",
language: tree_sitter_cmake::LANGUAGE,
outline: outline!("cmake"),
highlights: None,
fold_nodes: &["function_def", "macro_def", "if_condition", "foreach_loop", "while_loop", "block_def"],
fold_bodies: NONE,
imports: NONE,
+483
Переглянути файл
@@ -0,0 +1,483 @@
//! Syntax highlighting from a grammar's own `highlights.scm`, for languages the
//! UI has no CodeMirror mode for.
//!
//! Capture names follow the nvim-treesitter / Zed conventions (`@keyword`,
//! `@string.special.symbol`, ...) and are folded into [`SyntaxHighlightKind`] by
//! their longest known dotted prefix. Overlaps resolve the way those editors
//! do: a smaller node wins over the node containing it, and for the same node
//! the later pattern wins (the first one for tree-sitter CLI style queries). `@embedded` (string interpolation) clears the
//! surrounding colour. Besides tree-sitter's own text predicates, nvim's
//! `#lua-match?` is understood; patterns with other predicates never match.
use super::lines::LineIndex;
use serde::{Deserialize, Serialize};
use specta::Type;
use tree_sitter::{Language, Query, QueryCursor, QueryMatch, QueryPredicateArg, StreamingIterator, Tree};
/// Highlight classes sent to the UI, which maps each onto a Lezer tag.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SyntaxHighlightKind {
Keyword,
String,
StringSpecial,
Escape,
Regexp,
Atom,
Number,
Constant,
Comment,
DocComment,
Function,
FunctionCall,
Builtin,
Type,
Namespace,
Variable,
SelfVariable,
Property,
Attribute,
Macro,
Label,
Tag,
Operator,
Punctuation,
}
impl SyntaxHighlightKind {
/// Every kind, in `as u32` order: the legend for [`SyntaxHighlights::data`].
pub const ALL: [Self; 24] = [
Self::Keyword,
Self::String,
Self::StringSpecial,
Self::Escape,
Self::Regexp,
Self::Atom,
Self::Number,
Self::Constant,
Self::Comment,
Self::DocComment,
Self::Function,
Self::FunctionCall,
Self::Builtin,
Self::Type,
Self::Namespace,
Self::Variable,
Self::SelfVariable,
Self::Property,
Self::Attribute,
Self::Macro,
Self::Label,
Self::Tag,
Self::Operator,
Self::Punctuation,
];
}
/// Highlighted ranges of a whole document, packed like LSP semantic tokens.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SyntaxHighlights {
/// Legend: `data` kind `i` is `kinds[i]`.
pub kinds: Vec<SyntaxHighlightKind>,
/// `[from, to, kind]` triples: sorted, non-overlapping UTF-16 offsets.
pub data: Vec<u32>,
}
impl SyntaxHighlights {
pub(crate) fn new(data: Vec<u32>) -> Self {
Self { kinds: SyntaxHighlightKind::ALL.to_vec(), data }
}
}
/// What a capture paints over its node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Paint {
Kind(SyntaxHighlightKind),
/// `@embedded`: code inside a string, uncoloured unless captured itself.
Clear,
}
/// Capture name prefixes, most specific first within each family.
const CAPTURES: &[(&str, Paint)] = {
use Paint::{Clear, Kind};
use SyntaxHighlightKind as K;
&[
("embedded", Clear),
("keyword", Kind(K::Keyword)),
("include", Kind(K::Keyword)),
("import", Kind(K::Keyword)),
("conditional", Kind(K::Keyword)),
("repeat", Kind(K::Keyword)),
("exception", Kind(K::Keyword)),
("boolean", Kind(K::Keyword)),
("string.escape", Kind(K::Escape)),
("escape", Kind(K::Escape)),
("string.regex", Kind(K::Regexp)),
("string.regexp", Kind(K::Regexp)),
("string.special.symbol", Kind(K::Atom)),
("symbol", Kind(K::Atom)),
("string.special", Kind(K::StringSpecial)),
("string", Kind(K::String)),
("character", Kind(K::String)),
("number", Kind(K::Number)),
("float", Kind(K::Number)),
("constant.builtin", Kind(K::Constant)),
("constant.macro", Kind(K::Macro)),
("constant", Kind(K::Constant)),
// nvim greys out unused bindings (`_acc`); IDEA shows them as variables.
("comment.unused", Kind(K::Variable)),
("comment.doc", Kind(K::DocComment)),
("comment.documentation", Kind(K::DocComment)),
("comment", Kind(K::Comment)),
("function.builtin", Kind(K::Builtin)),
("function.macro", Kind(K::Macro)),
("function.definition", Kind(K::Function)),
("function", Kind(K::FunctionCall)),
("method", Kind(K::FunctionCall)),
("constructor", Kind(K::Type)),
("type.builtin", Kind(K::Builtin)),
("type", Kind(K::Type)),
("module", Kind(K::Namespace)),
("namespace", Kind(K::Namespace)),
("variable.builtin", Kind(K::SelfVariable)),
("variable.member", Kind(K::Property)),
("variable.field", Kind(K::Property)),
("variable", Kind(K::Variable)),
("parameter", Kind(K::Variable)),
("property", Kind(K::Property)),
("field", Kind(K::Property)),
("attribute", Kind(K::Attribute)),
("label", Kind(K::Label)),
("tag", Kind(K::Tag)),
("operator", Kind(K::Operator)),
("punctuation", Kind(K::Punctuation)),
]
};
/// The paint for a capture name: its longest prefix (on `.` boundaries) in
/// [`CAPTURES`]. Private captures (`@__name__`) and unknown names paint nothing.
fn paint_for(name: &str) -> Option<Paint> {
if name.starts_with('_') {
return None;
}
let mut prefix = name;
loop {
if let Some((_, p)) = CAPTURES.iter().find(|(n, _)| *n == prefix) {
return Some(*p);
}
prefix = &prefix[..prefix.rfind('.')?];
}
}
/// A predicate tree-sitter leaves to the caller.
enum Check {
/// `#lua-match?` / `#not-lua-match?` on a capture's text.
Matches {
capture: u32,
regex: regex_lite::Regex,
negate: bool,
},
Unsupported,
}
pub(crate) struct HighlightQuery {
query: Query,
/// By capture index.
paints: Vec<Option<Paint>>,
/// By pattern index.
checks: Vec<Vec<Check>>,
first_wins: bool,
}
impl HighlightQuery {
pub(crate) fn new(language: &Language, source: &str, first_wins: bool) -> Result<Self, tree_sitter::QueryError> {
let query = Query::new(language, source)?;
let paints = query.capture_names().iter().map(|n| paint_for(n)).collect();
let checks = (0..query.pattern_count())
.map(|i| {
query
.general_predicates(i)
.iter()
.filter_map(|p| match (&*p.operator, &*p.args) {
// Locals are not tracked: builtins are assumed not to be shadowed.
("is-not?", [QueryPredicateArg::String(s)]) if &**s == "local" => None,
(
op @ ("lua-match?" | "not-lua-match?"),
[QueryPredicateArg::Capture(c), QueryPredicateArg::String(pat)],
) => Some(match regex_lite::Regex::new(&lua_pattern_to_regex(pat)) {
Ok(regex) => Check::Matches { capture: *c, regex, negate: op.starts_with("not-") },
Err(_) => Check::Unsupported,
}),
_ => Some(Check::Unsupported),
})
.collect()
})
.collect();
Ok(Self { query, paints, checks, first_wins })
}
fn accepts(&self, m: &QueryMatch<'_, '_>, text: &str) -> bool {
self.checks[m.pattern_index].iter().all(|check| match check {
Check::Matches { capture, regex, negate } => m
.captures
.iter()
.filter(|c| c.index == *capture)
.all(|c| regex.is_match(&text[c.node.byte_range()]) != *negate),
Check::Unsupported => false,
})
}
}
/// Translates the Lua patterns used by nvim queries (`^[A-Z][A-Z_0-9]+$`, `^//!`) to regex syntax.
fn lua_pattern_to_regex(pat: &str) -> String {
let class = |c: char| match c {
'a' => Some("A-Za-z"),
'd' => Some("0-9"),
'l' => Some("a-z"),
'u' => Some("A-Z"),
'w' => Some("A-Za-z0-9"),
's' => Some("\\s"),
'x' => Some("0-9A-Fa-f"),
'p' => Some("[:punct:]"),
_ => None,
};
let mut out = String::with_capacity(pat.len() + 8);
let mut in_set = false;
let mut chars = pat.chars();
while let Some(c) = chars.next() {
match c {
'%' => {
let Some(next) = chars.next() else { break };
match class(next) {
Some(set) if in_set => out.push_str(set),
Some(set) => {
out.push('[');
out.push_str(set);
out.push(']');
}
None => out.push_str(&regex_lite::escape(&next.to_string())),
}
}
'[' if !in_set => {
in_set = true;
out.push(c);
}
']' if in_set => {
in_set = false;
out.push(c);
}
// Lua's lazy `*` (inside a set, `-` is a range).
'-' if !in_set => out.push_str("*?"),
'\\' | '{' | '}' | '|' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
}
out
}
/// Byte value for "no colour" in the paint buffer; kinds are `1 + index`.
const NONE: u8 = 0;
/// `[from, to, kind]` UTF-16 triples for `text`; see [`SyntaxHighlights::data`].
pub(crate) fn highlights(q: &HighlightQuery, tree: &Tree, text: &str) -> Vec<u32> {
// (byte len, rank, start, end, paint): painted largest first, then by rank,
// so inner nodes and winning patterns overwrite.
let mut captures: Vec<(usize, usize, usize, usize, Paint)> = Vec::new();
let mut cursor = QueryCursor::new();
let mut matches = cursor.matches(&q.query, tree.root_node(), text.as_bytes());
while let Some(m) = matches.next() {
if !q.accepts(m, text) {
continue;
}
for c in m.captures {
if let Some(paint) = q.paints[c.index as usize] {
let r = c.node.byte_range();
if r.start < r.end {
let rank = if q.first_wins { usize::MAX - m.pattern_index } else { m.pattern_index };
captures.push((r.end - r.start, rank, r.start, r.end, paint));
}
}
}
}
captures.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
let mut painted = vec![NONE; text.len()];
for &(_, _, start, end, paint) in &captures {
let v = match paint {
Paint::Kind(k) => 1 + k as u8,
Paint::Clear => NONE,
};
painted[start..end].fill(v);
}
let lines = LineIndex::new(text);
let mut data = Vec::new();
let mut i = 0;
while i < painted.len() {
let v = painted[i];
let start = i;
while i < painted.len() && painted[i] == v {
i += 1;
}
// Node boundaries are char boundaries; whitespace-only runs stay uncoloured.
if v != NONE && text.is_char_boundary(start) && text.is_char_boundary(i) && !text[start..i].trim().is_empty() {
data.extend([lines.utf16_at(start) as u32, lines.utf16_at(i) as u32, (v - 1) as u32]);
}
}
data
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capture_names_fold_to_the_longest_known_prefix() {
use SyntaxHighlightKind as K;
assert_eq!(paint_for("keyword.function"), Some(Paint::Kind(K::Keyword)));
assert_eq!(paint_for("string.special.symbol"), Some(Paint::Kind(K::Atom)));
assert_eq!(paint_for("string.special.path"), Some(Paint::Kind(K::StringSpecial)));
assert_eq!(paint_for("comment.doc.__attribute__"), Some(Paint::Kind(K::DocComment)));
assert_eq!(paint_for("punctuation.bracket"), Some(Paint::Kind(K::Punctuation)));
assert_eq!(paint_for("embedded"), Some(Paint::Clear));
assert_eq!(paint_for("__name__"), None);
assert_eq!(paint_for("spell"), None);
}
/// `(text, kind)` of every highlighted range.
fn spans(lang: &str, text: &str) -> Vec<(String, SyntaxHighlightKind)> {
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new(lang), text).unwrap();
let units: Vec<u16> = text.encode_utf16().collect();
h.data
.chunks(3)
.map(|t| (String::from_utf16(&units[t[0] as usize..t[1] as usize]).unwrap(), h.kinds[t[2] as usize]))
.collect()
}
#[test]
fn highlights_elixir() {
use SyntaxHighlightKind as K;
let src = "defmodule Greeter do\n @moduledoc \"Hi\"\n # 😀 note\n def hello(name, _opts) do\n IO.puts(\"Hello #{name}\")\n :ok\n end\nend\n";
let got = spans("elixir", src);
let kind = |t: &str| got.iter().find(|(s, _)| s == t).map(|(_, k)| *k);
assert_eq!(kind("defmodule"), Some(K::Keyword));
assert_eq!(kind("Greeter"), Some(K::Namespace));
assert_eq!(kind("\"Hi\""), Some(K::DocComment));
assert_eq!(kind("# 😀 note"), Some(K::Comment));
assert_eq!(kind("def"), Some(K::Keyword));
assert_eq!(kind("hello"), Some(K::FunctionCall));
assert_eq!(kind("_opts"), Some(K::Variable));
assert_eq!(kind("puts"), Some(K::FunctionCall));
// Interpolation clears the string colour; its contents are coloured on their own.
assert_eq!(kind("\"Hello "), Some(K::String));
assert_eq!(kind("#{"), Some(K::Punctuation));
assert_eq!(kind(":ok"), Some(K::Atom));
assert_eq!(kind("end"), Some(K::Keyword));
// Sorted and non-overlapping.
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new("elixir"), src).unwrap();
assert!(h.data.chunks(3).zip(h.data.chunks(3).skip(1)).all(|(a, b)| a[0] < a[1] && a[1] <= b[0]));
}
#[test]
fn highlights_other_grammar_only_languages() {
use SyntaxHighlightKind as K;
type Expect<'a> = &'a [(&'a str, SyntaxHighlightKind)];
let cases: &[(&str, &str, Expect)] = &[
(
"zig",
"const std = @import(\"std\");\n// hi\npub fn main() void {\n var x: u32 = 42;\n _ = x;\n}\n",
&[
("const", K::Keyword),
("\"std\"", K::String),
("// hi", K::Comment),
("42", K::Number),
("u32", K::Builtin),
],
),
(
"nix",
"{ pkgs ? import <nixpkgs> {} }:\n# hi\nlet x = 1; in pkgs.mkShell { name = \"dev\"; }\n",
&[
("let", K::Keyword),
("# hi", K::Comment),
("1", K::Number),
("\"dev\"", K::String),
("import", K::Builtin),
],
),
(
"graphql",
"# hi\nquery Hero($id: ID!) @cached {\n hero(id: $id) { name ...Friends }\n}\nenum Episode { NEWHOPE }\n",
&[
("# hi", K::Comment),
("query", K::Keyword),
("Hero", K::FunctionCall),
("$id", K::Variable),
("ID", K::Type),
("@cached", K::Attribute),
("name", K::Property),
("Friends", K::FunctionCall),
("NEWHOPE", K::Constant),
],
),
(
"hcl",
"# hi\nresource \"aws_instance\" \"web\" {\n ami = var.ami\n count = 2\n tags = { Name = \"web-${var.env}\" }\n name = upper(\"x\")\n}\n",
&[
("# hi", K::Comment),
("resource", K::Keyword),
("aws_instance", K::Type),
("ami", K::Property),
("2", K::Number),
("upper", K::FunctionCall),
("\"web-", K::String),
("env", K::Property),
("var", K::Variable),
],
),
("make", "# hi\nCC := gcc\nall: main.o\n\t$(CC) -o app main.o\n", &[("# hi", K::Comment)]),
];
for (lang, src, expect) in cases {
let got = spans(lang, src);
for (text, kind) in *expect {
assert!(got.iter().any(|(s, k)| s == text && k == kind), "{lang}: {text:?} as {kind:?} in {got:?}");
}
}
}
#[test]
fn languages_without_a_query_have_none() {
assert_eq!(crate::Syntax::new().highlights(&ide_core::LanguageId::new("rust"), "fn a() {}"), None);
}
#[test]
fn every_highlights_query_compiles() {
for spec in super::super::grammars::SPECS {
if let Some(h) = &spec.highlights {
let lang = Language::new(spec.language);
if let Err(e) = HighlightQuery::new(&lang, h.query, h.first_wins) {
panic!("{}: {e}", spec.name);
}
}
}
}
#[test]
fn lua_patterns_translate() {
assert_eq!(lua_pattern_to_regex("^[A-Z][A-Z_0-9]+$"), "^[A-Z][A-Z_0-9]+$");
assert_eq!(lua_pattern_to_regex("^//!"), "^//!");
assert_eq!(lua_pattern_to_regex("^%u[%w_]*$"), "^[A-Z][A-Za-z0-9_]*$");
assert_eq!(lua_pattern_to_regex("a.-b%."), "a.*?b\\.");
}
#[test]
fn legend_matches_discriminants() {
for (i, k) in SyntaxHighlightKind::ALL.iter().enumerate() {
assert_eq!(*k as usize, i);
}
}
}
+1 -1
Переглянути файл
@@ -40,7 +40,7 @@ impl<'a> LineIndex<'a> {
}
/// UTF-16 offset of a char-boundary byte offset.
fn utf16_at(&self, byte: usize) -> usize {
pub(crate) fn utf16_at(&self, byte: usize) -> usize {
if self.checkpoints.is_empty() {
return byte;
}
+83 -6
Переглянути файл
@@ -1,20 +1,24 @@
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges.
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting.
mod cache;
mod folding;
mod grammars;
mod highlight;
pub(crate) mod lines;
mod outline;
mod selection;
mod web;
use crate::{FoldRange, LanguageConfig, LanguageRegistry, SymbolTag};
pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats};
use grammars::{SPECS, Spec};
use ide_core::{LanguageId, OutlineItem, Range};
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
use ide_core::{LanguageId, OutlineItem, Pos, Range};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::OnceLock;
use tree_sitter::{Language, Parser, Tree};
pub use web::{CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, WebReference, WebReferenceKind};
/// Texts larger than this are not parsed (minified bundles, generated dumps).
pub const MAX_PARSE_BYTES: usize = 16 * 1024 * 1024;
@@ -31,6 +35,7 @@ pub(crate) struct Grammar {
pub(crate) spec: &'static Spec,
pub(crate) language: Language,
outline: OnceLock<Option<outline::OutlineQuery>>,
highlights: OnceLock<Option<highlight::HighlightQuery>>,
kinds: OnceLock<folding::KindTable>,
}
@@ -50,6 +55,17 @@ impl Grammar {
})
.as_ref()
}
fn highlight_query(&self) -> Option<&highlight::HighlightQuery> {
self.highlights
.get_or_init(|| {
let h = self.spec.highlights.as_ref()?;
highlight::HighlightQuery::new(&self.language, h.query, h.first_wins)
.inspect_err(|e| tracing::error!("highlights query for {} is invalid: {e}", self.spec.name))
.ok()
})
.as_ref()
}
}
thread_local! {
@@ -72,6 +88,7 @@ impl Syntax {
spec,
language: Language::new(spec.language),
outline: OnceLock::new(),
highlights: OnceLock::new(),
kinds: OnceLock::new(),
})
.collect();
@@ -102,6 +119,8 @@ impl Syntax {
FP.get_or_init(|| {
let mut h = blake3::Hasher::new();
h.update(env!("CARGO_PKG_VERSION").as_bytes());
// Bump when web definitions (`.class`, `#id`, `--var` tags) change.
h.update(b"web-definitions-1");
for s in SPECS {
h.update(s.name.as_bytes());
h.update(&Language::new(s.language).abi_version().to_le_bytes());
@@ -126,7 +145,8 @@ impl Syntax {
/// Whether [`Syntax::tags`] can return anything for this language (data
/// formats such as JSON only have an outline). Lets indexers skip parsing.
pub fn has_symbols(&self, lang: &LanguageId) -> bool {
self.grammar(lang).and_then(Grammar::outline_query).is_some_and(|q| q.has_tags)
self.web_grammar(lang).is_some()
|| self.grammar(lang).and_then(Grammar::outline_query).is_some_and(|q| q.has_tags)
}
pub fn outline(&self, lang: &LanguageId, text: &str) -> Vec<OutlineItem> {
@@ -143,11 +163,68 @@ impl Syntax {
}
pub fn tags(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
let mut tags = self
.analyze(lang, text, |g, tree, text| {
let query = g.outline_query()?;
Some(outline::tags(g, query, tree, text))
})
.unwrap_or_default();
tags.extend(self.web_definitions(lang, text));
tags
}
/// 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.
fn web_grammar(&self, lang: &LanguageId) -> Option<&Grammar> {
let name = match lang.as_str() {
"scss" | "less" => "css",
"vue" | "svelte" => "html",
_ => self.grammar(lang).map(|g| g.spec.name)?,
};
web::is_web_grammar(name).then(|| self.grammar(&LanguageId::new(name))).flatten()
}
fn with_web_tree<R>(
&self,
lang: &LanguageId,
text: &str,
f: impl FnOnce(&Grammar, Option<&Grammar>, &Tree) -> R,
) -> Option<R> {
let g = self.web_grammar(lang)?;
if text.len() > MAX_PARSE_BYTES {
return None;
}
let tree = parse(&g.language, text, None)?;
Some(f(g, self.grammar(&LanguageId::new("css")), &tree))
}
/// CSS class (`.card`), id (`#main`) and custom property (`--accent`)
/// definitions of a stylesheet or of the `<style>` elements of a document.
pub fn web_definitions(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
self.with_web_tree(lang, text, |g, css, tree| web::definitions(g, css, tree, text)).unwrap_or_default()
}
/// The `class` / `id` / `href="#…"` / `var(--…)` reference at `pos`.
pub fn web_reference_at(&self, lang: &LanguageId, text: &str, pos: Pos) -> Option<WebReference> {
self.with_web_tree(lang, text, |g, css, tree| web::reference_at(g, css, tree, text, pos)).flatten()
}
/// File paths written in an HTML document or stylesheet (`href`, `src`, `srcset`, `url()`, `@import`).
pub fn web_file_references(&self, lang: &LanguageId, text: &str) -> Vec<FileReference> {
self.with_web_tree(lang, text, |g, css, tree| web::file_references(g, css, tree, text)).unwrap_or_default()
}
/// Value ranges of the `id="name"` / `name="name"` attributes in an HTML document.
pub fn web_anchors(&self, lang: &LanguageId, text: &str, name: &str) -> Vec<Range> {
self.with_web_tree(lang, text, |_, _, tree| web::anchors(tree, text, name)).unwrap_or_default()
}
/// Highlighting from the grammar's own query; `None` without one.
pub fn highlights(&self, lang: &LanguageId, text: &str) -> Option<SyntaxHighlights> {
self.analyze(lang, text, |g, tree, text| {
let query = g.outline_query()?;
Some(outline::tags(g, query, tree, text))
Some(SyntaxHighlights::new(highlight::highlights(g.highlight_query()?, tree, text)))
})
.unwrap_or_default()
}
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
+85
Переглянути файл
@@ -1085,3 +1085,88 @@ fn large_input_is_not_parsed() {
let big = "a".repeat(MAX_PARSE_BYTES + 1);
assert!(syntax().outline(&lang("rust"), &big).is_empty());
}
// --- web references -------------------------------------------------------------
fn web_defs(id: &str, src: &str) -> Vec<(String, SymbolKind, u32, u32)> {
syntax()
.web_definitions(&lang(id), src)
.into_iter()
.map(|t| (t.name, t.kind, t.range.start.line, t.range.start.col))
.collect()
}
fn web_ref(id: &str, src: &str) -> Option<(WebReferenceKind, String, u32, u32)> {
let at = src.find('|').expect("caret marker");
let text = src.replace('|', "");
let line = text[..at].matches('\n').count() as u32;
let col = (at - text[..at].rfind('\n').map_or(0, |i| i + 1)) as u32;
syntax()
.web_reference_at(&lang(id), &text, Pos::new(line, col))
.map(|r| (r.kind, r.name, r.range.start.col, r.range.end.col))
}
#[test]
fn web_definitions_of_stylesheets_and_style_elements() {
let css = ".a.b, div#main > .c:hover { color: var(--x); --y: 1px; }\n@media (x) { .d {} }\n";
assert_eq!(
web_defs("css", css),
vec![
(".a".into(), CSS_CLASS, 0, 1),
(".b".into(), CSS_CLASS, 0, 3),
("#main".into(), CSS_ID, 0, 10),
(".c".into(), CSS_CLASS, 0, 18),
("--y".into(), CSS_VARIABLE, 0, 45),
(".d".into(), CSS_CLASS, 1, 14),
]
);
// Pseudo-classes (`:hover`) are not classes; nested SCSS rules parse with the CSS grammar.
assert!(!web_defs("css", css).iter().any(|d| d.0 == ".hover"));
assert!(web_defs("scss", ".card { &:hover { } .title { } }").iter().any(|d| d.0 == ".title"));
let html = "<p class=\"x\">\n<style>\n .card { --gap: 2px }\n</style>";
assert_eq!(web_defs("html", html), vec![(".card".into(), CSS_CLASS, 2, 3), ("--gap".into(), CSS_VARIABLE, 2, 10)]);
assert!(syntax().tags(&lang("css"), css).iter().any(|t| t.name == ".a"));
assert!(syntax().has_symbols(&lang("css")) && syntax().has_symbols(&lang("vue")));
}
#[test]
fn web_references_in_attributes_and_stylesheets() {
use WebReferenceKind::*;
assert_eq!(web_ref("html", r##"<div class="card bi|g">"##), Some((Class, "big".into(), 17, 20)));
assert_eq!(web_ref("html", r##"<div class="|card big">"##), Some((Class, "card".into(), 12, 16)));
assert_eq!(web_ref("html", r##"<div id="ma|in">"##), Some((Id, "main".into(), 9, 13)));
assert_eq!(web_ref("html", r##"<a href="#to|p">"##), Some((Anchor, "top".into(), 9, 13)));
assert_eq!(web_ref("html", r##"<a href="page.ht|ml">"##), None);
assert_eq!(
web_ref("html", r##"<p style="color: var(--ac|cent)">"##),
Some((CssVariable, "--accent".into(), 21, 29))
);
assert_eq!(web_ref("html", "<style>\n.a { color: var(--x|) }\n</style>").map(|r| r.1), Some("--x".into()));
assert_eq!(web_ref("css", ".a { color: var(--a|ccent, red) }"), Some((CssVariable, "--accent".into(), 16, 24)));
assert_eq!(web_ref("css", ".a { color: re|d }"), None);
assert_eq!(web_ref("vue", r##"<template><div class="ti|tle"/></template>"##).map(|r| r.0), Some(Class));
}
#[test]
fn web_anchors_find_ids_and_names() {
let html = "<h2 id=\"top\">x</h2>\n<a name=\"top\"></a>\n<p class=\"top\">";
let found: Vec<(u32, u32)> =
syntax().web_anchors(&lang("html"), html, "top").into_iter().map(|r| (r.start.line, r.start.col)).collect();
assert_eq!(found, vec![(0, 8), (1, 9)]);
}
#[test]
fn web_file_references_in_attributes_and_stylesheets() {
let refs = |id: &str, src: &str| -> Vec<String> {
syntax().web_file_references(&lang(id), src).into_iter().map(|r| r.value).collect()
};
let html = concat!(
"<link href=\"css/a.css\"><img srcset=\"a.png 1x, b.png 2x\" src=img/c.png alt=\"x\">\n",
"<a href=\"#top\" class=\"k\">t</a><div style=\"background: url(d.svg)\"></div>\n",
"<style>@import \"e.css\"; .x { background: url('f.png') }</style>",
);
assert_eq!(refs("html", html), ["css/a.css", "a.png", "b.png", "img/c.png", "#top", "d.svg", "e.css", "f.png"]);
assert_eq!(refs("css", "@import url(g.css);\n.y { mask: url(\"h.svg#i\") }"), ["g.css", "h.svg#i"]);
let first = &syntax().web_file_references(&lang("html"), html)[0];
assert_eq!((first.range.start.col, first.range.end.col), (12, 21));
}
+374
Переглянути файл
@@ -0,0 +1,374 @@
//! Web references that no language server resolves: HTML `class` / `id`
//! attributes to the CSS selectors that style them, `href="#id"` to the element
//! with that id, and `var(--x)` to the custom property's declarations.
//!
//! Definitions (`.card`, `#main`, `--accent`) come from stylesheets and the
//! `<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::{Grammar, parse};
use crate::SymbolTag;
use ide_core::{Pos, Range, SymbolKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use tree_sitter::{Node, Tree};
/// Index symbol kinds of web definitions; names carry the CSS sigil.
pub const CSS_CLASS: SymbolKind = SymbolKind::Class;
pub const CSS_ID: SymbolKind = SymbolKind::Field;
pub const CSS_VARIABLE: SymbolKind = SymbolKind::Variable;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum WebReferenceKind {
/// A class in a `class` / `className` attribute: `.name` selectors.
Class,
/// An `id` attribute value: `#name` selectors.
Id,
/// `href="#name"`: the element with that id in the same document.
Anchor,
/// `var(--name)`: the custom property's declarations.
CssVariable,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WebReference {
pub kind: WebReferenceKind,
/// Without sigil: `card`, `main`, `--accent`.
pub name: String,
pub range: Range,
}
impl WebReference {
/// The index symbol a reference resolves to: `.card`, `#main`, `--accent`.
pub fn symbol(&self) -> Option<(String, SymbolKind)> {
match self.kind {
WebReferenceKind::Class => Some((format!(".{}", self.name), CSS_CLASS)),
WebReferenceKind::Id => Some((format!("#{}", self.name), CSS_ID)),
WebReferenceKind::CssVariable => Some((self.name.clone(), CSS_VARIABLE)),
WebReferenceKind::Anchor => None,
}
}
}
/// Grammars whose documents carry web definitions and references.
pub(crate) fn is_web_grammar(name: &str) -> bool {
matches!(name, "css" | "html")
}
/// Stylesheet text embedded in a document: `(byte offset, text)`.
fn css_regions<'t>(grammar: &str, tree: &Tree, text: &'t str) -> Vec<(usize, &'t str)> {
match grammar {
"css" => vec![(0, text)],
"html" => {
let mut out = Vec::new();
walk(tree.root_node(), &mut |n| {
if n.kind() == "style_element" {
let mut c = n.walk();
for raw in n.children(&mut c).filter(|c| c.kind() == "raw_text") {
out.push((raw.start_byte(), &text[raw.start_byte()..raw.end_byte()]));
}
return false;
}
true
});
out
}
_ => Vec::new(),
}
}
/// Pre-order walk; `f` returns whether to descend.
fn walk<'t>(n: Node<'t>, f: &mut dyn FnMut(Node<'t>) -> bool) {
if !f(n) {
return;
}
let mut c = n.walk();
for child in n.children(&mut c) {
walk(child, f);
}
}
fn text_of<'t>(n: Node, text: &'t str) -> &'t str {
text.get(n.start_byte()..n.end_byte()).unwrap_or_default()
}
/// `.name`, `#name` and `--name` definitions in `text` (a stylesheet, or a document with `<style>`).
pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: &str) -> Vec<SymbolTag> {
let idx = LineIndex::new(text);
let mut out = Vec::new();
for (base, css_text) in css_regions(g.spec.name, tree, text) {
let parsed;
let css_tree = if base == 0 && g.spec.name == "css" {
tree
} else {
let Some(css) = css else { continue };
let Some(t) = parse(&css.language, css_text, None) else { continue };
parsed = t;
&parsed
};
walk(css_tree.root_node(), &mut |n| {
let def = match n.kind() {
"class_name" if n.parent().is_some_and(|p| p.kind() == "class_selector") => {
Some((format!(".{}", text_of(n, css_text)), CSS_CLASS))
}
"id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID)),
"property_name" if text_of(n, css_text).starts_with("--") => {
Some((text_of(n, css_text).to_owned(), CSS_VARIABLE))
}
_ => None,
};
if let Some((name, kind)) = def {
let range = idx.range(base + n.start_byte(), base + n.end_byte());
out.push(SymbolTag { name, kind, container: None, range });
}
true
});
}
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)?;
let start = value[..rel.min(value.len())].rfind(char::is_whitespace).map_or(0, |i| i + 1);
let end = value[rel.min(value.len())..].find(char::is_whitespace).map_or(value.len(), |i| rel + i);
(start < end).then(|| (base + start, &value[start..end]))
}
/// `var(--name)` around byte `at` of a stylesheet tree.
fn css_variable_at(tree: &Tree, css_text: &str, at: usize) -> Option<(usize, usize, String)> {
let mut n = tree.root_node().descendant_for_byte_range(at, at)?;
if n.kind() != "plain_value" {
// The caret right after `--x` in `var(--x)`.
n = tree.root_node().descendant_for_byte_range(at.saturating_sub(1), at.saturating_sub(1))?;
}
let name = text_of(n, css_text);
let call = n.parent()?.parent()?;
let is_var = call.kind() == "call_expression"
&& call
.child_by_field_name("function_name")
.or_else(|| call.child(0))
.is_some_and(|f| text_of(f, css_text) == "var");
(n.kind() == "plain_value" && name.starts_with("--") && is_var)
.then(|| (n.start_byte(), n.end_byte(), name.to_owned()))
}
/// The web reference at `pos` of a document parsed as `tree`.
pub(crate) fn reference_at(
g: &Grammar,
css: Option<&Grammar>,
tree: &Tree,
text: &str,
pos: Pos,
) -> Option<WebReference> {
let at = byte_at(text, pos)?;
let idx = LineIndex::new(text);
let make = |kind, from: usize, to: usize, name: String| WebReference { kind, name, range: idx.range(from, to) };
// Stylesheet regions: `var(--x)`.
for (base, css_text) in css_regions(g.spec.name, tree, text) {
if at < base || at > base + css_text.len() {
continue;
}
let parsed;
let css_tree = if g.spec.name == "css" {
tree
} else {
parsed = parse(&css?.language, css_text, None)?;
&parsed
};
let (from, to, name) = css_variable_at(css_tree, css_text, at - base)?;
return Some(make(WebReferenceKind::CssVariable, base + from, base + to, name));
}
if g.spec.name != "html" {
return None;
}
// HTML attribute values.
let node = tree.root_node().descendant_for_byte_range(at, at)?;
let value = std::iter::successors(Some(node), |n| n.parent()).find(|n| n.kind() == "attribute_value")?;
let attribute = std::iter::successors(value.parent(), |n| n.parent()).find(|n| n.kind() == "attribute")?;
let attr_name = attribute.child(0).map(|n| text_of(n, text).to_ascii_lowercase())?;
let (vs, vtext) = (value.start_byte(), text_of(value, text));
match attr_name.as_str() {
"class" | "classname" | "class:list" => {
let (from, token) = token_at(vtext, vs, at)?;
Some(make(WebReferenceKind::Class, from, from + token.len(), token.to_owned()))
}
"id" => {
let (from, token) = token_at(vtext, vs, at)?;
Some(make(WebReferenceKind::Id, from, from + token.len(), token.to_owned()))
}
"href" | "xlink:href" if vtext.len() > 1 && vtext.starts_with('#') => {
Some(make(WebReferenceKind::Anchor, vs, vs + vtext.len(), vtext[1..].to_owned()))
}
"style" => {
// An inline declaration list: parse it as the block of a rule.
let wrapped = format!("x{{{vtext}}}");
let t = parse(&css?.language, &wrapped, None)?;
let (from, to, name) = css_variable_at(&t, &wrapped, at - vs + 2)?;
Some(make(WebReferenceKind::CssVariable, vs + from - 2, vs + to - 2, name))
}
_ => None,
}
}
/// Elements whose `id` (or `<a name>`) is `name`: the targets of `href="#name"`.
pub(crate) fn anchors(tree: &Tree, text: &str, name: &str) -> Vec<Range> {
let idx = LineIndex::new(text);
let mut out = Vec::new();
walk(tree.root_node(), &mut |n| {
if n.kind() == "attribute" {
let attr = n.child(0).map(|a| text_of(a, text).to_ascii_lowercase());
if matches!(attr.as_deref(), Some("id" | "name")) {
let mut found = None;
walk(n, &mut |v| {
if v.kind() == "attribute_value" && text_of(v, text) == name {
found = Some(v);
}
found.is_none()
});
if let Some(v) = found {
out.push(idx.range(v.start_byte(), v.end_byte()));
}
}
return false;
}
true
});
out
}
/// A path written in a document: an HTML URL attribute, a CSS `url()` / `@import`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileReference {
pub range: Range,
pub value: String,
}
/// HTML attributes whose value is a URL.
const URL_ATTRIBUTES: &[&str] = &[
"href",
"src",
"srcset",
"action",
"formaction",
"poster",
"data",
"cite",
"background",
"manifest",
"xlink:href",
"longdesc",
"icon",
];
/// `url(…)` arguments and `@import` targets of a stylesheet: `(start, end)` byte ranges.
fn css_paths(tree: &Tree, css_text: &str, out: &mut Vec<(usize, usize)>) {
let target = |n: Node| -> Option<(usize, usize)> {
let n =
if n.kind() == "string_value" { n.named_child(0).filter(|c| c.kind() == "string_content")? } else { n };
matches!(n.kind(), "plain_value" | "string_content").then(|| (n.start_byte(), n.end_byte()))
};
walk(tree.root_node(), &mut |n| {
match n.kind() {
"import_statement" => {
if let Some(first) = n.named_child(0)
&& first.kind() == "string_value"
{
out.extend(target(first));
}
}
"call_expression" => {
let is_url =
n.named_child(0).is_some_and(|f| f.kind() == "function_name" && text_of(f, css_text) == "url");
if is_url
&& let Some(args) = n.child_by_field_name("arguments").or_else(|| n.named_child(1))
&& let Some(arg) = args.named_child(0)
{
out.extend(target(arg));
}
}
_ => {}
}
true
});
}
/// File paths written in an HTML document or a stylesheet.
pub(crate) fn file_references(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: &str) -> Vec<FileReference> {
let idx = LineIndex::new(text);
let mut spans: Vec<(usize, usize)> = Vec::new();
for (base, css_text) in css_regions(g.spec.name, tree, text) {
let parsed;
let css_tree = if g.spec.name == "css" {
tree
} else {
let Some(t) = css.and_then(|c| parse(&c.language, css_text, None)) else { continue };
parsed = t;
&parsed
};
let mut found = Vec::new();
css_paths(css_tree, css_text, &mut found);
spans.extend(found.into_iter().map(|(s, e)| (base + s, base + e)));
}
if g.spec.name == "html" {
walk(tree.root_node(), &mut |n| {
if n.kind() != "attribute" {
return true;
}
let name = n.child(0).map(|a| text_of(a, text).to_ascii_lowercase()).unwrap_or_default();
let mut value = None;
walk(n, &mut |v| {
if v.kind() == "attribute_value" {
value = Some(v);
}
value.is_none()
});
let Some(v) = value else { return false };
let (vs, vtext) = (v.start_byte(), text_of(v, text));
match name.as_str() {
"srcset" => {
// `a.png 1x, b.png 2x`: the URL of each candidate.
let mut at = 0;
for part in vtext.split(',') {
let lead = part.len() - part.trim_start().len();
let url = part.split_whitespace().next().unwrap_or_default();
if !url.is_empty() {
spans.push((vs + at + lead, vs + at + lead + url.len()));
}
at += part.len() + 1;
}
}
"style" => {
let wrapped = format!("x{{{vtext}}}");
if let Some(t) = css.and_then(|c| parse(&c.language, &wrapped, None)) {
let mut found = Vec::new();
css_paths(&t, &wrapped, &mut found);
spans.extend(found.into_iter().map(|(s, e)| (vs + s - 2, vs + e - 2)));
}
}
_ if URL_ATTRIBUTES.contains(&name.as_str()) && !vtext.trim().is_empty() => {
spans.push((vs, vs + vtext.len()));
}
_ => {}
}
false
});
}
spans.sort_unstable();
spans.into_iter().map(|(s, e)| FileReference { range: idx.range(s, e), value: text[s..e].to_owned() }).collect()
}
+2
Переглянути файл
@@ -121,6 +121,7 @@ pub fn client_capabilities() -> Value {
"honorsChangeAnnotations": false
},
"codeLens": { "dynamicRegistration": false },
"documentLink": { "dynamicRegistration": false, "tooltipSupport": true },
"formatting": { "dynamicRegistration": false },
"rangeFormatting": { "dynamicRegistration": false },
"rename": {
@@ -205,6 +206,7 @@ pub fn capability_key(method: &str) -> Option<&'static str> {
"textDocument/inlayHint" => "inlayHintProvider",
"textDocument/semanticTokens" | "textDocument/semanticTokens/full" => "semanticTokensProvider",
"textDocument/codeLens" => "codeLensProvider",
"textDocument/documentLink" => "documentLinkProvider",
"textDocument/prepareCallHierarchy" => "callHierarchyProvider",
"textDocument/prepareTypeHierarchy" => "typeHierarchyProvider",
_ => return None,
+42
Переглянути файл
@@ -783,6 +783,27 @@ pub fn code_lens(conv: &Conv, path: &Path, l: lsp::CodeLens) -> CodeLens {
CodeLens { range: conv.range(path, l.range), command: l.command.map(command) }
}
pub fn document_link(conv: &Conv, path: &Path, l: lsp::DocumentLink) -> Option<DocumentLink> {
let target = l.target?;
let target = target.as_str();
let (file, url) = match uri_to_path(target) {
Some(p) => (Some(p), None),
None => (None, Some(target.to_owned())),
};
let fragment = file
.as_ref()
.and_then(|_| target.split_once('#'))
.map(|(_, f)| percent_encoding::percent_decode_str(f).decode_utf8_lossy().into_owned())
.filter(|f| !f.is_empty());
Some(DocumentLink {
range: conv.range(path, l.range),
path: file.map(Into::into),
fragment,
url,
tooltip: l.tooltip,
})
}
pub fn call_item(conv: &Conv, item: &lsp::CallHierarchyItem, from_ranges: Vec<Range>) -> Option<HierarchyItem> {
let (path, uri) = uri_target(item.uri.as_str());
Some(HierarchyItem {
@@ -1112,4 +1133,25 @@ mod tests {
assert_eq!(h.kind, InlayKind::Type);
assert!(h.padding_left && !h.padding_right);
}
#[cfg(unix)]
#[test]
fn document_links_split_file_targets_and_urls() {
let conv = Conv::utf16();
let link = |target: Option<&str>| {
serde_json::from_value::<lsp::DocumentLink>(json!({
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 15 } },
"target": target,
}))
.unwrap()
};
let here = Path::new("/p/index.html");
let file = document_link(&conv, here, link(Some("file:///p/a%20b.md#L12"))).unwrap();
assert_eq!(file.path.as_deref(), Some(Path::new("/p/a b.md")));
assert_eq!(file.fragment.as_deref(), Some("L12"));
assert_eq!(file.range, Range::new(p(0, 6), p(0, 15)));
let web = document_link(&conv, here, link(Some("https://example.com/#top"))).unwrap();
assert_eq!((web.path, web.url.as_deref(), web.fragment), (None, Some("https://example.com/#top"), None));
assert!(document_link(&conv, here, link(None)).is_none());
}
}
+3
Переглянути файл
@@ -179,6 +179,9 @@ impl LspManager {
ide_core::event::ServerStatus::Missing => {
"jdtls is not installed (Settings › Languages & Frameworks › Language Servers)".to_owned()
}
ide_core::event::ServerStatus::Misconfigured => {
server.status_message().unwrap_or_else(|| "jdtls cannot start".to_owned())
}
_ => format!("jdtls is not ready ({status:?})"),
}))
}
+3 -1
Переглянути файл
@@ -10,6 +10,8 @@ use std::sync::{Arc, OnceLock};
pub enum LaunchError {
/// The server binary is not installed / not on `PATH`.
Missing,
/// The configuration can't be launched (`LanguageServerConfig::launch_error`).
Config(String),
Failed(String),
}
@@ -72,7 +74,7 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> PathBuf {
if !is_proxy || command.contains('/') {
return binary;
}
let works = std::process::Command::new(&binary)
let works = ide_core::process::no_window(&mut std::process::Command::new(&binary))
.arg("--version")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
+58 -3
Переглянути файл
@@ -339,7 +339,7 @@ impl LspManager {
if let Some(message) = &cfg.launch_error {
// A missing binary still asks to be installed first.
let missing = !me.launcher.available(&cfg, &root);
return Err(if missing { LaunchError::Missing } else { LaunchError::Failed(message.clone()) });
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
}
me.launcher.launch(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)))
})
@@ -358,6 +358,13 @@ impl LspManager {
}
return;
}
Err(LaunchError::Config(message)) => {
tracing::warn!("{}: {message}", server.name);
if server.finish_start(generation, Conn::Failed) {
server.set_status(&self.sink, ide_core::event::ServerStatus::Misconfigured, Some(message));
}
return;
}
Err(LaunchError::Failed(message)) => {
tracing::warn!("{}: {message}", server.name);
if server.finish_start(generation, Conn::Failed) {
@@ -1415,6 +1422,52 @@ impl LspManager {
out.finish(Vec::new())
}
/// The document's links; ones without a target are resolved when the server can.
pub async fn document_links(&self, doc: DocId) -> IdeResult<Vec<DocumentLink>> {
let (snap, targets) = self.doc_targets(doc, "document links", |c| c.has("documentLinkProvider")).await?;
let requests = targets.iter().map(|t| {
let params = json!({ "textDocument": snap.ident() });
async move {
let links = self
.call::<_, Option<Vec<lsp::DocumentLink>>>(
t,
"textDocument/documentLink",
params,
None,
DEFAULT_TIMEOUT,
)
.await?
.unwrap_or_default();
if !t.caps().has_sub("documentLinkProvider", "resolveProvider") {
return Ok::<_, IdeError>((t, links));
}
let resolved = join_all(links.into_iter().map(|l| async move {
if l.target.is_some() {
return l;
}
let original = l.clone();
self.call::<_, lsp::DocumentLink>(t, "documentLink/resolve", l, None, DEFAULT_TIMEOUT)
.await
.unwrap_or(original)
}))
.await;
Ok((t, resolved))
}
});
let mut out = Outcome::new();
for r in join_all(requests).await {
match r {
Ok((t, links)) => {
let conv = self.conv(t.enc());
let acc = out.value.get_or_insert_with(Vec::new);
acc.extend(links.into_iter().filter_map(|l| convert::document_link(&conv, &snap.path, l)));
}
Err(e) => out.fail(e),
}
}
out.finish(Vec::new())
}
pub async fn call_hierarchy(
&self,
doc: DocId,
@@ -1604,8 +1657,10 @@ impl LspManager {
s.reset_for_restart();
self.ensure_started(&s);
}
// Missing / crashed servers retry with the new configuration (e.g. a new PATH).
ide_core::event::ServerStatus::Missing | ide_core::event::ServerStatus::Crashed => {
// Missing / crashed / misconfigured servers retry with the new configuration (e.g. a new PATH).
ide_core::event::ServerStatus::Missing
| ide_core::event::ServerStatus::Crashed
| ide_core::event::ServerStatus::Misconfigured => {
s.reset_for_restart();
self.ensure_started(&s);
}
+15
Переглянути файл
@@ -214,6 +214,21 @@ pub struct CodeLens {
pub command: Option<Command>,
}
/// A link in a document (`textDocument/documentLink`): an HTML `href`, a
/// Markdown link, an `#include`, a JSON `$schema`…
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DocumentLink {
pub range: Range,
/// A `file:` target.
pub path: Option<ide_core::IpcPath>,
/// The `#fragment` of a `file:` target (`L12`, `L12,5`, a heading or element id).
pub fragment: Option<String>,
/// Any other target (`https:`, …).
pub url: Option<String>,
pub tooltip: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HierarchyDirection {
+6 -4
Переглянути файл
@@ -710,13 +710,15 @@ async fn launch_error_fails_without_starting_the_server() {
h.mgr.set_config_hook(Box::new(|cfg, _| cfg.launch_error = Some("needs JDK 21".into())));
assert!(!h.mgr.serves_path(&h.root.join("a.mk")), "batch inspection skips it");
h.open("a.mk", "x");
h.wait_status("mock", ServerStatus::Crashed).await;
// Not a crash: nothing ran, the configuration has to change.
h.wait_status("mock", ServerStatus::Misconfigured).await;
assert_eq!(h.launcher.state("mock").launches.load(Ordering::SeqCst), 0);
let crashed = h.events.lock().iter().find_map(|e| match e {
IdeEvent::LanguageServer { status: ServerStatus::Crashed, message, .. } => message.clone(),
let reason = h.events.lock().iter().find_map(|e| match e {
IdeEvent::LanguageServer { status: ServerStatus::Misconfigured, message, .. } => message.clone(),
_ => None,
});
assert_eq!(crashed.as_deref(), Some("needs JDK 21"));
assert_eq!(reason.as_deref(), Some("needs JDK 21"));
assert!(!h.statuses("mock").contains(&ServerStatus::Crashed));
}
#[tokio::test(flavor = "multi_thread")]
+1 -1
Переглянути файл
@@ -124,7 +124,7 @@ async fn rust_analyzer_end_to_end() {
mgr.did_open(doc, &main, &LanguageId::new("rust"), 1, MAIN_RS);
retry("rust-analyzer ready", Duration::from_secs(60), || {
let s = last_status(&events, "rust-analyzer");
if let Some((ServerStatus::Crashed | ServerStatus::Missing, msg)) = &s {
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &s {
panic!("rust-analyzer failed: {msg:?}");
}
async move { matches!(s, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
+1 -1
Переглянути файл
@@ -161,7 +161,7 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
if !data.is_file() {
return Err(nothing_recorded("perf wrote no data"));
}
let out = Command::new(perf)
let out = ide_core::process::no_window(&mut Command::new(perf))
.args(["script", "-i"])
.arg(data.as_ref() as &Path)
.current_dir(cwd)
+1
Переглянути файл
@@ -232,6 +232,7 @@ mod tests {
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
+7
Переглянути файл
@@ -11,6 +11,7 @@
//! env = { RUST_LOG = "debug" }
//! is-test = false
//! debug-adapter = "codelldb"
//! allow-parallel = true
//! ```
use crate::RunConfig;
@@ -51,6 +52,8 @@ struct FileConfig {
is_test: bool,
#[serde(alias = "debugAdapter", alias = "debug_adapter")]
debug_adapter: Option<String>,
#[serde(default, alias = "allowParallel", alias = "allow_parallel")]
allow_parallel: bool,
}
fn slug(s: &str) -> String {
@@ -91,6 +94,7 @@ pub(crate) fn load(root: &Path) -> IdeResult<Vec<RunConfig>> {
detected: false,
is_test: c.is_test,
debug_adapter: c.debug_adapter.filter(|d| !d.is_empty()),
allow_parallel: c.allow_parallel,
});
}
Ok(out)
@@ -121,6 +125,9 @@ fn to_table(c: &RunConfig) -> Table {
if let Some(adapter) = &c.debug_adapter {
t.insert("debug-adapter", value(adapter));
}
if c.allow_parallel {
t.insert("allow-parallel", value(true));
}
t
}
+1
Переглянути файл
@@ -37,6 +37,7 @@ fn config(id: impl Into<String>, name: impl Into<String>, kind: &str, command: &
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
+4
Переглянути файл
@@ -34,6 +34,10 @@ pub struct RunConfig {
pub is_test: bool,
/// DAP adapter that can debug this config, if any.
pub debug_adapter: Option<String>,
/// "Allow multiple instances": Run on a running config starts another one instead of restarting it.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
#[specta(optional)]
pub allow_parallel: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
+2 -3
Переглянути файл
@@ -205,8 +205,7 @@ impl ProcessManager {
{
use std::os::windows::process::CommandExt;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | ide_core::process::CREATE_NO_WINDOW);
}
let mut child = cmd.spawn().map_err(|e| match e.kind() {
@@ -400,7 +399,7 @@ fn kill_tree(pid: u32, _force: bool) {
// Console children have no reliable graceful signal from outside their console.
let _ = Command::new("taskkill")
.args(["/T", "/F", "/PID", &pid.to_string()])
.creation_flags(0x0800_0000)
.creation_flags(ide_core::process::CREATE_NO_WINDOW)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
+2 -1
Переглянути файл
@@ -93,7 +93,7 @@ pub fn find_tool(name: &str, config: &RunConfig, dir: &Path, root: &Path) -> Opt
pub fn probe(argv: &[String], dir: &Path, config: &RunConfig) -> bool {
let Some((program, args)) = argv.split_first() else { return false };
let program = resolve(program, config);
Command::new(program)
ide_core::process::no_window(&mut Command::new(program))
.args(args)
.current_dir(dir)
.envs(&config.env)
@@ -260,6 +260,7 @@ mod tests {
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
+2
Переглянути файл
@@ -16,6 +16,7 @@ fn sample() -> Vec<RunConfig> {
detected: false,
is_test: false,
debug_adapter: Some("codelldb".into()),
allow_parallel: true,
},
RunConfig {
id: "user:tests".into(),
@@ -28,6 +29,7 @@ fn sample() -> Vec<RunConfig> {
detected: false,
is_test: true,
debug_adapter: None,
allow_parallel: false,
},
]
}
+1
Переглянути файл
@@ -42,6 +42,7 @@ fn cfg(id: &str, command: &str, args: &[&str]) -> RunConfig {
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
+95 -2
Переглянути файл
@@ -16,7 +16,7 @@ fn non_empty(s: &str) -> Option<&str> {
}
/// Resolves `~/` and project-relative paths of a setting.
fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
pub fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
let s = non_empty(s)?;
let p = match s.strip_prefix("~/") {
Some(rest) => crate::home_dir()?.join(rest),
@@ -56,6 +56,71 @@ fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
setting_path(root, &s.languages.go.goroot)
}
/// A JDK setting: a JDK home, its `bin` or its `bin/java`.
fn jdk_setting(root: &Path, value: &str) -> Option<Result<crate::java::Jdk, PathBuf>> {
let p = setting_path(root, value)?;
Some(p.ancestors().take(3).find_map(crate::java::jdk_at).ok_or(p))
}
/// The project JDK (`languages.java.jdk`).
pub fn project_jdk(root: &Path, s: &Settings) -> Option<crate::java::Jdk> {
jdk_setting(root, &s.languages.java.jdk)?
.inspect_err(|p| tracing::warn!("project JDK {} is not a JDK home", p.display()))
.ok()
}
/// The JDK chosen to run jdtls (`languages.java.jdtlsJdk`): `Ok(None)` when not
/// set, `Err` (the message) when it is not a JDK home.
pub fn jdtls_jdk(root: &Path, s: &Settings) -> Result<Option<crate::java::Jdk>, String> {
match jdk_setting(root, &s.languages.java.jdtls_jdk) {
None => Ok(None),
Some(Ok(jdk)) => Ok(Some(jdk)),
Some(Err(p)) => Err(format!(
"The language server JDK {} is not a JDK home (Settings › Languages & Frameworks › Java).",
p.display()
)),
}
}
/// `mvn` of the configured Maven home (`languages.java.maven.home`): the
/// executable itself, `<home>/bin/mvn` or `<bin>/mvn`.
pub fn maven_command(root: &Path, s: &Settings) -> Option<PathBuf> {
let p = setting_path(root, &s.languages.java.maven.home)?;
let name = if cfg!(windows) { "mvn.cmd" } else { "mvn" };
let found = [p.clone(), p.join("bin").join(name), p.join(name)].into_iter().find(|c| c.is_file());
if found.is_none() {
tracing::warn!("Maven home {} has no {name}", p.display());
}
found
}
/// Maven options from settings, placed before the goals: `-s <settings.xml>`
/// and `-Dmaven.repo.local=<dir>`.
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
let m = &s.languages.java.maven;
let mut out = Vec::new();
if let Some(file) = setting_path(root, &m.user_settings) {
out.extend(["-s".to_owned(), file.to_string_lossy().into_owned()]);
}
if let Some(dir) = setting_path(root, &m.local_repository) {
out.push(format!("-Dmaven.repo.local={}", dir.to_string_lossy()));
}
out
}
/// The Maven local repository from settings: the configured one, else
/// `<localRepository>` of the configured user `settings.xml`; `None` = Maven's default.
pub fn maven_local_repository(root: &Path, s: &Settings) -> Option<PathBuf> {
let m = &s.languages.java.maven;
setting_path(root, &m.local_repository).or_else(|| {
let text = std::fs::read_to_string(setting_path(root, &m.user_settings)?).ok()?;
let repo = crate::java::xml_value(&crate::lombok::strip_xml_comments(&text), "localRepository")?;
let home = crate::home_dir().map(|h| h.to_string_lossy().into_owned()).unwrap_or_default();
let repo = repo.replace("${user.home}", &home);
(!repo.is_empty() && !repo.contains("${")).then(|| PathBuf::from(repo))
})
}
/// TypeScript `lib` directory for the selected version; `None` = the server's bundled one.
pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
match s.languages.typescript.version.trim() {
@@ -104,6 +169,9 @@ pub(crate) fn merge_init_options(cfg: &mut LanguageServerConfig, layer: Value) {
/// server settings (`python.pythonPath`, rust-analyzer `check.command`, `typescript.tsdk`).
/// `root` is the project root, `server_root` the server's workspace root.
pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
if let Some(custom) = s.tool_path(&cfg.command).and_then(|p| setting_path(root, p)) {
cfg.command = custom.to_string_lossy().into_owned();
}
let mut path_dirs: Vec<PathBuf> = Vec::new();
let name = cfg.name.clone();
let name = name.as_str();
@@ -170,6 +238,14 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
// The jdtls launcher forwards `--jvm-arg=` values to the JVM it starts.
let args = s.languages.java.jdtls_vm_args.split_whitespace().map(|a| format!("--jvm-arg={a}"));
cfg.args.extend(args);
// m2e (the Maven import) reads mirrors, servers and `<localRepository>` from it.
if let Some(file) = setting_path(root, &s.languages.java.maven.user_settings) {
let file = file.to_string_lossy();
merge_init_options(
cfg,
json!({ "settings": { "java": { "configuration": { "maven": { "userSettings": file } } } } }),
);
}
}
if let Some(lib) = tsdk(server_root, s).or_else(|| tsdk(root, s)) {
@@ -206,7 +282,8 @@ const PY_RUNNERS: [&str; 3] = ["uv", "poetry", "pdm"];
/// Points run configurations at the selected toolchains: Python configs use the
/// project interpreter, npm scripts the chosen package manager and Node.js,
/// cargo / go configs the selected toolchain.
/// cargo / go configs the selected toolchain, Maven / Gradle the project JDK
/// (and Maven the configured home and options).
pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings) {
let explicit_python = setting_path(root, &s.languages.python.interpreter);
let python = python_interpreter(root, s);
@@ -215,6 +292,9 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
let rust = rust_bin(root, s);
let go = goroot(root, s);
let gopath = setting_path(root, &s.languages.go.gopath);
let jdk = project_jdk(root, s);
let mvn = maven_command(root, s);
let mvn_options = maven_options(root, s);
for c in configs.iter_mut() {
let mut path_dirs: Vec<PathBuf> = Vec::new();
@@ -281,6 +361,19 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
c.env.entry("GOPATH".into()).or_insert_with(|| gopath.to_string_lossy().into_owned());
}
}
"maven" | "gradle" => {
if let Some(jdk) = &jdk {
c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());
}
if c.kind == "maven" && c.detected {
if let Some(mvn) = &mvn {
c.command = mvn.to_string_lossy().into_owned();
}
if !c.args.starts_with(&mvn_options) {
c.args.splice(0..0, mvn_options.iter().cloned());
}
}
}
_ => {}
}
if !path_dirs.is_empty() && !c.env.contains_key("PATH") {
+107
Переглянути файл
@@ -18,6 +18,8 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::Rust => rust(),
SdkKind::Go => go(),
SdkKind::TypeScript => typescript(root),
SdkKind::Jdk => jdk(),
SdkKind::Maven => maven(),
}
}
@@ -382,3 +384,108 @@ fn typescript(root: Option<&Path>) -> Vec<Sdk> {
}
out
}
// ------------------------------------------------------------------ jdk
/// `KEY="value"` of a JDK `release` file.
fn release_value(release: &str, key: &str) -> Option<String> {
let line = release.lines().find_map(|l| l.trim().strip_prefix(key)?.strip_prefix('='))?;
Some(line.trim().trim_matches('"').to_owned()).filter(|v| !v.is_empty())
}
fn jdk() -> Vec<Sdk> {
let java_home = std::env::var_os("JAVA_HOME").and_then(|h| dunce::canonicalize(h).ok());
crate::java::rescan_jdks()
.iter()
.map(|j| {
let release = std::fs::read_to_string(j.home.join("release")).unwrap_or_default();
let version = release_value(&release, "JAVA_VERSION").unwrap_or_else(|| j.major.to_string());
let name = match release_value(&release, "IMPLEMENTOR") {
Some(vendor) => format!("{vendor} {version}"),
None => format!("JDK {version}"),
};
let source = if java_home.as_ref() == Some(&j.home) { "JAVA_HOME" } else { "system" };
Sdk {
path: j.home.clone().into(),
name,
version: Some(version),
source: source.to_owned(),
home: Some(j.home.clone().into()),
extra: None,
}
})
.collect()
}
// ------------------------------------------------------------------ maven
/// Maven version from `lib/maven-core-<version>.jar`.
fn maven_version(home: &Path) -> Option<String> {
std::fs::read_dir(home.join("lib")).ok()?.flatten().find_map(|e| {
let name = e.file_name().to_string_lossy().into_owned();
Some(name.strip_prefix("maven-core-")?.strip_suffix(".jar")?.to_owned())
})
}
/// A Maven home (`bin/mvn` and `lib/`); Homebrew's formula keeps it in `libexec`.
fn maven_home(dir: &Path) -> Option<PathBuf> {
let mvn = if cfg!(windows) { "mvn.cmd" } else { "mvn" };
[dir.join("libexec"), dir.to_path_buf()]
.into_iter()
.find(|h| h.join("bin").join(mvn).is_file() && h.join("lib").is_dir())
}
fn maven() -> Vec<Sdk> {
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
// Windows' Maven ships `mvn.cmd` only (`which` looks for `mvn.exe`).
let on_path = if cfg!(windows) {
std::env::split_paths(&search_path()).map(|d| d.join("mvn.cmd")).find(|p| p.is_file())
} else {
which("mvn")
};
if let Some(mvn) = on_path.and_then(|p| dunce::canonicalize(p).ok())
&& let Some(home) = mvn.parent().and_then(Path::parent)
{
found.push((home.to_path_buf(), "path"));
}
for var in ["MAVEN_HOME", "M2_HOME"] {
if let Some(h) = std::env::var_os(var) {
found.push((PathBuf::from(h), "env"));
}
}
for p in ["/opt/homebrew/opt/maven", "/usr/local/opt/maven", "/usr/share/maven", "/opt/maven"] {
found.push((PathBuf::from(p), "system"));
}
if let Some(home) = home_dir() {
for d in subdirs(&home.join(".sdkman/candidates/maven")) {
found.push((d, "sdkman"));
}
// Distributions the Maven wrapper downloaded: `dists/apache-maven-3.9.6-bin/<hash>/apache-maven-3.9.6`,
// or since wrapper 3.3 the home itself, `dists/apache-maven-3.9.6/<hash>`.
for dist in subdirs(&home.join(".m2/wrapper/dists")) {
for hash in subdirs(&dist) {
found.extend(subdirs(&hash).into_iter().map(|d| (d, "wrapper")));
found.push((hash, "wrapper"));
}
}
}
let mut seen = HashSet::new();
let mut out = Vec::new();
for (dir, source) in found {
let Some(home) = maven_home(&dir) else { continue };
let home = dunce::canonicalize(&home).unwrap_or(home);
if !seen.insert(home.clone()) {
continue;
}
let version = maven_version(&home);
out.push(Sdk {
path: home.clone().into(),
name: format!("Maven {}", version.clone().unwrap_or_default()).trim().to_owned(),
version,
source: source.to_owned(),
home: Some(home.into()),
extra: None,
});
}
out
}
+2 -1
Переглянути файл
@@ -44,7 +44,7 @@ pub(crate) fn which(name: &str) -> Option<PathBuf> {
/// Runs `program args` and returns trimmed stdout (stderr when stdout is empty)
/// on success; `None` on failure or after `timeout`.
pub(crate) fn query(program: &Path, args: &[&str], timeout: Duration) -> Option<String> {
let mut child = Command::new(program)
let mut child = ide_core::process::no_window(&mut Command::new(program))
.args(args)
.env("PATH", search_path())
.stdin(Stdio::null())
@@ -96,6 +96,7 @@ pub(crate) fn stream(
on_line: &dyn Fn(String),
) -> IdeResult<String> {
let mut cmd = Command::new(program);
ide_core::process::no_window(&mut cmd);
cmd.args(args).env("PATH", search_path()).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
cmd.envs(env.iter().map(|(k, v)| (k, v)));
if let Some(cwd) = cwd {
+151 -18
Переглянути файл
@@ -25,7 +25,8 @@ pub fn parse_release(release: &str) -> Option<u32> {
if first == 1 { parts.next()?.parse().ok() } else { Some(first) }
}
fn jdk_at(home: &Path) -> Option<Jdk> {
/// The JDK at `home`, if it is one (a `release` file and `bin/java`).
pub fn jdk_at(home: &Path) -> Option<Jdk> {
let release = std::fs::read_to_string(home.join("release")).ok()?;
if !home.join("bin").join(crate::exe("java")).is_file() {
return None;
@@ -117,6 +118,11 @@ fn rescan(slot: &mut Option<Scan>) -> Arc<[Jdk]> {
slot.insert(Scan { at: Instant::now(), jdks: scan().into() }).jdks.clone()
}
/// Scans for installed JDKs again (Settings › Detect again).
pub fn rescan_jdks() -> Arc<[Jdk]> {
rescan(&mut JDKS.lock().unwrap_or_else(|e| e.into_inner()))
}
/// Installed JDKs (scanned on first use; [`jdtls_jdks`] may refresh them).
pub fn installed_jdks() -> Arc<[Jdk]> {
let mut slot = JDKS.lock().unwrap_or_else(|e| e.into_inner());
@@ -258,12 +264,17 @@ const METADATA_PROPERTY: &str = "java.import.generatesMetadataFilesAtProjectRoot
/// directory, one per server root, and no Eclipse metadata is written into
/// the project; it runs on a JDK `min_java`+ (via `JAVA_HOME`, which its
/// launcher reads), installed JDKs are registered as runtimes and `bundles`
/// (e.g. the java-debug plugin jar) are loaded into the server.
/// (e.g. the java-debug plugin jar) are loaded into the server. The project
/// JDK, when set, is the default runtime and preferred for running the server;
/// `server_jdk` (the user's choice for the server alone) overrides that.
#[allow(clippy::too_many_arguments)]
pub fn configure_jdtls(
cfg: &mut LanguageServerConfig,
server_root: &Path,
data_dir: &Path,
jdks: &[Jdk],
project_jdk: Option<&Jdk>,
server_jdk: Option<&Jdk>,
min_java: u32,
bundles: &[PathBuf],
lombok: Option<&Path>,
@@ -294,15 +305,35 @@ pub fn configure_jdtls(
{
cfg.args.push(format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy()));
}
let mut all: Vec<Jdk> = Vec::new();
for j in project_jdk.into_iter().chain(jdks).chain(server_jdk) {
if !all.contains(j) {
all.push(j.clone());
}
}
let jdks = all.as_slice();
if !cfg.env.contains_key("JAVA_HOME") {
match jdtls_runtime(jdks, min_java) {
Some(jdk) => {
let runtime = match server_jdk {
Some(jdk) if jdk.major < min_java => Err(server_jdk_too_old_message(jdk, min_java)),
Some(jdk) => Ok(jdk),
None => jdtls_runtime(jdks, min_java).ok_or_else(|| missing_runtime_message(jdks, min_java)),
};
match runtime {
Ok(jdk) => {
cfg.env.insert("JAVA_HOME".to_owned(), jdk.home.to_string_lossy().into_owned());
}
None => cfg.launch_error = Some(missing_runtime_message(jdks, min_java)),
Err(e) => cfg.launch_error = Some(e),
}
}
let mut runtimes = runtimes(jdks);
if let Some(project) = project_jdk {
let home = project.home.to_string_lossy();
for r in &mut runtimes {
if r["path"] == *home {
r["default"] = json!(true);
}
}
}
let runtimes = runtimes(jdks);
if !runtimes.is_empty() {
merge_init_options(cfg, json!({ "settings": { "java": { "configuration": { "runtimes": runtimes } } } }));
}
@@ -328,6 +359,15 @@ fn missing_runtime_message(jdks: &[Jdk], min_java: u32) -> String {
)
}
fn server_jdk_too_old_message(jdk: &Jdk, min_java: u32) -> String {
format!(
"The language server JDK ({}, JDK {}) is too old: jdtls needs JDK {min_java} or newer. Choose another \
one in Settings › Languages & Frameworks › Java, or set it to Auto.",
jdk.home.display(),
jdk.major
)
}
/// The `java` launcher of a JDK home.
pub fn java_executable(home: &Path) -> PathBuf {
home.join("bin").join(crate::exe("java"))
@@ -424,7 +464,17 @@ mod tests {
Jdk { major: 8, home: PathBuf::from("/jdk8") },
];
let bundles = [PathBuf::from("/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar")];
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, JDTLS_MIN_JAVA, &bundles, None);
configure_jdtls(
&mut cfg,
Path::new("/p/demo"),
Path::new("/data"),
&jdks,
None,
None,
JDTLS_MIN_JAVA,
&bundles,
None,
);
assert_eq!(cfg.args[0], "-data");
assert!(cfg.args[1].starts_with("/data/lsp/jdtls/"), "{}", cfg.args[1]);
assert_eq!(cfg.args[2], "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false");
@@ -439,11 +489,50 @@ mod tests {
// Deterministic (reconfigure compares configs) and idempotent.
let before = cfg.clone();
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, JDTLS_MIN_JAVA, &bundles, None);
configure_jdtls(
&mut cfg,
Path::new("/p/demo"),
Path::new("/data"),
&jdks,
None,
None,
JDTLS_MIN_JAVA,
&bundles,
None,
);
assert_eq!(cfg, before);
// The project JDK is the default runtime, and runs the server when new enough.
let project = Jdk { major: 21, home: PathBuf::from("/jdk21b") };
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
configure_jdtls(
&mut cfg,
Path::new("/p"),
Path::new("/data"),
&jdks,
Some(&project),
None,
JDTLS_MIN_JAVA,
&[],
None,
);
let opts = serde_json::to_value(cfg.initialization_options.clone().unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": "/jdk21b", "default": true }));
assert_eq!(cfg.env["JAVA_HOME"], "/jdk21b");
let mut other: LanguageServerConfig = toml::from_str("name = \"pyright\"\ncommand = \"x\"").unwrap();
configure_jdtls(&mut other, Path::new("/p"), Path::new("/data"), &jdks, JDTLS_MIN_JAVA, &bundles, None);
configure_jdtls(
&mut other,
Path::new("/p"),
Path::new("/data"),
&jdks,
None,
None,
JDTLS_MIN_JAVA,
&bundles,
None,
);
assert!(other.args.is_empty() && other.initialization_options.is_none());
}
@@ -452,23 +541,23 @@ mod tests {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let jar = Path::new("/m2/lombok-1.18.48.jar");
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], JDTLS_MIN_JAVA, &[], Some(jar));
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
let agent = format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy());
assert!(cfg.args.contains(&agent), "{:?}", cfg.args);
let mut plain = jdtls();
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
assert_ne!(cfg.args[1], plain.args[1], "a separate workspace, so everything is rebuilt with the agent");
let before = cfg.clone();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], JDTLS_MIN_JAVA, &[], Some(jar));
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
assert_eq!(cfg, before, "idempotent");
let mut cfg = jdtls();
cfg.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], JDTLS_MIN_JAVA, &[], Some(jar));
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
assert!(!cfg.args.contains(&agent), "the user's agent wins");
let mut own = jdtls();
own.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
configure_jdtls(&mut own, Path::new("/p"), Path::new("/data"), &[], JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut own, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
assert_eq!(cfg.args, own.args, "its workspace follows the agent in use");
}
@@ -477,19 +566,19 @@ mod tests {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let old = [Jdk { major: 17, home: PathBuf::from("/jdk17") }, Jdk { major: 8, home: PathBuf::from("/jdk8") }];
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, None, JDTLS_MIN_JAVA, &[], None);
assert!(!cfg.env.contains_key("JAVA_HOME"));
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 21 or newer") && err.contains("found JDK 8, 17"), "{err}");
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
assert!(cfg.launch_error.unwrap().contains("no JDK was found"));
// An explicit JAVA_HOME is the user's call.
let mut cfg = jdtls();
cfg.env.insert("JAVA_HOME".into(), "/custom".into());
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, None, JDTLS_MIN_JAVA, &[], None);
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/custom", None));
let mixed = [old[0].clone(), Jdk { major: 21, home: PathBuf::from("/jdk21") }];
@@ -497,11 +586,55 @@ mod tests {
// A jdtls whose bundles need 25 doesn't start on 21, and says what it needs.
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, 25, &[], None);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, None, None, 25, &[], None);
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 25 or newer") && err.contains("found JDK 17, 21"), "{err}");
}
#[test]
fn jdtls_runs_on_the_chosen_server_jdk() {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let jdk = |major: u32, home: &str| Jdk { major, home: PathBuf::from(home) };
let installed = [jdk(25, "/jdk25"), jdk(21, "/jdk21"), jdk(17, "/jdk17")];
let project = jdk(17, "/jdk17");
let run = |server: Option<&Jdk>, min_java: u32| {
let mut cfg = jdtls();
configure_jdtls(
&mut cfg,
Path::new("/p"),
Path::new("/data"),
&installed,
Some(&project),
server,
min_java,
&[],
None,
);
cfg
};
// Project on JDK 17, server on the chosen 21: each keeps its own JDK.
let cfg = run(Some(&jdk(21, "/jdk21")), JDTLS_MIN_JAVA);
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/jdk21", None));
let opts = serde_json::to_value(cfg.initialization_options.unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(rt[0], json!({ "name": "JavaSE-17", "path": "/jdk17", "default": true }), "still compiles on 17");
// Not set: the first installed JDK new enough, as before.
assert_eq!(run(None, JDTLS_MIN_JAVA).env["JAVA_HOME"], "/jdk25");
// A chosen JDK outside the scanned locations.
let own = jdk(25, "/opt/own-jdk");
let cfg = run(Some(&own), 25);
assert_eq!(cfg.env["JAVA_HOME"], "/opt/own-jdk");
// Too old for this jdtls: the user's choice is not overridden, it is explained.
let cfg = run(Some(&jdk(21, "/jdk21")), 25);
assert!(!cfg.env.contains_key("JAVA_HOME"));
let err = cfg.launch_error.unwrap();
assert!(err.contains("/jdk21") && err.contains("JDK 25 or newer"), "{err}");
}
#[test]
fn bundle_manifests_give_the_java_jdtls_needs() {
let ee = |m: &str| manifest_min_java(m);
+4
Переглянути файл
@@ -31,6 +31,10 @@ pub enum SdkKind {
Rust,
Go,
TypeScript,
/// JDK homes.
Jdk,
/// Maven homes.
Maven,
}
/// One installed interpreter / toolchain.
+12 -6
Переглянути файл
@@ -64,8 +64,14 @@ pub fn agent_in_args<'a>(args: impl IntoIterator<Item = &'a str>) -> Option<Path
}
/// The Lombok agent for the project at `root`: the user's own (`own`, from the JVM
/// options) wins, then `managed` (the IDE-installed jar), then the build caches.
pub fn lombok_agent(root: &Path, own: Option<PathBuf>, managed: Option<PathBuf>) -> LombokAgent {
/// options) wins, then `managed` (the IDE-installed jar), then the build caches
/// (`maven_repo`, the configured Maven local repository, else the default one).
pub fn lombok_agent(
root: &Path,
own: Option<PathBuf>,
managed: Option<PathBuf>,
maven_repo: Option<PathBuf>,
) -> LombokAgent {
if let Some(jar) = own {
let version = jar
.file_stem()
@@ -82,7 +88,7 @@ pub fn lombok_agent(root: &Path, own: Option<PathBuf>, managed: Option<PathBuf>)
}
let home = home_dir();
let mut dirs = Vec::new();
if let Some(repo) = maven_repository(home.as_deref()) {
if let Some(repo) = maven_repo.or_else(|| maven_repository(home.as_deref())) {
dirs.push(repo.join("org").join("projectlombok").join("lombok"));
}
if let Some(gradle) =
@@ -137,7 +143,7 @@ fn maven_repository(home: Option<&Path>) -> Option<PathBuf> {
Some(custom.unwrap_or_else(|| m2.join("repository")))
}
fn strip_xml_comments(text: &str) -> String {
pub(crate) fn strip_xml_comments(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(i) = rest.find("<!--") {
@@ -249,10 +255,10 @@ mod tests {
let own = agent_in_args(["--jvm-arg=-Xmx2g", "--jvm-arg=-javaagent:/opt/lombok-1.18.26.jar"]);
assert_eq!(own.as_deref(), Some(Path::new("/opt/lombok-1.18.26.jar")));
assert_eq!(agent_in_args(["-javaagent:/opt/other.jar"]), None);
let agent = lombok_agent(tmp.path(), own, Some("/managed/lombok.jar".into()));
let agent = lombok_agent(tmp.path(), own, Some("/managed/lombok.jar".into()), None);
assert_eq!(agent.jar(), Some(Path::new("/opt/lombok-1.18.26.jar")));
assert!(agent.outdated(), "its version is read from the file name");
let plain = lombok_agent(tmp.path(), agent_in_args(["-javaagent:/opt/lombok.jar"]), None);
let plain = lombok_agent(tmp.path(), agent_in_args(["-javaagent:/opt/lombok.jar"]), None, None);
assert_eq!(plain.problem(), None, "a user agent is never reported missing");
}
+85 -1
Переглянути файл
@@ -1,4 +1,7 @@
use crate::apply::{apply_to_run_configs, configure_server, python_interpreter, terminal_activation, tsdk};
use crate::apply::{
apply_to_run_configs, configure_server, jdtls_jdk, maven_command, maven_options, project_jdk, python_interpreter,
terminal_activation, tsdk,
};
use crate::python::parse_pip_list;
use crate::{bin_dir, exe, venv_of};
use ide_core::settings::Settings;
@@ -43,6 +46,7 @@ fn run(kind: &str, command: &str, args: &[&str]) -> RunConfig {
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
@@ -153,6 +157,71 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
assert_eq!(configs[4].command, "python3", "shell configs are left alone");
}
fn fake_jdk(dir: &Path) {
std::fs::create_dir_all(dir.join("bin")).unwrap();
std::fs::write(dir.join("bin").join(exe("java")), "").unwrap();
std::fs::write(dir.join("release"), "JAVA_VERSION=\"17.0.9\"\n").unwrap();
}
#[test]
fn project_jdk_and_maven_settings() {
if cfg!(windows) {
return; // Unix paths and shells
}
let tmp = tempfile::tempdir().unwrap();
let jdk = tmp.path().join("jdk17");
fake_jdk(&jdk);
let maven = tmp.path().join("maven");
std::fs::create_dir_all(maven.join("bin")).unwrap();
std::fs::write(maven.join("bin/mvn"), "").unwrap();
let mut s = Settings::default();
assert_eq!(project_jdk(tmp.path(), &s), None);
assert_eq!(maven_command(tmp.path(), &s), None);
assert!(maven_options(tmp.path(), &s).is_empty());
// Project-relative paths, a JDK's `bin/java`, a Maven home.
s.languages.java.jdk = "jdk17/bin/java".into();
s.languages.java.maven.home = maven.to_string_lossy().into_owned();
s.languages.java.maven.user_settings = "/m2/settings.xml".into();
s.languages.java.maven.local_repository = "/m2/repo".into();
assert_eq!(project_jdk(tmp.path(), &s).map(|j| j.major), Some(17));
assert_eq!(maven_command(tmp.path(), &s), Some(maven.join("bin/mvn")));
assert_eq!(maven_options(tmp.path(), &s), ["-s", "/m2/settings.xml", "-Dmaven.repo.local=/m2/repo"]);
let mut configs = vec![run("maven", "./mvnw", &["package"]), run("gradle", "./gradlew", &["build"])];
apply_to_run_configs(&mut configs, tmp.path(), &s);
let home = project_jdk(tmp.path(), &s).unwrap().home.to_string_lossy().into_owned();
assert_eq!(configs[0].command, maven.join("bin/mvn").to_string_lossy());
assert_eq!(configs[0].args, ["-s", "/m2/settings.xml", "-Dmaven.repo.local=/m2/repo", "package"]);
assert_eq!(configs[0].env["JAVA_HOME"], home);
assert_eq!(configs[1].env["JAVA_HOME"], home);
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(configs[0].args.len(), 4, "applied once");
s.languages.java.jdk = "missing".into();
assert_eq!(project_jdk(tmp.path(), &s), None);
}
#[test]
fn jdtls_jdk_setting() {
if cfg!(windows) {
return; // Unix paths
}
let tmp = tempfile::tempdir().unwrap();
fake_jdk(&tmp.path().join("jdk17"));
let mut s = Settings::default();
assert_eq!(jdtls_jdk(tmp.path(), &s), Ok(None));
// Separate from the project JDK, which run configurations keep using.
s.languages.java.jdk = "jdk17".into();
assert_eq!(jdtls_jdk(tmp.path(), &s), Ok(None));
s.languages.java.jdtls_jdk = "jdk17/bin".into();
assert_eq!(jdtls_jdk(tmp.path(), &s).unwrap().map(|j| j.major), Some(17));
// A chosen path that is not a JDK is an error, not a silent fallback.
s.languages.java.jdtls_jdk = "missing".into();
assert!(jdtls_jdk(tmp.path(), &s).unwrap_err().contains("is not a JDK home"));
}
#[test]
fn terminal_activation_for_project_venv() {
if cfg!(windows) {
@@ -206,3 +275,18 @@ fn detect_on_this_machine() {
}
}
}
#[test]
fn custom_tool_path_replaces_the_command() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Settings::default();
s.tools.insert("elixir-ls".into(), ide_core::settings::ToolSettings { path: "tools/ls/language_server.sh".into() });
s.tools.insert("zls".into(), ide_core::settings::ToolSettings { path: " ".into() });
let mut cfg = server("elixir-ls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(Path::new(&cfg.command), tmp.path().join("tools/ls/language_server.sh"));
// A blank path keeps auto-detection.
let mut cfg = server("zls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(cfg.command, "zls");
}
+188 -3
Переглянути файл
@@ -32,7 +32,7 @@ const KILL_GRACE: Duration = Duration::from_millis(1500);
#[serde(rename_all = "camelCase")]
pub struct TerminalOptions {
pub cwd: ide_core::IpcPath,
/// Defaults to the user's login shell (`$SHELL`, or `COMSPEC` on Windows).
/// Defaults to the user's login shell (passwd entry, then `$SHELL`; PowerShell or `COMSPEC` on Windows).
pub shell: Option<String>,
pub args: Vec<String>,
pub env: BTreeMap<String, String>,
@@ -160,6 +160,19 @@ impl TerminalManager {
Ok(())
}
/// Whether the shell is running a command, so closing its tab should ask first
/// (as IDEA does). On Unix: the PTY's foreground process
/// group isn't the shell's, i.e. a job is in the foreground (background helpers
/// such as prompt daemons don't count). On Windows: the shell has child processes.
pub fn is_busy(&self, id: TerminalId) -> IdeResult<bool> {
let session = self.session(id)?;
if session.exited.load(Ordering::Acquire) {
return Ok(false);
}
let Some(pid) = session.info.pid else { return Ok(false) };
Ok(foreground_busy(&session, pid))
}
pub fn list(&self) -> Vec<TerminalInfo> {
let mut out: Vec<TerminalInfo> = self.sessions.lock().values().map(|s| s.info.clone()).collect();
out.sort_by_key(|i| i.id);
@@ -191,6 +204,76 @@ fn not_found(id: TerminalId) -> IdeError {
IdeError::not_found(format!("no such terminal: {id}"))
}
#[cfg(unix)]
fn foreground_busy(session: &Session, pid: u32) -> bool {
let leader = session.master.lock().process_group_leader();
leader.is_some_and(|fg| u32::try_from(fg).ok() != Some(pid))
}
#[cfg(windows)]
fn foreground_busy(_session: &Session, pid: u32) -> bool {
win::has_child_processes(pid)
}
#[cfg(not(any(unix, windows)))]
fn foreground_busy(_session: &Session, _pid: u32) -> bool {
false
}
#[cfg(windows)]
mod win {
use std::ffi::c_void;
const TH32CS_SNAPPROCESS: u32 = 0x2;
const INVALID_HANDLE_VALUE: isize = -1;
/// `PROCESSENTRY32W` from `<tlhelp32.h>`.
#[repr(C)]
struct ProcessEntry32W {
dw_size: u32,
cnt_usage: u32,
th32_process_id: u32,
th32_default_heap_id: usize,
th32_module_id: u32,
cnt_threads: u32,
th32_parent_process_id: u32,
pc_pri_class_base: i32,
dw_flags: u32,
sz_exe_file: [u16; 260],
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn CreateToolhelp32Snapshot(flags: u32, pid: u32) -> *mut c_void;
fn Process32FirstW(snapshot: *mut c_void, entry: *mut ProcessEntry32W) -> i32;
fn Process32NextW(snapshot: *mut c_void, entry: *mut ProcessEntry32W) -> i32;
fn CloseHandle(handle: *mut c_void) -> i32;
}
pub fn has_child_processes(pid: u32) -> bool {
// SAFETY: plain Win32 calls on a locally owned snapshot handle and entry buffer.
unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if snapshot.is_null() || snapshot as isize == INVALID_HANDLE_VALUE {
return false;
}
let mut entry: ProcessEntry32W = std::mem::zeroed();
entry.dw_size = std::mem::size_of::<ProcessEntry32W>() as u32;
let mut found = false;
let mut ok = Process32FirstW(snapshot, &mut entry);
while ok != 0 {
if entry.th32_parent_process_id == pid && entry.th32_process_id != pid {
found = true;
break;
}
ok = Process32NextW(snapshot, &mut entry);
}
CloseHandle(snapshot);
found
}
}
}
/// Hangs up the shell (and its process group), escalating to SIGKILL if it lingers.
fn terminate(session: &Session) {
if session.exited.load(Ordering::Acquire) {
@@ -359,6 +442,48 @@ pub fn default_shell_path() -> String {
default_shell()
}
/// Installed shells for "New Predefined Session", the login shell first. On
/// Unix: `/etc/shells` plus `$PATH`, so Homebrew shells show up too.
pub fn available_shells() -> Vec<String> {
let mut found: Vec<PathBuf> = Vec::new();
let mut add = |p: PathBuf| {
let key = p.canonicalize().unwrap_or_else(|_| p.clone());
if p.is_file() && !found.iter().any(|f| f.canonicalize().unwrap_or_else(|_| f.clone()) == key) {
found.push(p);
}
};
add(PathBuf::from(default_shell()));
#[cfg(unix)]
{
const NAMES: [&str; 5] = ["zsh", "bash", "fish", "nu", "pwsh"];
let listed = std::fs::read_to_string("/etc/shells").unwrap_or_default();
for name in NAMES {
for line in listed.lines().map(str::trim).filter(|l| l.starts_with('/')) {
if shell_title(line) == name {
add(PathBuf::from(line));
}
}
if let Some(p) = find_in_path(name) {
add(p);
}
}
}
#[cfg(windows)]
{
for exe in ["pwsh.exe", "powershell.exe", "cmd.exe", "wsl.exe"] {
if let Some(p) = find_in_path(exe) {
add(p);
}
}
for var in ["ProgramFiles", "ProgramW6432"] {
if let Some(dir) = std::env::var_os(var) {
add(PathBuf::from(dir).join("Git").join("bin").join("bash.exe"));
}
}
}
found.into_iter().map(|p| p.to_string_lossy().into_owned()).collect()
}
/// Picks the shell binary and its arguments. A default (or explicitly chosen but
/// argument-less) POSIX shell is started as a login shell, like Terminal.app/IDEA.
fn resolve_shell(shell: Option<&str>, args: &[String]) -> (String, Vec<String>) {
@@ -372,14 +497,34 @@ fn resolve_shell(shell: Option<&str>, args: &[String]) -> (String, Vec<String>)
(shell, args)
}
/// The account's login shell comes first: `$SHELL` is inherited from whatever
/// launched the app (a terminal running another shell, `tauri dev`), so it may
/// not be the shell the user picked.
#[cfg(unix)]
fn default_shell() -> String {
if let Some(shell) = std::env::var("SHELL").ok().filter(|s| !s.is_empty() && Path::new(s).exists()) {
let usable = |s: &String| !s.is_empty() && Path::new(s).exists();
if let Some(shell) = login_shell().filter(usable).or_else(|| std::env::var("SHELL").ok().filter(usable)) {
return shell;
}
["/bin/zsh", "/bin/bash", "/bin/sh"].into_iter().find(|p| Path::new(p).exists()).unwrap_or("/bin/sh").to_owned()
}
/// `pw_shell` of the current user's passwd entry.
#[cfg(unix)]
fn login_shell() -> Option<String> {
let mut buf = vec![0 as libc::c_char; 4096];
let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
let mut result: *mut libc::passwd = std::ptr::null_mut();
// SAFETY: every pointer refers to a live local buffer of the stated size.
let rc = unsafe { libc::getpwuid_r(libc::getuid(), &mut pwd, buf.as_mut_ptr(), buf.len(), &mut result) };
if rc != 0 || result.is_null() || pwd.pw_shell.is_null() {
return None;
}
// SAFETY: on success `pw_shell` is a NUL-terminated string inside `buf`.
let shell = unsafe { std::ffi::CStr::from_ptr(pwd.pw_shell) };
Some(shell.to_string_lossy().into_owned())
}
#[cfg(windows)]
fn default_shell() -> String {
for candidate in ["pwsh.exe", "powershell.exe"] {
@@ -390,7 +535,6 @@ fn default_shell() -> String {
std::env::var("COMSPEC").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| "cmd.exe".to_owned())
}
#[cfg(windows)]
fn find_in_path(exe: &str) -> Option<PathBuf> {
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path).map(|dir| dir.join(exe)).find(|p| p.is_file())
@@ -421,6 +565,22 @@ fn terminal_env(user: &BTreeMap<String, String>) -> BTreeMap<String, String> {
#[cfg(all(test, unix))]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn login_shell_reads_the_passwd_entry() {
let shell = login_shell().expect("passwd entry");
assert!(shell.starts_with('/'), "{shell}");
}
#[cfg(unix)]
#[test]
fn available_shells_start_with_the_default_and_are_distinct() {
let shells = available_shells();
assert_eq!(shells.first(), Some(&default_shell_path()));
let unique: std::collections::HashSet<_> = shells.iter().collect();
assert_eq!(unique.len(), shells.len());
}
use std::sync::mpsc::Receiver;
struct Harness {
@@ -573,6 +733,31 @@ mod tests {
assert!(h.manager.kill(info.id).is_err());
}
#[test]
fn busy_while_a_command_runs_in_the_foreground() {
let h = harness();
let mut opts = sh("");
opts.args = vec!["-i".into()];
opts.env.insert("PS1".into(), "$ ".into());
opts.env.insert("ENV".into(), "/dev/null".into());
let (info, _rx) = spawn_collect(&h, opts);
let wait_for = |want: bool| {
let deadline = Instant::now() + Duration::from_secs(10);
while h.manager.is_busy(info.id).unwrap() != want {
assert!(Instant::now() < deadline, "is_busy never became {want}");
std::thread::sleep(Duration::from_millis(20));
}
};
wait_for(false);
h.manager.write(info.id, "sleep 30\n").unwrap();
wait_for(true);
h.manager.write(info.id, "\u{3}").unwrap();
wait_for(false);
h.manager.write(info.id, "exit\n").unwrap();
let _ = wait_exit(&h, info.id);
assert!(h.manager.is_busy(info.id).is_err());
}
#[test]
fn large_output_is_batched_and_complete() {
let h = harness();
+22 -1
Переглянути файл
@@ -113,7 +113,7 @@ fn extract_zip(archive: &Path, dest: &Path) -> IdeResult<()> {
/// `.tar.xz` goes through the system `tar` (bsdtar on macOS/Windows, GNU tar + xz on Linux).
fn extract_tar_xz(archive: &Path, dest: &Path) -> IdeResult<()> {
let tar = which::which("tar").map_err(|_| IdeError::unavailable("`tar` is required to unpack .tar.xz archives"))?;
let out = std::process::Command::new(tar)
let out = ide_core::process::no_window(&mut std::process::Command::new(tar))
.arg("-xJf")
.arg(archive)
.arg("-C")
@@ -177,6 +177,27 @@ pub fn locate(root: &Path, names: &[String]) -> Option<PathBuf> {
/// Creates `bin_dir/<command>` that runs `target`: a shell wrapper on Unix
/// (keeps the target's own directory layout intact), a `.cmd` shim on Windows.
/// Like [`link_executable`], with `env` set for `target`.
pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &Path)]) -> IdeResult<PathBuf> {
fs::create_dir_all(bin_dir)?;
#[cfg(unix)]
{
let quote = |p: &Path| format!("'{}'", p.to_string_lossy().replace('\'', r"'\''"));
let vars: String = env.iter().map(|(k, v)| format!("{k}={} ", quote(v))).collect();
let link = bin_dir.join(command);
fs::write(&link, format!("#!/bin/sh\n{vars}exec {} \"$@\"\n", quote(target)))?;
make_executable(&link)?;
Ok(link)
}
#[cfg(not(unix))]
{
let link = bin_dir.join(format!("{command}.cmd"));
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", v.display())).collect();
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", target.display()))?;
Ok(link)
}
}
pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResult<PathBuf> {
fs::create_dir_all(bin_dir)?;
#[cfg(unix)]
+163 -6
Переглянути файл
@@ -39,6 +39,8 @@ pub enum ToolStatus {
Installed,
/// Found on the system `PATH`.
OnPath,
/// The executable chosen in settings.
Custom,
Missing,
}
@@ -66,6 +68,8 @@ pub struct ToolInfo {
/// Manual install instructions from the language definition.
pub install_hint: Option<String>,
pub homepage: Option<String>,
/// Why the executable chosen in settings cannot be used (status is then `Missing`).
pub custom_error: Option<String>,
}
/// Streamed install progress.
@@ -116,7 +120,9 @@ fn bin_dirs_in(root: &Path, platform: Platform) -> Vec<PathBuf> {
fn managed_bin_dir(root: &Path, spec: &ToolSpec, platform: Platform) -> Option<PathBuf> {
match spec.method {
Method::Npm { .. } => Some(root.join("node_modules").join(".bin")),
Method::Go { .. } | Method::Release { .. } => Some(root.join(spec.name).join("bin")),
Method::Go { .. } | Method::Gem { .. } | Method::DotnetTool { .. } | Method::Release { .. } => {
Some(root.join(spec.name).join("bin"))
}
Method::PipVenv { .. } => {
Some(root.join(spec.name).join("venv").join(if platform.os == Os::Windows { "Scripts" } else { "bin" }))
}
@@ -212,8 +218,15 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
for s in &l.language_servers {
add(&s.name, &s.command, ToolKind::LanguageServer, s.install_hint.as_ref(), &l.name);
}
}
let servers: HashSet<&str> = langs.iter().flat_map(|l| &l.language_servers).map(|s| s.name.as_str()).collect();
for l in langs {
if let Some(d) = &l.debugger {
add(&d.adapter, &d.command, ToolKind::Debugger, d.install_hint.as_ref(), &l.name);
// An adapter named like a server but launched differently (ElixirLS's
// `elixir-ls-debugger`) is a tool of its own, listed by its command.
let name =
if servers.contains(d.adapter.as_str()) && d.command != d.adapter { &d.command } else { &d.adapter };
add(name, &d.command, ToolKind::Debugger, d.install_hint.as_ref(), &l.name);
}
}
for (plugin, host) in registry::PLUGIN_HOSTS {
@@ -260,6 +273,8 @@ pub struct Tools {
/// `PATH` handed to installer child processes.
child_path: OsString,
platform: Platform,
/// Executables chosen in settings, by command.
custom: BTreeMap<String, PathBuf>,
}
impl Tools {
@@ -273,7 +288,13 @@ impl Tools {
let system: Vec<PathBuf> = std::env::split_paths(&search_path).filter(|d| !ours.contains(d)).collect();
let system_path = std::env::join_paths(&system).unwrap_or_default();
let child_path = std::env::join_paths(ours.iter().chain(system.iter())).unwrap_or_default();
Self { root, system_path, child_path, platform }
Self { root, system_path, child_path, platform, custom: BTreeMap::new() }
}
/// Reports the executables chosen in settings (command → path) as the tools' location.
pub fn with_custom_paths(mut self, custom: BTreeMap<String, PathBuf>) -> Self {
self.custom = custom;
self
}
pub fn root(&self) -> &Path {
@@ -290,7 +311,7 @@ impl Tools {
fn command(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
let mut cmd = Command::new(program);
cmd.env("PATH", &self.child_path);
ide_core::process::no_window(&mut cmd).env("PATH", &self.child_path);
cmd
}
@@ -343,6 +364,12 @@ impl Tools {
/// Requirement check for installing `spec` right now.
fn unavailable_reason(&self, spec: &ToolSpec) -> Option<String> {
self.installer_missing(spec)
.or_else(|| spec.needs.iter().find(|(cmd, _)| self.which(cmd).is_none()).map(|(_, why)| why.to_string()))
}
/// What the install method itself lacks (npm, a build for this platform, …).
fn installer_missing(&self, spec: &ToolSpec) -> Option<String> {
let need = |ok: bool, msg: &str| (!ok).then(|| msg.to_string());
match spec.method {
Method::Rustup { .. } => need(self.which("rustup").is_some(), "rustup is required (https://rustup.rs)"),
@@ -351,6 +378,10 @@ impl Tools {
"npm or pnpm is required: install Node.js (https://nodejs.org)",
),
Method::Go { .. } => need(self.which("go").is_some(), "Go is required (https://go.dev/dl)"),
Method::Gem { .. } => need(self.which("gem").is_some(), "Ruby is required (https://www.ruby-lang.org)"),
Method::DotnetTool { .. } => {
need(self.which("dotnet").is_some(), ".NET SDK is required (https://dotnet.microsoft.com/download)")
}
Method::PipVenv { .. } => need(
self.which("uv").is_some() || self.python().is_some(),
"Python 3 or uv is required (https://www.python.org)",
@@ -394,7 +425,9 @@ impl Tools {
can_uninstall: false,
install_hint,
homepage: None,
});
custom_error: None,
})
.map(|info| self.apply_custom(info, None));
};
let (status, path, version) = self.detect(spec);
let unavailable_reason = self.unavailable_reason(spec);
@@ -414,7 +447,34 @@ impl Tools {
can_uninstall,
install_hint,
homepage: Some(spec.homepage.to_string()),
custom_error: None,
})
.map(|info| self.apply_custom(info, Some(spec)))
}
/// Overrides the detected location with the executable chosen in settings.
fn apply_custom(&self, mut info: ToolInfo, spec: Option<&ToolSpec>) -> ToolInfo {
let Some(path) = self.custom.get(&info.command) else { return info };
if !path.is_file() {
info.status = ToolStatus::Missing;
info.custom_error = Some(format!("{} does not exist", path.display()));
info.path = None;
info.version = None;
return info;
}
info.version = spec.and_then(|spec| {
let (cmd, args) = spec.version?;
// The version command is the tool itself, whatever the chosen file is called.
let program =
if cmd == spec.commands[0] { path.clone() } else { path.parent().and_then(|d| self.exe_in(d, cmd))? };
let mut c = self.command(program);
c.args(args);
let (ok, out) = run_quiet(c, Duration::from_secs(4))?;
if ok { parse_version(&out) } else { None }
});
info.status = ToolStatus::Custom;
info.path = Some(path.clone().into());
info
}
fn detect(&self, spec: &ToolSpec) -> (ToolStatus, Option<PathBuf>, Option<String>) {
@@ -539,6 +599,8 @@ impl Tools {
}
Method::Npm { packages } => self.install_npm(packages, cancel, emit)?,
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
Method::DotnetTool { package } => self.install_dotnet_tool(spec, package, cancel, emit)?,
Method::PipVenv { package } => self.install_venv(spec, package, cancel, emit)?,
Method::PipUser { package, .. } => self.install_pip_user(package, cancel, emit)?,
Method::PipTarget { package, .. } => self.install_pip_target(spec, package, cancel, emit)?,
@@ -618,6 +680,96 @@ impl Tools {
self.write_manifest(spec.name, &Manifest { version, source: Some(module.to_string()) })
}
fn install_gem(&self, spec: &ToolSpec, gem: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
let dir = self.root.join(spec.name);
let _ = std::fs::remove_dir_all(&dir);
let home = dir.join("gems");
std::fs::create_dir_all(&home)?;
let mut c = self.command(self.which("gem").expect("checked"));
c.args(["install", "--no-document", "--install-dir"]).arg(&home).arg("--bindir").arg(home.join("bin")).arg(gem);
let result = run_streamed(c, cancel, emit).and_then(|_| {
// RubyGems' stubs only find their gems through GEM_HOME / GEM_PATH.
let env = [("GEM_HOME", home.as_path()), ("GEM_PATH", home.as_path())];
for cmd in spec.commands {
let stub = self
.exe_in(&home.join("bin"), cmd)
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("gem {gem} did not install `{cmd}`")))?;
archive::env_wrapper(&dir.join("bin"), cmd, &stub, &env)?;
}
Ok(())
});
if let Err(e) = result {
let _ = std::fs::remove_dir_all(&dir);
return Err(e);
}
// `gems/gems/<gem>-<version>/`
let version = std::fs::read_dir(home.join("gems")).ok().and_then(|entries| {
entries.flatten().find_map(|e| {
let name = e.file_name().to_string_lossy().into_owned();
name.strip_prefix(&format!("{gem}-"))
.filter(|v| v.starts_with(|c: char| c.is_ascii_digit()))
.map(String::from)
})
});
self.write_manifest(spec.name, &Manifest { version, source: Some(format!("rubygems:{gem}")) })
}
fn install_dotnet_tool(
&self,
spec: &ToolSpec,
package: &str,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let dir = self.root.join(spec.name);
let _ = std::fs::remove_dir_all(&dir);
let tool = dir.join("tool");
std::fs::create_dir_all(&tool)?;
let dotnet = self.which("dotnet").expect("checked");
let mut c = self.command(&dotnet);
c.args(["tool", "install", package, "--tool-path"]).arg(&tool);
let result = run_streamed(c, cancel, emit).and_then(|_| {
// The tool's apphost looks for .NET in the default location only; a
// Homebrew / user-local SDK must be named through DOTNET_ROOT.
let root = self.dotnet_root(&dotnet);
for cmd in spec.commands {
let exe = self
.exe_in(&tool, cmd)
.ok_or_else(|| IdeError::new(ErrorKind::Io, format!("{package} did not install `{cmd}`")))?;
match &root {
Some(root) => archive::env_wrapper(&dir.join("bin"), cmd, &exe, &[("DOTNET_ROOT", root)])?,
None => archive::link_executable(&dir.join("bin"), cmd, &exe)?,
};
}
Ok(())
});
if let Err(e) = result {
let _ = std::fs::remove_dir_all(&dir);
return Err(e);
}
// `Package Id Version Commands` table.
let mut c = self.command(&dotnet);
c.args(["tool", "list", "--tool-path"]).arg(&tool);
let version = run_quiet(c, Duration::from_secs(20)).and_then(|(_, out)| {
out.lines().find_map(|l| {
let mut cols = l.split_whitespace();
cols.next().filter(|id| id.eq_ignore_ascii_case(package))?;
cols.next().map(String::from)
})
});
self.write_manifest(spec.name, &Manifest { version, source: Some(format!("nuget:{package}")) })
}
/// The .NET install `dotnet` runs from: `Microsoft.NETCore.App 9.0.1 [<root>/shared/Microsoft.NETCore.App]`.
fn dotnet_root(&self, dotnet: &Path) -> Option<PathBuf> {
let mut c = self.command(dotnet);
c.arg("--list-runtimes");
let (_, out) = run_quiet(c, Duration::from_secs(20))?;
let line = out.lines().find(|l| l.starts_with("Microsoft.NETCore.App "))?;
let shared = line.rsplit_once('[')?.1.trim_end().strip_suffix(']')?;
Path::new(shared).parent()?.parent().map(Path::to_path_buf)
}
fn install_venv(&self, spec: &ToolSpec, package: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
let dir = self.root.join(spec.name);
let _ = std::fs::remove_dir_all(&dir);
@@ -897,7 +1049,12 @@ impl Tools {
run_streamed(c, &cancel, &quiet)?;
}
}
Method::Go { .. } | Method::PipVenv { .. } | Method::PipTarget { .. } | Method::Release { .. } => {
Method::Go { .. }
| Method::Gem { .. }
| Method::DotnetTool { .. }
| Method::PipVenv { .. }
| Method::PipTarget { .. }
| Method::Release { .. } => {
let dir = self.root.join(spec.name);
if dir.exists() {
std::fs::remove_dir_all(&dir)?;
+3 -2
Переглянути файл
@@ -48,7 +48,7 @@ pub fn run_streamed(cmd: Command, cancel: &CancellationToken, emit: Emit) -> Ide
/// Like [`run_streamed`] but returns `(success, output, status text)` instead of failing on a non-zero exit.
pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) -> IdeResult<(bool, String, String)> {
emit(InstallEvent::Line { text: format!("$ {}", describe(&cmd)) });
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", describe(&cmd))))?;
let (tx, rx) = mpsc::channel::<String>();
let pipes: [Option<Box<dyn Read + Send>>; 2] = [
@@ -94,7 +94,7 @@ pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) ->
/// Runs `cmd` to completion within `timeout`; returns (success, stdout + stderr).
pub fn run_quiet(mut cmd: Command, timeout: Duration) -> Option<(bool, String)> {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn().ok()?;
let mut stdout = child.stdout.take()?;
let mut stderr = child.stderr.take()?;
@@ -161,6 +161,7 @@ impl Http {
fn base(&self, url: &str) -> Command {
let mut cmd = Command::new(&self.curl);
ide_core::process::no_window(&mut cmd);
cmd.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-A", "openidea"]);
if url.starts_with("https://api.github.com/")
&& let Ok(token) = std::env::var("GITHUB_TOKEN").or_else(|_| std::env::var("GH_TOKEN"))
+318
Переглянути файл
@@ -44,6 +44,11 @@ pub enum Method {
/// A pure-Python package unpacked into `<tools>/<name>/lib` (`pip install --target`,
/// universal wheel), put on `PYTHONPATH` of whichever interpreter runs it.
PipTarget { package: &'static str, module: &'static str },
/// `gem install` into `<tools>/<name>/gems`, launched through `GEM_HOME` wrappers in `bin/`.
Gem { gem: &'static str },
/// `dotnet tool install --tool-path <tools>/<name>/tool <package>`, launched
/// through `DOTNET_ROOT` wrappers in `bin/`.
DotnetTool { package: &'static str },
/// Platform archive download into `<tools>/<name>/`.
Release { source: ReleaseSource, assets: &'static [AssetRule], locate: &'static [&'static str] },
}
@@ -54,6 +59,8 @@ impl Method {
Method::Rustup { .. } => "rustup",
Method::Npm { .. } => "npm",
Method::Go { .. } => "go install",
Method::Gem { .. } => "gem",
Method::DotnetTool { .. } => "dotnet tool",
Method::PipVenv { .. } => "pip (virtualenv)",
Method::PipUser { .. } => "pip --user",
Method::PipTarget { .. } => "pip (private copy)",
@@ -78,6 +85,8 @@ pub struct ToolSpec {
/// Version query: a command (looked up next to the main binary first) and its args.
pub version: Option<(&'static str, &'static [&'static str])>,
pub homepage: &'static str,
/// Runtimes the tool runs on, found on `PATH`: command and why it is needed.
pub needs: &'static [(&'static str, &'static str)],
}
impl ToolSpec {
@@ -94,6 +103,11 @@ use Os::{Linux, Mac, Windows};
use ToolKind::{Debugger, LanguageServer, Plugin};
const V: Option<(&str, &[&str])> = None;
const JAVA: &[(&str, &str)] = &[("java", "Java is required (https://adoptium.net)")];
const NODE: &[(&str, &str)] = &[("node", "Node.js is required (https://nodejs.org)")];
const ELIXIR: &[(&str, &str)] = &[("elixir", "Elixir is required (https://elixir-lang.org/install.html)")];
const ELIXIR_LS_ASSETS: &[AssetRule] =
&[any_arch(Mac, "elixir-ls-v*.zip"), any_arch(Linux, "elixir-ls-v*.zip"), any_arch(Windows, "elixir-ls-v*.zip")];
const fn ver(cmd: &'static str) -> Option<(&'static str, &'static [&'static str])> {
Some((cmd, &["--version"]))
}
@@ -107,6 +121,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Rustup { component: "rust-analyzer" },
version: ver("rust-analyzer"),
homepage: "https://rust-analyzer.github.io",
needs: &[],
},
ToolSpec {
name: "vtsls",
@@ -116,6 +131,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["@vtsls/language-server"] },
version: V,
homepage: "https://github.com/yioneko/vtsls",
needs: &[],
},
ToolSpec {
name: "typescript-language-server",
@@ -125,6 +141,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["typescript-language-server", "typescript"] },
version: ver("typescript-language-server"),
homepage: "https://github.com/typescript-language-server/typescript-language-server",
needs: &[],
},
ToolSpec {
name: "pyright",
@@ -134,6 +151,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["pyright"] },
version: ver("pyright"),
homepage: "https://github.com/microsoft/pyright",
needs: &[],
},
ToolSpec {
name: "basedpyright",
@@ -143,6 +161,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::PipVenv { package: "basedpyright" },
version: ver("basedpyright"),
homepage: "https://docs.basedpyright.com",
needs: &[],
},
ToolSpec {
name: "bash-language-server",
@@ -152,6 +171,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["bash-language-server"] },
version: ver("bash-language-server"),
homepage: "https://github.com/bash-lsp/bash-language-server",
needs: &[],
},
ToolSpec {
name: "yaml-language-server",
@@ -161,6 +181,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["yaml-language-server"] },
version: V,
homepage: "https://github.com/redhat-developer/yaml-language-server",
needs: &[],
},
ToolSpec {
name: "vscode-json-language-server",
@@ -170,6 +191,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["vscode-langservers-extracted"] },
version: V,
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
needs: &[],
},
ToolSpec {
name: "vscode-css-language-server",
@@ -179,6 +201,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["vscode-langservers-extracted"] },
version: V,
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
needs: &[],
},
ToolSpec {
name: "vscode-html-language-server",
@@ -188,6 +211,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["vscode-langservers-extracted"] },
version: V,
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
needs: &[],
},
ToolSpec {
name: "dockerfile-language-server",
@@ -197,6 +221,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["dockerfile-language-server-nodejs"] },
version: V,
homepage: "https://github.com/rcjsuen/dockerfile-language-server",
needs: &[],
},
ToolSpec {
name: "svelte-language-server",
@@ -206,6 +231,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["svelte-language-server"] },
version: V,
homepage: "https://github.com/sveltejs/language-tools",
needs: &[],
},
ToolSpec {
name: "vue-language-server",
@@ -215,6 +241,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["@vue/language-server"] },
version: V,
homepage: "https://github.com/vuejs/language-tools",
needs: &[],
},
ToolSpec {
name: "graphql-lsp",
@@ -224,6 +251,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["graphql-language-service-cli"] },
version: V,
homepage: "https://github.com/graphql/graphiql",
needs: &[],
},
ToolSpec {
name: "intelephense",
@@ -233,6 +261,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Npm { packages: &["intelephense"] },
version: V,
homepage: "https://intelephense.com",
needs: &[],
},
ToolSpec {
name: "gopls",
@@ -242,6 +271,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Go { module: "golang.org/x/tools/gopls@latest" },
version: Some(("gopls", &["version"])),
homepage: "https://pkg.go.dev/golang.org/x/tools/gopls",
needs: &[],
},
ToolSpec {
name: "sqls",
@@ -251,6 +281,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Go { module: "github.com/sqls-server/sqls@latest" },
version: Some(("sqls", &["--version"])),
homepage: "https://github.com/sqls-server/sqls",
needs: &[],
},
ToolSpec {
name: "delve",
@@ -260,6 +291,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::Go { module: "github.com/go-delve/delve/cmd/dlv@latest" },
version: Some(("dlv", &["version"])),
homepage: "https://github.com/go-delve/delve",
needs: &[],
},
ToolSpec {
name: "debugpy",
@@ -269,6 +301,7 @@ pub static TOOLS: &[ToolSpec] = &[
method: Method::PipTarget { package: "debugpy", module: "debugpy" },
version: V,
homepage: "https://github.com/microsoft/debugpy",
needs: &[],
},
ToolSpec {
name: "clangd",
@@ -286,6 +319,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("clangd"),
homepage: "https://clangd.llvm.org",
needs: &[],
},
ToolSpec {
name: "lua-language-server",
@@ -305,6 +339,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("lua-language-server"),
homepage: "https://luals.github.io",
needs: &[],
},
ToolSpec {
name: "marksman",
@@ -323,6 +358,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("marksman"),
homepage: "https://github.com/artempyanykh/marksman",
needs: &[],
},
ToolSpec {
name: "taplo",
@@ -342,6 +378,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("taplo"),
homepage: "https://taplo.tamasfe.dev",
needs: &[],
},
ToolSpec {
name: "zls",
@@ -361,6 +398,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: ver("zls"),
homepage: "https://github.com/zigtools/zls",
needs: &[],
},
ToolSpec {
name: "terraform-ls",
@@ -380,6 +418,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: Some(("terraform-ls", &["version"])),
homepage: "https://github.com/hashicorp/terraform-ls",
needs: &[],
},
ToolSpec {
name: "codelldb",
@@ -404,6 +443,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/vadimcn/codelldb",
needs: &[],
},
ToolSpec {
name: "js-debug",
@@ -422,6 +462,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/microsoft/vscode-js-debug",
needs: &[],
},
ToolSpec {
name: "jdtls",
@@ -439,6 +480,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/eclipse-jdtls/eclipse.jdt.ls",
needs: &[],
},
ToolSpec {
name: "java-debug",
@@ -457,6 +499,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/microsoft/java-debug",
needs: &[],
},
ToolSpec {
name: "lombok",
@@ -475,6 +518,7 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://projectlombok.org",
needs: &[],
},
ToolSpec {
name: "kotlin-lsp",
@@ -498,6 +542,280 @@ pub static TOOLS: &[ToolSpec] = &[
},
version: V,
homepage: "https://github.com/Kotlin/kotlin-lsp",
needs: &[],
},
// ElixirLS ships launcher scripts only: on first start they build the server
// with the Elixir / OTP found for the project (Mix.install, needs network).
ToolSpec {
name: "elixir-ls",
display: "ElixirLS",
kind: LanguageServer,
commands: &["elixir-ls"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "elixir-lsp/elixir-ls" },
assets: ELIXIR_LS_ASSETS,
locate: &["language_server.sh", "language_server.bat"],
},
version: V,
homepage: "https://github.com/elixir-lsp/elixir-ls",
needs: ELIXIR,
},
ToolSpec {
name: "elixir-ls-debugger",
display: "ElixirLS Debugger",
kind: Debugger,
commands: &["elixir-ls-debugger"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "elixir-lsp/elixir-ls" },
assets: ELIXIR_LS_ASSETS,
locate: &["debug_adapter.sh", "debug_adapter.bat"],
},
version: V,
homepage: "https://github.com/elixir-lsp/elixir-ls",
needs: ELIXIR,
},
ToolSpec {
name: "buf",
display: "Buf (Protocol Buffers)",
kind: LanguageServer,
commands: &["buf"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "bufbuild/buf" },
assets: &[
rule(Mac, Arm64, "buf-Darwin-arm64.tar.gz"),
rule(Mac, X64, "buf-Darwin-x86_64.tar.gz"),
rule(Linux, X64, "buf-Linux-x86_64.tar.gz"),
rule(Linux, Arm64, "buf-Linux-aarch64.tar.gz"),
rule(Windows, X64, "buf-Windows-x86_64.zip"),
rule(Windows, Arm64, "buf-Windows-arm64.zip"),
],
locate: &["buf"],
},
version: ver("buf"),
homepage: "https://buf.build",
needs: &[],
},
ToolSpec {
name: "clojure-lsp",
display: "clojure-lsp",
kind: LanguageServer,
commands: &["clojure-lsp"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "clojure-lsp/clojure-lsp" },
assets: &[
rule(Mac, Arm64, "clojure-lsp-native-macos-aarch64.zip"),
rule(Mac, X64, "clojure-lsp-native-macos-amd64.zip"),
rule(Linux, X64, "clojure-lsp-native-linux-amd64.zip"),
rule(Linux, Arm64, "clojure-lsp-native-linux-aarch64.zip"),
rule(Windows, X64, "clojure-lsp-native-windows-amd64.zip"),
],
locate: &["clojure-lsp"],
},
version: V,
homepage: "https://clojure-lsp.io",
needs: &[],
},
ToolSpec {
name: "texlab",
display: "TexLab (LaTeX)",
kind: LanguageServer,
commands: &["texlab"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "latex-lsp/texlab" },
assets: &[
rule(Mac, Arm64, "texlab-aarch64-macos.tar.gz"),
rule(Mac, X64, "texlab-x86_64-macos.tar.gz"),
rule(Linux, X64, "texlab-x86_64-linux.tar.gz"),
rule(Linux, Arm64, "texlab-aarch64-linux.tar.gz"),
rule(Windows, X64, "texlab-x86_64-windows.zip"),
rule(Windows, Arm64, "texlab-aarch64-windows.zip"),
],
locate: &["texlab"],
},
version: ver("texlab"),
homepage: "https://github.com/latex-lsp/texlab",
needs: &[],
},
ToolSpec {
name: "neocmakelsp",
display: "neocmakelsp (CMake)",
kind: LanguageServer,
commands: &["neocmakelsp"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "Decodetalkers/neocmakelsp" },
assets: &[
any_arch(Mac, "neocmakelsp-universal-apple-darwin.tar.gz"),
rule(Linux, X64, "neocmakelsp-x86_64-unknown-linux-gnu.tar.gz"),
rule(Linux, Arm64, "neocmakelsp-aarch64-unknown-linux-gnu.tar.gz"),
rule(Windows, X64, "neocmakelsp-x86_64-pc-windows-msvc.zip"),
rule(Windows, Arm64, "neocmakelsp-aarch64-pc-windows-msvc.zip"),
],
locate: &["neocmakelsp"],
},
version: ver("neocmakelsp"),
homepage: "https://github.com/Decodetalkers/neocmakelsp",
needs: &[],
},
ToolSpec {
name: "lemminx",
display: "LemMinX (XML)",
kind: LanguageServer,
commands: &["lemminx"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "redhat-developer/vscode-xml" },
assets: &[
rule(Mac, Arm64, "lemminx-osx-aarch_64.zip"),
rule(Mac, X64, "lemminx-osx-x86_64.zip"),
rule(Linux, X64, "lemminx-linux-x86_64.zip"),
rule(Linux, Arm64, "lemminx-linux-aarch_64.zip"),
rule(Windows, X64, "lemminx-win32.zip"),
],
locate: &["lemminx-*"],
},
version: V,
homepage: "https://github.com/eclipse/lemminx",
needs: &[],
},
ToolSpec {
name: "perlnavigator",
display: "Perl Navigator",
kind: LanguageServer,
commands: &["perlnavigator"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "bscan/PerlNavigator" },
assets: &[
any_arch(Mac, "perlnavigator-macos-x86_64.zip"),
rule(Linux, X64, "perlnavigator-linux-x86_64.zip"),
rule(Windows, X64, "perlnavigator-win-x86_64.zip"),
],
locate: &["perlnavigator"],
},
version: V,
homepage: "https://github.com/bscan/PerlNavigator",
needs: &[("perl", "Perl is required (https://www.perl.org/get.html)")],
},
ToolSpec {
name: "kotlin-language-server",
display: "Kotlin Language Server (fwcd)",
kind: LanguageServer,
commands: &["kotlin-language-server"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "fwcd/kotlin-language-server" },
assets: &[any_arch(Mac, "server.zip"), any_arch(Linux, "server.zip"), any_arch(Windows, "server.zip")],
locate: &["kotlin-language-server"],
},
version: V,
homepage: "https://github.com/fwcd/kotlin-language-server",
needs: JAVA,
},
ToolSpec {
name: "kotlin-debug-adapter",
display: "Kotlin Debug Adapter",
kind: Debugger,
commands: &["kotlin-debug-adapter"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "fwcd/kotlin-debug-adapter" },
assets: &[any_arch(Mac, "adapter.zip"), any_arch(Linux, "adapter.zip"), any_arch(Windows, "adapter.zip")],
locate: &["kotlin-debug-adapter"],
},
version: V,
homepage: "https://github.com/fwcd/kotlin-debug-adapter",
needs: JAVA,
},
ToolSpec {
name: "netcoredbg",
display: "netcoredbg (.NET debugger)",
kind: Debugger,
commands: &["netcoredbg"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "Samsung/netcoredbg" },
assets: &[
rule(Mac, Arm64, "netcoredbg-osx-arm64.zip"),
rule(Linux, X64, "netcoredbg-linux-amd64.tar.gz"),
rule(Linux, Arm64, "netcoredbg-linux-arm64.tar.gz"),
rule(Windows, X64, "netcoredbg-win64.zip"),
],
locate: &["netcoredbg"],
},
version: V,
homepage: "https://github.com/Samsung/netcoredbg",
needs: &[],
},
ToolSpec {
name: "bash-debug",
display: "Bash Debug",
kind: Debugger,
commands: &["bash-debug-adapter"],
method: Method::Release {
source: ReleaseSource::OpenVsx { namespace: "rogalmic", extension: "bash-debug" },
assets: &[
any_arch(Mac, "rogalmic.bash-debug-*.vsix"),
any_arch(Linux, "rogalmic.bash-debug-*.vsix"),
any_arch(Windows, "rogalmic.bash-debug-*.vsix"),
],
locate: &["bashDebug.js"],
},
version: V,
homepage: "https://github.com/rogalmic/vscode-bash-debug",
needs: NODE,
},
ToolSpec {
name: "php-debug",
display: "PHP Debug (Xdebug)",
kind: Debugger,
commands: &["php-debug-adapter"],
method: Method::Release {
source: ReleaseSource::OpenVsx { namespace: "xdebug", extension: "php-debug" },
assets: &[
any_arch(Mac, "xdebug.php-debug-*.vsix"),
any_arch(Linux, "xdebug.php-debug-*.vsix"),
any_arch(Windows, "xdebug.php-debug-*.vsix"),
],
locate: &["phpDebug.js"],
},
version: V,
homepage: "https://github.com/xdebug/vscode-php-debug",
needs: NODE,
},
ToolSpec {
name: "ruby-lsp",
display: "Ruby LSP (Shopify)",
kind: LanguageServer,
commands: &["ruby-lsp"],
method: Method::Gem { gem: "ruby-lsp" },
version: V,
homepage: "https://shopify.github.io/ruby-lsp",
needs: &[],
},
ToolSpec {
name: "solargraph",
display: "Solargraph (Ruby)",
kind: LanguageServer,
commands: &["solargraph"],
method: Method::Gem { gem: "solargraph" },
version: ver("solargraph"),
homepage: "https://solargraph.org",
needs: &[],
},
ToolSpec {
name: "csharp-ls",
display: "csharp-ls",
kind: LanguageServer,
commands: &["csharp-ls"],
method: Method::DotnetTool { package: "csharp-ls" },
version: V,
homepage: "https://github.com/razzmatazz/csharp-language-server",
needs: &[],
},
ToolSpec {
name: "fsautocomplete",
display: "FsAutoComplete (F#)",
kind: LanguageServer,
commands: &["fsautocomplete"],
method: Method::DotnetTool { package: "fsautocomplete" },
version: V,
homepage: "https://github.com/ionide/FsAutoComplete",
needs: &[],
},
];
+101 -5
Переглянути файл
@@ -68,10 +68,12 @@ fn everything_missing_on_an_empty_system() {
assert!(vtsls.languages.iter().any(|l| l == "TypeScript"));
assert!(vtsls.unavailable_reason.as_deref().unwrap().contains("npm"));
// Servers without an installer are listed with their manual hint.
let ruby = find(&list, "solargraph");
assert_eq!(ruby.install_method, None);
assert!(!ruby.can_install);
assert_eq!(ruby.status, ToolStatus::Missing);
let hls = find(&list, "haskell-language-server");
assert_eq!(hls.install_method, None);
assert!(!hls.can_install);
assert_eq!(hls.status, ToolStatus::Missing);
// Gem tools need Ruby.
assert!(find(&list, "solargraph").unavailable_reason.as_deref().unwrap().contains("Ruby"));
// Shared npm package: each server is its own row.
assert_eq!(find(&list, "vscode-css-language-server").install_method.as_deref(), Some("npm"));
assert!(find(&list, "delve").kind == ToolKind::Debugger);
@@ -155,7 +157,7 @@ fn bin_dirs_cover_every_managed_layout() {
fn unknown_or_manual_tools_cannot_be_installed() {
let env = Env::new();
let tools = env.tools();
let err = tools.install("solargraph", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
let err = tools.install("haskell-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert!(err.message.contains("cannot be installed automatically"));
assert_eq!(tools.info("nope", &langs()).unwrap_err().kind, ErrorKind::NotFound);
@@ -286,3 +288,97 @@ fn installed_bundle_is_detected_and_resolvable() {
assert_eq!(managed_bundle(app_data, "java-debug"), Some(bin.join("com.microsoft.java.debug.plugin.jar")));
assert_eq!(managed_bundle(app_data, "jdtls"), None, "not a bundle");
}
#[cfg(unix)]
#[test]
fn custom_paths_win_and_report_their_version() {
let env = Env::new();
env.script(&env.sys, "gopls", "echo 'golang.org/x/tools/gopls v0.16.1'");
let elsewhere = env.sys.parent().unwrap().join("opt/go/bin");
env.script(&elsewhere, "my-gopls", "echo 'golang.org/x/tools/gopls v0.17.0'");
let custom =
BTreeMap::from([("gopls".to_string(), elsewhere.join("my-gopls")), ("zls".to_string(), elsewhere.join("zls"))]);
let list = env.tools().with_custom_paths(custom).list(&langs());
let gopls = find(&list, "gopls");
assert_eq!(gopls.status, ToolStatus::Custom);
assert_eq!(gopls.path.as_deref(), Some(elsewhere.join("my-gopls").as_path()));
assert_eq!(gopls.version.as_deref(), Some("0.17.0"));
assert_eq!(gopls.custom_error, None);
// A path that does not exist is reported, not silently replaced by detection.
let zls = find(&list, "zls");
assert_eq!(zls.status, ToolStatus::Missing);
assert!(zls.custom_error.as_deref().unwrap().contains("does not exist"));
}
#[test]
fn a_debugger_named_like_its_server_is_listed_by_its_command() {
let list = Env::new().tools().list(&langs());
let server = find(&list, "elixir-ls");
assert_eq!((server.kind, server.command.as_str()), (ToolKind::LanguageServer, "elixir-ls"));
let debugger = find(&list, "elixir-ls-debugger");
assert_eq!((debugger.kind, debugger.command.as_str()), (ToolKind::Debugger, "elixir-ls-debugger"));
assert_eq!(debugger.languages, vec!["Elixir".to_string()]);
}
#[cfg(unix)]
#[test]
fn elixir_ls_needs_elixir_and_lists_its_debugger() {
let env = Env::new();
env.script(&env.sys, "curl", "exit 0");
let list = env.tools().list(&langs());
let server = find(&list, "elixir-ls");
assert_eq!(server.install_method.as_deref(), Some("GitHub release"));
assert!(!server.can_install);
assert!(server.unavailable_reason.as_deref().unwrap().contains("Elixir is required"));
let debugger = find(&list, "elixir-ls-debugger");
assert_eq!((debugger.kind, debugger.languages.as_slice()), (ToolKind::Debugger, ["Elixir".to_string()].as_slice()));
env.script(&env.sys, "elixir", "exit 0");
let list = env.tools().list(&langs());
assert!(find(&list, "elixir-ls").can_install);
assert!(find(&list, "elixir-ls-debugger").can_install);
}
#[cfg(unix)]
#[test]
fn gem_install_wraps_stubs_with_gem_home() {
let env = Env::new();
// `gem install --no-document --install-dir <home> --bindir <bin> solargraph`
env.script(
&env.sys,
"gem",
r#"home="$4"; bin="$6"; /bin/mkdir -p "$home/gems/solargraph-0.50.0" "$bin"
printf '#!/bin/sh\necho "$GEM_HOME"\n' > "$bin/solargraph"; /bin/chmod +x "$bin/solargraph""#,
);
let tools = env.tools();
let info = tools.install("solargraph", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("0.50.0"));
let wrapper = env.root.join("solargraph/bin/solargraph");
assert_eq!(info.path.as_deref(), Some(wrapper.as_path()));
let out = std::process::Command::new(&wrapper).output().unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), env.root.join("solargraph/gems").to_string_lossy());
}
#[cfg(unix)]
#[test]
fn dotnet_tool_install_into_tool_path() {
let env = Env::new();
env.script(
&env.sys,
"dotnet",
r#"case "$2" in
install) /bin/mkdir -p "$5"; printf '#!/bin/sh\necho "$DOTNET_ROOT"\n' > "$5/csharp-ls"; /bin/chmod +x "$5/csharp-ls" ;;
list) printf 'Package Id Version Commands\n----\ncsharp-ls 0.15.0 csharp-ls\n' ;;
esac
[ "$1" = --list-runtimes ] && echo 'Microsoft.NETCore.App 9.0.1 [/opt/dotnet/shared/Microsoft.NETCore.App]'
exit 0"#,
);
let info = env.tools().install("csharp-ls", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
assert_eq!(info.version.as_deref(), Some("0.15.0"));
let wrapper = env.root.join("csharp-ls/bin/csharp-ls");
assert_eq!(info.path.as_deref(), Some(wrapper.as_path()));
let out = std::process::Command::new(&wrapper).output().unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "/opt/dotnet");
}
+2 -11
Переглянути файл
@@ -64,11 +64,7 @@ pub fn git_version(executable: Option<&Path>) -> IdeResult<String> {
};
let mut cmd = Command::new(&exe);
cmd.arg("--version").stdin(Stdio::null()).env("LC_ALL", "C");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
ide_core::process::no_window(&mut cmd);
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", exe.display())))?;
let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !out.status.success() || !text.starts_with("git version") {
@@ -99,12 +95,7 @@ pub(crate) fn command(root: &Path) -> IdeResult<Command> {
.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
ide_core::process::no_window(&mut cmd);
Ok(cmd)
}
+195 -2
Переглянути файл
@@ -126,6 +126,42 @@ pub struct Branch {
pub commit: String,
}
/// Commit Options (IDEA's commit options popup).
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CommitOptions {
pub amend: bool,
pub sign_off: bool,
/// `--author`, e.g. `Name <[email protected]>`; `None` or blank uses the configured user.
pub author: Option<String>,
/// False skips the pre-commit and commit-msg hooks (`--no-verify`).
pub run_hooks: bool,
/// Files committed with only some of their changes (IDEA's partial commit). They are
/// committed through a temporary index, so neither the working tree nor the other
/// entries of the index change; afterwards their index entries match the new commit.
#[serde(default)]
pub partial: Vec<PartialCommitFile>,
}
/// A file of a partial commit: which of its changes against HEAD to commit.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PartialCommitFile {
pub path: ide_core::IpcPath,
/// The hunks to commit, as [`diff_hunks`] of the HEAD and on-disk texts reports them.
pub hunks: Vec<HunkRange>,
}
/// A hunk identified by its line ranges (0-based), see [`LineHunk`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HunkRange {
pub start: u32,
pub lines: u32,
pub old_start: u32,
pub old_lines: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ChangedFile {
@@ -225,6 +261,106 @@ pub struct ApplyOutcome {
pub conflicts: Vec<String>,
}
/// How Checkout treats local changes that the switch would overwrite (IDEA's Smart
/// Checkout dialog).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum CheckoutMode {
/// Fail with [`CheckoutOutcome::LocalChanges`] and change nothing.
#[default]
Normal,
/// Stash local changes, switch, and restore them (conflicts are left to resolve).
Smart,
/// Discard the local changes in the way (`git switch --discard-changes`).
Force,
}
/// Checking out remote `origin/x` while local `x` has commits `origin/x` lacks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DivergedLocal {
/// Rebase local `x` onto `origin/x` (IDEA "Rebase onto Remote").
Rebase,
/// Reset local `x` to `origin/x` (IDEA "Drop Local Commits").
Reset,
}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutOptions {
#[serde(default)]
pub mode: CheckoutMode,
/// Required when checking out a remote branch whose local namesake is ahead of it.
#[serde(default)]
pub diverged: Option<DivergedLocal>,
}
/// Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts`
/// left the repository untouched.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum CheckoutOutcome {
Done,
/// These local changes (repository-relative paths) would be overwritten.
LocalChanges {
files: Vec<String>,
},
/// Local branch `local` has commits that remote branch `remote` does not.
LocalBranchAhead {
local: String,
remote: String,
},
/// Switched, but restoring the local changes (Smart Checkout) or the rebase stopped
/// on conflicts in these files.
Conflicts {
files: Vec<String>,
},
}
/// A deleted local branch, enough to restore it (IDEA's "Restore" notification action).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DeletedBranch {
pub name: String,
/// The commit the branch pointed at.
pub tip: String,
/// Its upstream (`origin/x`), restored with it.
pub upstream: Option<String>,
/// It was not fully merged: its own commits are now unreachable from any branch.
pub unmerged: bool,
}
/// Who stands on each side of the conflicts of the operation in progress (merge editor
/// titles, as IDEA labels them).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MergeSides {
/// `merge`, `rebase`, `cherry-pick`, `revert`…; `None` outside an operation.
pub operation: Option<String>,
/// Git's "ours" is not the user's work: during a rebase stage 2 holds the commits
/// rebased onto and stage 3 the user's commit being replayed. [`MergeVersions`] is
/// already swapped; conflict markers in the file are not.
pub reversed: bool,
/// The current branch (for a rebase: the branch being rebased).
pub branch: Option<String>,
/// Short id of the commit being applied (REBASE_HEAD, CHERRY_PICK_HEAD, REVERT_HEAD)
/// or merged (MERGE_HEAD).
pub commit: Option<String>,
/// The other branch: the one being merged, or the one rebased onto.
pub other_branch: Option<String>,
}
/// The versions of a conflicted file as the merge editor shows them.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MergeVersions {
pub base: Option<String>,
/// The user's side ("Accept Yours"): git's stage 2, or stage 3 when `sides.reversed`.
pub ours: Option<String>,
pub theirs: Option<String>,
pub sides: MergeSides,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Changelist {
@@ -256,6 +392,7 @@ mod patch;
mod refs;
mod remotes;
mod repo;
mod roots;
pub mod shelf;
mod status;
mod write;
@@ -263,6 +400,7 @@ mod write;
pub use cli::{detected_git_executable, git_version, set_git_executable};
pub use diff::build_partial_patch;
pub use remotes::Remote;
pub use roots::Repos;
/// Clones `url` into `dest` (which must not exist or be empty), streaming progress.
pub fn clone(url: &str, dest: &Path, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
@@ -308,6 +446,10 @@ impl Repo {
pub fn branch_info(&self) -> IdeResult<BranchInfo> {
refs::branch_info(self)
}
/// Merge / rebase / cherry-pick… in progress (cheap: no ref walking).
pub fn operation(&self) -> IdeResult<Option<String>> {
Ok(refs::operation(&self.gix()?))
}
/// Content of `path` at `rev` (default HEAD); `None` if absent there.
/// `rev` may be any revision git understands, or `":"` / `":0"` for the index.
pub fn file_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<String>> {
@@ -398,7 +540,12 @@ impl Repo {
/// Commits the index; returns the new HEAD commit id. An empty message with
/// `amend` keeps the previous message.
pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
write::commit(self, message, amend, sign_off)
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true, partial: Vec::new() };
write::commit(self, message, &options)
}
/// Commits with the Commit Options popup's choices.
pub fn commit_with(&self, message: &str, options: &CommitOptions) -> IdeResult<String> {
write::commit(self, message, options)
}
/// Switches to `branch`. With `create`, creates it at HEAD. Without, a remote branch
/// (`origin/x`) gets a local tracking branch and any other revision is checked out
@@ -406,6 +553,13 @@ impl Repo {
pub fn checkout(&self, branch: &str, create: bool) -> IdeResult<()> {
write::checkout(self, branch, create)
}
/// [`Repo::checkout`] as IDEA does it: local changes in the way are reported (or
/// stashed / discarded per `options.mode`), and a remote branch whose local namesake
/// is behind fast-forwards that branch, while one that is ahead is reported (or
/// rebased / reset per `options.diverged`).
pub fn checkout_with(&self, branch: &str, create: bool, options: &CheckoutOptions) -> IdeResult<CheckoutOutcome> {
write::checkout_with(self, branch, create, options)
}
/// Creates branch `name` at `start` (default HEAD), optionally switching to it. A
/// remote-tracking start point (`origin/x`) becomes the new branch's upstream.
pub fn create_branch(&self, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> {
@@ -421,6 +575,16 @@ impl Repo {
pub fn delete_branch(&self, branch: &str, force: bool) -> IdeResult<()> {
write::delete_branch(self, branch, force)
}
/// Deletes a local branch as IDEA does: without asking, force-deleting one that is not
/// fully merged (reported as `unmerged`), and returning what [`Repo::restore_branch`]
/// needs to undo it.
pub fn delete_branch_restorable(&self, branch: &str) -> IdeResult<DeletedBranch> {
write::delete_branch_restorable(self, branch)
}
/// Recreates a deleted branch at its old tip, with its upstream.
pub fn restore_branch(&self, deleted: &DeletedBranch) -> IdeResult<()> {
write::restore_branch(self, deleted)
}
/// Renames a local branch (`git branch -m`); its upstream configuration moves with it.
pub fn rename_branch(&self, from: &str, to: &str) -> IdeResult<()> {
write::rename_branch(self, from, to)
@@ -500,7 +664,20 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
write::push_branch(self, branch, revision, force_with_lease, cancel, on_output)
write::push_branch(self, branch, revision, None, force_with_lease, cancel, on_output)
}
/// [`Repo::push_branch`] to remote branch `target` instead of the upstream's name (the
/// Push dialog's editable target).
pub fn push_branch_to(
&self,
branch: &str,
revision: Option<&str>,
target: &str,
force_with_lease: bool,
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
write::push_branch(self, branch, revision, Some(target), force_with_lease, cancel, on_output)
}
/// Fast-forwards a local branch that is not checked out to its upstream (Branches ›
/// Update). Fails when the branch has diverged.
@@ -563,6 +740,10 @@ impl Repo {
pub fn tags(&self) -> IdeResult<Vec<String>> {
ops::tags(self)
}
/// Files that differ between revisions `from` and `to`.
pub fn diff_revisions(&self, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
ops::diff_revisions(self, from, to)
}
/// Tracked files whose working-tree content differs from `rev`.
pub fn diff_with_worktree(&self, rev: &str) -> IdeResult<Vec<ChangedFile>> {
ops::diff_with_worktree(self, rev)
@@ -595,6 +776,18 @@ impl Repo {
shelf::unshelve(self, shelf_dir, id, remove)
}
/// Who is on each side of the conflicts of the operation in progress.
pub fn merge_sides(&self) -> IdeResult<MergeSides> {
ops::merge_sides(self)
}
/// The versions of a conflicted file with the user's work as `ours`, as IDEA's merge
/// dialog shows them (sides swapped during a rebase).
pub fn merge_versions(&self, path: &Path) -> IdeResult<MergeVersions> {
let (base, ours, theirs) = self.conflict_versions(path)?;
let sides = self.merge_sides()?;
let (ours, theirs) = if sides.reversed { (theirs, ours) } else { (ours, theirs) };
Ok(MergeVersions { base, ours, theirs, sides })
}
/// For conflict resolution: (base, ours, theirs) versions of a conflicted file.
pub fn conflict_versions(&self, path: &Path) -> IdeResult<(Option<String>, Option<String>, Option<String>)> {
let rel = self.rel_path(path)?;
+66 -1
Переглянути файл
@@ -3,7 +3,7 @@
use crate::cli::{self, run};
use crate::repo::{gx, resolve};
use crate::{ChangeKind, ChangedFile, RebaseAction, RebaseEntry, Repo, ResetMode};
use crate::{ChangeKind, ChangedFile, MergeSides, RebaseAction, RebaseEntry, Repo, ResetMode};
use ide_core::{CancellationToken, IdeError, IdeResult};
/// The in-progress operation git can continue / abort / skip.
@@ -20,6 +20,64 @@ fn sequencer(r: &Repo) -> IdeResult<&'static str> {
use crate::write::unmerged_paths;
/// The sides of the operation in progress, read from the files git keeps in `.git`.
pub(crate) fn merge_sides(r: &Repo) -> IdeResult<MergeSides> {
let repo = r.gix()?;
let operation = crate::refs::operation(&repo);
let read = |name: &str| {
std::fs::read_to_string(r.git_dir.join(name))
.ok()
.and_then(|s| s.lines().next().map(|l| l.trim().to_string()))
.filter(|s| !s.is_empty())
};
let short = |id: String| id.chars().take(8).collect::<String>();
let head_branch = repo.head_name().map_err(gx)?.map(|n| crate::repo::to_string(n.as_ref().shorten()));
let mut sides = MergeSides { operation: operation.clone(), branch: head_branch, ..Default::default() };
match operation.as_deref() {
Some("rebase") => {
sides.reversed = true;
let dir = ["rebase-merge", "rebase-apply"].into_iter().find(|d| r.git_dir.join(d).is_dir());
if let Some(dir) = dir {
if let Some(head) = read(&format!("{dir}/head-name")) {
sides.branch = Some(head.strip_prefix("refs/heads/").unwrap_or(&head).to_string());
}
sides.other_branch = read(&format!("{dir}/onto")).and_then(|onto| branch_at(r, &onto));
}
sides.commit = read("REBASE_HEAD").map(short);
}
Some("merge") => {
let head = read("MERGE_HEAD");
// git quotes the merged ref on the first line: `Merge branch 'main' into feature`.
sides.other_branch = read("MERGE_MSG")
.and_then(|m| m.split('\'').nth(1).map(str::to_string))
.filter(|b| !b.is_empty())
.or_else(|| head.as_deref().and_then(|h| branch_at(r, h)));
sides.commit = head.map(short);
}
Some("cherry-pick") => sides.commit = read("CHERRY_PICK_HEAD").map(short),
Some("revert") => sides.commit = read("REVERT_HEAD").map(short),
_ => {}
}
Ok(sides)
}
/// The single branch (local first, then remote) pointing at `commit`.
fn branch_at(r: &Repo, commit: &str) -> Option<String> {
if commit.starts_with('-') {
return None;
}
["refs/heads", "refs/remotes"].into_iter().find_map(|refs| {
let out =
run(r.root(), &["for-each-ref", "--points-at", commit, "--format=%(refname:short)", refs], None).ok()?;
let names: Vec<String> =
out.stdout_str().lines().filter(|l| !l.is_empty() && !l.ends_with("/HEAD")).map(str::to_string).collect();
match names.as_slice() {
[one] => Some(one.clone()),
_ => None,
}
})
}
fn check_commits(commits: &[String]) -> IdeResult<()> {
if commits.is_empty() {
return Err(IdeError::invalid("no commits selected"));
@@ -259,6 +317,13 @@ pub(crate) fn diff_with_worktree(r: &Repo, rev: &str) -> IdeResult<Vec<ChangedFi
Ok(parse_name_status(&out.stdout_str()))
}
/// Files that differ between two revisions (Update Project's "N files updated").
pub(crate) fn diff_revisions(r: &Repo, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
check_commits(&[from.to_string(), to.to_string()])?;
let out = run(r.root(), &["diff", "--name-status", "-z", "-M", "--no-ext-diff", from, to, "--"], None)?;
Ok(parse_name_status(&out.stdout_str()))
}
/// Parses `git diff --name-status -z` output.
pub(crate) fn parse_name_status(text: &str) -> Vec<ChangedFile> {
let mut parts = text.split('\0').filter(|s| !s.is_empty());
+1 -1
Переглянути файл
@@ -30,7 +30,7 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
Ok(info)
}
fn operation(repo: &gix::Repository) -> Option<String> {
pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
use gix::state::InProgress::*;
let op = match repo.state()? {
ApplyMailbox | ApplyMailboxRebase => "am",
+243
Переглянути файл
@@ -0,0 +1,243 @@
//! The repositories of a project (IDEA's VCS roots): the one containing the project
//! root plus those nested below it (separate clones side by side, submodules).
use crate::{FileStatus, Repo};
use ide_core::IdeResult;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// How deep below the project root nested repositories are looked for.
const MAX_DEPTH: usize = 4;
/// Folders never searched for nested repositories (dependencies, build output).
const SKIPPED: &[&str] = &["node_modules", "target", "build", "dist", "out", "vendor", "venv", "__pycache__"];
/// The repositories of a project, sorted by root; lookups pick the innermost one.
#[derive(Clone, Default)]
pub struct Repos {
repos: Vec<Arc<Repo>>,
primary: Option<usize>,
}
impl Repos {
/// The repository containing `project_root` and every repository whose worktree
/// root lies below it (up to [`MAX_DEPTH`] levels; hidden and dependency folders and
/// folders `skip` rejects are not searched).
pub fn discover(project_root: &Path, skip: &dyn Fn(&Path) -> bool) -> IdeResult<Self> {
let mut repos: Vec<Repo> = Vec::new();
if let Some(r) = Repo::discover(project_root)? {
repos.push(r);
}
let mut stack: Vec<(PathBuf, usize)> = vec![(project_root.to_path_buf(), 0)];
while let Some((dir, depth)) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let name = entry.file_name();
let name = name.to_string_lossy();
let path = entry.path();
if name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(&path) {
continue;
}
if path.join(".git").exists()
&& let Ok(Some(r)) = Repo::discover(&path)
&& r.root() == path
&& !repos.iter().any(|x| x.root() == r.root())
{
repos.push(r);
}
if depth + 1 < MAX_DEPTH {
stack.push((path, depth + 1));
}
}
}
Ok(Self::new(repos, project_root))
}
/// Only the repository containing `project_root` (the quick lookup on project open).
pub fn enclosing(project_root: &Path) -> IdeResult<Self> {
Ok(Self::new(Repo::discover(project_root)?.into_iter().collect(), project_root))
}
/// Worktree roots, sorted.
pub fn roots(&self) -> Vec<PathBuf> {
self.repos.iter().map(|r| r.root().to_path_buf()).collect()
}
fn new(mut repos: Vec<Repo>, project_root: &Path) -> Self {
repos.sort_by(|a, b| a.root().cmp(b.root()));
let repos: Vec<Arc<Repo>> = repos.into_iter().map(Arc::new).collect();
let roots: Vec<&Path> = repos.iter().map(|r| r.root()).collect();
let primary = innermost(&roots, project_root, false).or((!repos.is_empty()).then_some(0));
Self { repos, primary }
}
pub fn is_empty(&self) -> bool {
self.repos.is_empty()
}
pub fn all(&self) -> &[Arc<Repo>] {
&self.repos
}
/// The repository of the project root, else the first one.
pub fn primary(&self) -> Option<&Arc<Repo>> {
self.primary.map(|i| &self.repos[i])
}
/// The innermost repository containing `path` (a file or folder). A nested repository's
/// root is an entry of the enclosing repository (a submodule or untracked folder there), so
/// it belongs to that one; to the repository itself only when nothing encloses it.
pub fn for_path(&self, path: &Path) -> Option<&Arc<Repo>> {
let roots: Vec<&Path> = self.repos.iter().map(|r| r.root()).collect();
let found = innermost(&roots, path, true).or_else(|| {
// Another spelling of the same location (symlinks, /var vs /private/var).
let canon = dunce::canonicalize(path).ok()?;
let roots: Vec<PathBuf> =
roots.iter().map(|r| dunce::canonicalize(r).unwrap_or_else(|_| r.to_path_buf())).collect();
innermost(&roots.iter().map(PathBuf::as_path).collect::<Vec<_>>(), &canon, true)
});
found.map(|i| &self.repos[i])
}
/// The repository whose worktree root is `root` (the repository a repository-scoped
/// command was given).
pub fn at_root(&self, root: &Path) -> Option<&Arc<Repo>> {
self.repos.iter().find(|r| r.root() == root).or_else(|| {
let canon = dunce::canonicalize(root).ok()?;
self.repos.iter().find(|r| dunce::canonicalize(r.root()).is_ok_and(|r| r == canon))
})
}
/// `paths` grouped by the repository each belongs to (paths outside every repository are dropped).
pub fn group(&self, paths: &[PathBuf]) -> Vec<(Arc<Repo>, Vec<PathBuf>)> {
let mut out: Vec<(Arc<Repo>, Vec<PathBuf>)> = Vec::new();
for p in paths {
let Some(repo) = self.for_path(p) else { continue };
match out.iter_mut().find(|(r, _)| Arc::ptr_eq(r, repo)) {
Some((_, list)) => list.push(p.clone()),
None => out.push((repo.clone(), vec![p.clone()])),
}
}
out
}
/// Changes of every repository. A nested repository reports its own files, so the
/// enclosing one's "untracked folder" entry for it is dropped. A repository that cannot
/// be read (e.g. deleted since the last scan) is left out; fails only when all fail.
pub fn status(&self) -> IdeResult<Vec<FileStatus>> {
let mut out = Vec::new();
let mut first_error = None;
let mut read = 0;
for repo in &self.repos {
let nested: Vec<&Path> = self
.repos
.iter()
.map(|r| r.root())
.filter(|r| *r != repo.root() && r.starts_with(repo.root()))
.collect();
let status = match repo.status() {
Ok(status) => {
read += 1;
status
}
Err(e) => {
tracing::warn!("git status of {}: {e}", repo.root().display());
first_error.get_or_insert(e);
continue;
}
};
out.extend(status.into_iter().filter(|f| {
let untracked_root =
f.unstaged == Some(crate::ChangeKind::Untracked) && nested.iter().any(|n| f.path.0 == *n);
!untracked_root
}));
}
match first_error {
Some(e) if read == 0 => Err(e),
_ => Ok(out),
}
}
}
/// Index of the innermost of `roots` containing `path`. With `strict`, a root equal to
/// `path` counts only when no other root contains it.
fn innermost(roots: &[&Path], path: &Path, strict: bool) -> Option<usize> {
let best = |strict: bool| {
roots
.iter()
.enumerate()
.filter(|(_, r)| path.starts_with(r) && !(strict && **r == path))
.max_by_key(|(_, r)| r.as_os_str().len())
.map(|(i, _)| i)
};
best(strict).or_else(|| best(false))
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
fn git_init(dir: &Path) {
std::fs::create_dir_all(dir).unwrap();
let ok = Command::new("git").args(["init", "-q"]).current_dir(dir).status().is_ok_and(|s| s.success());
assert!(ok, "git init in {}", dir.display());
}
#[test]
fn finds_nested_repositories_and_routes_paths() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git_init(&root);
git_init(&root.join("services/api"));
git_init(&root.join("web"));
git_init(&root.join("node_modules/dep"));
git_init(&root.join(".cache/repo"));
std::fs::write(root.join("services/api/main.rs"), "fn main() {}").unwrap();
std::fs::write(root.join("README.md"), "x").unwrap();
let repos = Repos::discover(&root, &|_| false).unwrap();
let roots: Vec<&Path> = repos.all().iter().map(|r| r.root()).collect();
assert_eq!(roots, [root.as_path(), &root.join("services/api"), &root.join("web")]);
assert_eq!(repos.primary().unwrap().root(), root);
assert_eq!(repos.for_path(&root.join("services/api/main.rs")).unwrap().root(), root.join("services/api"));
assert_eq!(repos.for_path(&root.join("services/other.txt")).unwrap().root(), root);
// A nested root is the enclosing repository's entry (submodule / untracked folder).
assert_eq!(repos.for_path(&root.join("services/api")).unwrap().root(), root);
assert_eq!(repos.for_path(&root).unwrap().root(), root);
assert_eq!(repos.at_root(&root.join("services/api")).unwrap().root(), root.join("services/api"));
assert!(repos.at_root(&root.join("services")).is_none());
let status = repos.status().unwrap();
let paths: Vec<String> =
status.iter().map(|f| f.path.0.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/")).collect();
assert!(paths.contains(&"README.md".to_owned()), "{paths:?}");
assert!(paths.contains(&"services/api/main.rs".to_owned()), "{paths:?}");
assert!(
!paths.iter().any(|p| p.trim_end_matches('/') == "web"),
"nested root is not an untracked folder: {paths:?}"
);
let groups = repos.group(&[root.join("README.md"), root.join("services/api/main.rs"), root.join("web/x")]);
assert_eq!(groups.len(), 3);
assert_eq!(groups[1].1, [root.join("services/api/main.rs")]);
let skipped = Repos::discover(&root, &|p| p.ends_with("services")).unwrap();
assert_eq!(skipped.all().len(), 2);
}
#[test]
fn side_by_side_repositories_without_an_enclosing_one() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git_init(&root.join("a"));
git_init(&root.join("b"));
let repos = Repos::discover(&root, &|_| false).unwrap();
assert_eq!(repos.all().len(), 2);
assert_eq!(repos.primary().unwrap().root(), root.join("a"), "the first when none contains the project root");
assert!(repos.for_path(&root.join("c.txt")).is_none());
}
}
+255 -7
Переглянути файл
@@ -2,7 +2,9 @@
use crate::cli::{self, run};
use crate::repo::{gx, resolve};
use crate::{BlameLine, Repo};
use crate::{
BlameLine, CheckoutMode, CheckoutOptions, CheckoutOutcome, CommitOptions, DeletedBranch, DivergedLocal, Repo,
};
use gix::bstr::{BStr, ByteSlice};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
@@ -222,15 +224,22 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
Ok(())
}
pub(crate) fn commit(r: &Repo, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
pub(crate) fn commit(r: &Repo, message: &str, options: &CommitOptions) -> IdeResult<String> {
let mut args = vec!["commit", "-q", "--cleanup=whitespace"];
if amend {
if options.amend {
args.push("--amend");
}
if sign_off {
if options.sign_off {
args.push("--signoff");
}
let stdin = if amend && message.trim().is_empty() {
if !options.run_hooks {
args.push("--no-verify");
}
let author = options.author.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(|a| format!("--author={a}"));
if let Some(a) = &author {
args.push(a.as_str());
}
let stdin = if options.amend && message.trim().is_empty() {
args.push("--no-edit");
None
} else {
@@ -240,11 +249,85 @@ pub(crate) fn commit(r: &Repo, message: &str, amend: bool, sign_off: bool) -> Id
args.extend(["-F", "-"]);
Some(message.as_bytes())
};
run(r.root(), &args, stdin)?;
if options.partial.is_empty() {
run(r.root(), &args, stdin)?;
} else {
commit_partial(r, &args, stdin, &options.partial)?;
}
let repo = r.gix()?;
Ok(repo.head_id().map_err(gx)?.detach().to_string())
}
/// Removes the temporary index however the partial commit ends.
struct TempIndex(PathBuf);
impl Drop for TempIndex {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
let _ = std::fs::remove_file(self.0.with_extension("lock"));
}
}
/// Commits the index with only the chosen hunks of `partial` files, through a copy of the
/// index (`GIT_INDEX_FILE`), as IDEA's partial commit does: the working tree and the
/// user's index are left alone except that the partial files' entries end up matching
/// the new commit.
fn commit_partial(
r: &Repo,
commit_args: &[&str],
stdin: Option<&[u8]>,
partial: &[crate::PartialCommitFile],
) -> IdeResult<()> {
let tmp = TempIndex(r.git_dir.join("openidea-partial-index"));
let index = r.git_dir.join("index");
if index.exists() {
std::fs::copy(&index, &tmp.0)?;
}
let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
let mut rels = Vec::new();
for file in partial {
let rel = r.rel_path(&file.path.0)?;
let head = {
let repo = r.gix()?;
crate::repo::blob_at(&repo, &rel, "HEAD")?
}
.ok_or_else(|| {
IdeError::invalid(format!("{rel}: only changes of a file in HEAD can be committed partially"))
})?;
let disk = std::fs::read(r.abs_path(&rel))?;
if head.contains(&0) || disk.contains(&0) {
return Err(IdeError::invalid(format!("{rel}: binary files cannot be committed partially")));
}
let (head, disk) = (String::from_utf8_lossy(&head), String::from_utf8_lossy(&disk));
let hunks = crate::diff::line_hunks(&head, &disk);
let mut selected = Vec::new();
for want in &file.hunks {
let found = hunks.iter().position(|h| {
(h.start, h.lines, h.old_start, h.old_lines) == (want.start, want.lines, want.old_start, want.old_lines)
});
match found {
Some(i) => selected.push(i),
None => return Err(IdeError::invalid(format!("{rel} changed on disk; review its changes again"))),
}
}
cli::run_env(r.root(), &["--literal-pathspecs", "reset", "-q", "HEAD", "--", &rel], None, &env)?;
let patch = crate::diff::build_partial_patch(&rel, &head, &disk, &selected);
if !patch.is_empty() {
cli::run_env(
r.root(),
&["apply", "--cached", "--unidiff-zero", "--whitespace=nowarn", "--recount", "-"],
Some(patch.as_bytes()),
&env,
)?;
}
rels.push(rel);
}
cli::run_env(r.root(), commit_args, stdin, &env)?;
// The user's index still holds the partial files' previous entries: align them with
// the commit so the remaining changes show as unstaged, nothing as staged.
run_paths(r, &["reset", "-q", "HEAD"], &rels)
}
pub(crate) fn checkout(r: &Repo, branch: &str, create: bool) -> IdeResult<()> {
let branch = branch.trim();
if branch.is_empty() {
@@ -273,6 +356,128 @@ pub(crate) fn checkout(r: &Repo, branch: &str, create: bool) -> IdeResult<()> {
run(r.root(), &["switch", "--detach", branch], None).map(|_| ())
}
/// What a checkout of `branch` runs.
enum SwitchPlan {
Switch(Vec<String>),
/// `git rebase <remote> <local>`.
Rebase {
local: String,
remote: String,
},
Ahead {
local: String,
remote: String,
},
}
fn switch_plan(r: &Repo, branch: &str, create: bool, diverged: Option<DivergedLocal>) -> IdeResult<SwitchPlan> {
let args = |a: &[&str]| SwitchPlan::Switch(a.iter().map(|s| s.to_string()).collect());
if create {
return Ok(args(&["switch", "-c", branch]));
}
let repo = r.gix()?;
let exists = |name: &str| repo.try_find_reference(name).map_err(gx).map(|r| r.is_some());
if exists(&format!("refs/heads/{branch}"))? {
return Ok(args(&["switch", branch]));
}
if exists(&format!("refs/remotes/{branch}"))?
&& let Some((_, name)) = branch.split_once('/')
{
if !exists(&format!("refs/heads/{name}"))? {
return Ok(args(&["switch", "-c", name, "--track", branch]));
}
// IDEA: a local namesake that is merely behind is fast-forwarded; one with commits
// of its own needs the user's choice.
let range = format!("{branch}..refs/heads/{name}");
let ahead = run(r.root(), &["rev-list", "--count", &range], None)?.stdout_str().trim() != "0";
return Ok(match (ahead, diverged) {
(true, None) => SwitchPlan::Ahead { local: name.to_string(), remote: branch.to_string() },
(true, Some(DivergedLocal::Rebase)) => {
SwitchPlan::Rebase { local: name.to_string(), remote: branch.to_string() }
}
_ => args(&["switch", "-C", name, "--track", branch]),
});
}
// A tag or commit: detached HEAD.
resolve(&repo, branch)?;
Ok(args(&["switch", "--detach", branch]))
}
/// Files git refuses to overwrite with local changes, from its error message.
fn overwritten_files(stderr: &str) -> Option<Vec<String>> {
let mut lines =
stderr.lines().skip_while(|l| !l.contains("local changes to the following files would be overwritten"));
lines.next()?;
Some(lines.take_while(|l| l.starts_with('\t')).map(|l| l.trim().to_string()).collect())
}
pub(crate) fn checkout_with(
r: &Repo,
branch: &str,
create: bool,
options: &CheckoutOptions,
) -> IdeResult<CheckoutOutcome> {
let branch = branch.trim();
if branch.is_empty() {
return Err(IdeError::invalid("branch name is empty"));
}
if branch.starts_with('-') {
return Err(IdeError::invalid(format!("invalid revision '{branch}'")));
}
let mut args = match switch_plan(r, branch, create, options.diverged)? {
SwitchPlan::Ahead { local, remote } => return Ok(CheckoutOutcome::LocalBranchAhead { local, remote }),
SwitchPlan::Rebase { local, remote } => {
let out = cli::run_raw(r.root(), &["rebase", "--autostash", &remote, &local], None)?;
if out.code == Some(0) {
return Ok(CheckoutOutcome::Done);
}
let files = unmerged_paths(r)?;
if files.is_empty() {
return Err(cli::failure(&["rebase"], &out.stderr, &out.stdout, out.code));
}
return Ok(CheckoutOutcome::Conflicts { files });
}
SwitchPlan::Switch(args) => args,
};
if options.mode == CheckoutMode::Force {
args.push("--discard-changes".into());
}
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
let out = cli::run_raw(r.root(), &argv, None)?;
if out.code == Some(0) {
return Ok(CheckoutOutcome::Done);
}
let Some(files) = overwritten_files(&String::from_utf8_lossy(&out.stderr)) else {
return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
};
if options.mode != CheckoutMode::Smart {
return Ok(CheckoutOutcome::LocalChanges { files });
}
// Smart Checkout: stash → switch → unstash, like IDEA.
let before = stash_count(r)?;
run(r.root(), &["stash", "push", "-q", "-m", &format!("Uncommitted changes before checkout of {branch}")], None)?;
if stash_count(r)? == before {
return Err(IdeError::invalid("could not save the local changes"));
}
if let Err(e) = run(r.root(), &argv, None) {
run(r.root(), &["stash", "pop", "-q", "--index"], None)?;
return Err(e);
}
let pop = cli::run_raw(r.root(), &["stash", "pop", "-q"], None)?;
if pop.code == Some(0) {
return Ok(CheckoutOutcome::Done);
}
let files = unmerged_paths(r)?;
if files.is_empty() {
return Err(cli::failure(&["stash", "pop"], &pop.stderr, &pop.stdout, pop.code));
}
Ok(CheckoutOutcome::Conflicts { files })
}
fn stash_count(r: &Repo) -> IdeResult<usize> {
Ok(run(r.root(), &["stash", "list"], None)?.stdout_str().lines().count())
}
/// Creates `name` at `start` (default HEAD); a remote-tracking start point is tracked.
pub(crate) fn create_branch(r: &Repo, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> {
let name = name.trim();
@@ -335,6 +540,39 @@ pub(crate) fn delete_branch(r: &Repo, branch: &str, force: bool) -> IdeResult<()
run(r.root(), &["branch", if force { "-D" } else { "-d" }, "--", branch], None).map(|_| ())
}
pub(crate) fn delete_branch_restorable(r: &Repo, branch: &str) -> IdeResult<DeletedBranch> {
check_local_branch(r, branch)?;
let tip = run(r.root(), &["rev-parse", "--verify", "-q", &format!("refs/heads/{branch}^{{commit}}")], None)?
.stdout_str()
.trim()
.to_string();
let upstream =
cli::run_raw(r.root(), &["for-each-ref", "--format=%(upstream:short)", &format!("refs/heads/{branch}")], None)?
.stdout_str()
.trim()
.to_string();
let out = cli::run_raw(r.root(), &["branch", "-d", "--", branch], None)?;
let unmerged = match out.code {
Some(0) => false,
_ if String::from_utf8_lossy(&out.stderr).contains("not fully merged") => {
run(r.root(), &["branch", "-D", "--", branch], None)?;
true
}
code => return Err(cli::failure(&["branch"], &out.stderr, &out.stdout, code)),
};
Ok(DeletedBranch { name: branch.to_string(), tip, upstream: (!upstream.is_empty()).then_some(upstream), unmerged })
}
pub(crate) fn restore_branch(r: &Repo, deleted: &DeletedBranch) -> IdeResult<()> {
let tip = check_rev(&deleted.tip)?;
run(r.root(), &["branch", "--", &deleted.name, tip], None)?;
if let Some(upstream) = &deleted.upstream {
let target = format!("--set-upstream-to={upstream}");
run(r.root(), &["branch", &target, "--", &deleted.name], None)?;
}
Ok(())
}
pub(crate) fn rename_branch(r: &Repo, from: &str, to: &str) -> IdeResult<()> {
let to = to.trim();
if to.is_empty() {
@@ -472,15 +710,25 @@ pub(crate) fn push_branch(
r: &Repo,
branch: &str,
revision: Option<&str>,
target: Option<&str>,
force_with_lease: bool,
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
check_local_branch(r, branch)?;
let (remote, target, set_upstream) = match branch_upstream(r, branch) {
let (remote, mut name, set_upstream) = match branch_upstream(r, branch) {
Some((remote, name)) => (remote, name, false),
None => (push_remote(r)?, branch.to_string(), revision.is_none()),
};
if let Some(t) = target.map(str::trim).filter(|t| !t.is_empty()) {
let valid =
!t.starts_with('-') && cli::run_raw(r.root(), &["check-ref-format", "--branch", t], None)?.code == Some(0);
if !valid {
return Err(IdeError::invalid(format!("'{t}' is not a valid branch name")));
}
name = t.to_string();
}
let target = name;
let source = match revision {
Some(rev) => check_rev(rev)?.to_string(),
None => format!("refs/heads/{branch}"),
+52
Переглянути файл
@@ -106,6 +106,47 @@ fn rebase_conflict_then_continue() {
assert_eq!(fx.git(&["rev-parse", "HEAD~1"]), fx.git(&["rev-parse", "main"]));
}
#[test]
fn merge_versions_put_the_users_work_on_the_left() {
// Rebase: git's "ours" is main; the user's commit (topic) must be `ours` here.
let fx = diverged();
let repo = fx.repo();
let topic = fx.git(&["rev-parse", "topic"]);
assert!(repo.rebase("main").is_err());
let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
assert_eq!(v.ours.as_deref(), Some("topic\n"));
assert_eq!(v.theirs.as_deref(), Some("main\n"));
assert_eq!(v.base.as_deref(), Some("base\n"));
assert!(v.sides.reversed);
assert_eq!(v.sides.operation.as_deref(), Some("rebase"));
assert_eq!(v.sides.branch.as_deref(), Some("topic"));
assert_eq!(v.sides.other_branch.as_deref(), Some("main"));
assert_eq!(v.sides.commit.as_deref(), Some(&topic[..8]));
let (cancel, out) = quiet();
repo.abort_operation(&cancel, &out).unwrap();
// Merge: not swapped; the merged branch is named.
assert!(repo.merge("main").is_err());
let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
assert_eq!(v.ours.as_deref(), Some("topic\n"));
assert_eq!(v.theirs.as_deref(), Some("main\n"));
assert!(!v.sides.reversed);
assert_eq!(v.sides.branch.as_deref(), Some("topic"));
assert_eq!(v.sides.other_branch.as_deref(), Some("main"));
repo.abort_operation(&cancel, &out).unwrap();
// Cherry-pick: not swapped; the picked commit is named.
let main = fx.git(&["rev-parse", "main"]);
assert!(repo.cherry_pick(std::slice::from_ref(&main), &cancel, &out).is_err());
let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
assert_eq!(v.ours.as_deref(), Some("topic\n"));
assert!(!v.sides.reversed);
assert_eq!(v.sides.operation.as_deref(), Some("cherry-pick"));
assert_eq!(v.sides.commit.as_deref(), Some(&main[..8]));
repo.abort_operation(&cancel, &out).unwrap();
assert_eq!(repo.merge_sides().unwrap(), MergeSides { branch: Some("topic".into()), ..Default::default() });
}
#[test]
fn rebase_conflict_then_abort_and_skip() {
let fx = diverged();
@@ -262,6 +303,11 @@ fn compare_with_local_lists_differences() {
got,
vec![("a.txt", ChangeKind::Modified), ("b.txt", ChangeKind::Modified), ("c.txt", ChangeKind::Added)]
);
// Between two revisions the working tree does not count.
let files = fx.repo().diff_revisions(&one, "HEAD").unwrap();
let got: Vec<(&str, ChangeKind)> = files.iter().map(|f| (f.path.as_str(), f.kind)).collect();
assert_eq!(got, vec![("a.txt", ChangeKind::Modified), ("c.txt", ChangeKind::Added)]);
assert!(fx.repo().diff_revisions("-x", "HEAD").is_err());
}
#[test]
@@ -448,6 +494,12 @@ fn push_branch_and_up_to_revision() {
assert_eq!(git_in(&bare, &["rev-parse", "side"]), c2);
assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "side@{upstream}"]), "origin/side");
assert!(repo.push_branch("nope", None, false, &cancel, &out).is_err());
// An edited target: same remote, another branch name; the upstream stays as it was.
repo.push_branch_to("main", None, "review/main", false, &cancel, &out).unwrap();
assert_eq!(git_in(&bare, &["rev-parse", "review/main"]), c3);
assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "main@{upstream}"]), "origin/main");
assert!(repo.push_branch_to("main", None, "bad..name", false, &cancel, &out).is_err());
}
#[test]
+229
Переглянути файл
@@ -707,6 +707,28 @@ fn commit_amend_and_signoff() {
assert!(repo.commit("nothing", false, false).is_err());
}
#[test]
fn commit_with_author_and_without_hooks() {
let fx = Fixture::new();
fx.write("a", "1\n");
fx.commit_all("init");
let hook = fx.path(".git/hooks/pre-commit");
std::fs::write(&hook, "#!/bin/sh\nexit 1\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let repo = fx.repo();
fx.write("a", "2\n");
repo.stage(&[fx.path("a")]).unwrap();
let hooked = CommitOptions { run_hooks: true, ..Default::default() };
assert!(repo.commit_with("blocked", &hooked).is_err(), "the failing pre-commit hook runs");
let options = CommitOptions { author: Some(" Other <[email protected]> ".into()), ..Default::default() };
repo.commit_with("by other", &options).unwrap();
assert_eq!(fx.git(&["log", "-1", "--format=%an <%ae>"]), "Other <[email protected]>");
}
#[test]
fn checkout_create_detached_delete_rebase() {
let fx = Fixture::new();
@@ -748,6 +770,213 @@ fn checkout_create_detached_delete_rebase() {
assert!(repo.checkout("does-not-exist", false).is_err());
}
#[test]
fn smart_and_force_checkout_with_local_changes_in_the_way() {
let fx = Fixture::new();
fx.write("f.txt", "1\n2\n3\n4\n5\n");
fx.commit_all("base");
fx.git(&["checkout", "-q", "-b", "other"]);
fx.write("f.txt", "1\nother\n3\n4\n5\n");
fx.commit_all("other edit");
fx.git(&["checkout", "-q", "main"]);
let repo = fx.repo();
let opts = |mode| CheckoutOptions { mode, diverged: None };
// A non-conflicting local edit to a file the switch rewrites.
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
let outcome = repo.checkout_with("other", false, &opts(CheckoutMode::Normal)).unwrap();
assert_eq!(outcome, CheckoutOutcome::LocalChanges { files: vec!["f.txt".into()] });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"), "nothing changed");
assert_eq!(fx.read("f.txt"), "1\n2\n3\n4\nlocal\n");
let outcome = repo.checkout_with("other", false, &opts(CheckoutMode::Smart)).unwrap();
assert_eq!(outcome, CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n", "local change carried over");
assert!(repo.stashes().unwrap().is_empty(), "stash restored and dropped");
// A local edit that conflicts with the target: smart checkout leaves a conflict.
fx.git(&["checkout", "-q", "-f", "main"]);
fx.write("f.txt", "1\nmine\n3\n4\n5\n");
let outcome = repo.checkout_with("other", false, &opts(CheckoutMode::Smart)).unwrap();
assert_eq!(outcome, CheckoutOutcome::Conflicts { files: vec!["f.txt".into()] });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
assert_eq!(repo.stashes().unwrap().len(), 1, "git keeps the stash after a conflicting pop");
// Force discards the change in the way.
fx.git(&["reset", "-q", "--hard"]);
fx.git(&["stash", "drop", "-q"]);
fx.write("f.txt", "1\nmine\n3\n4\n5\n");
fx.write("untouched.txt", "new\n");
let outcome = repo.checkout_with("main", false, &opts(CheckoutMode::Force)).unwrap();
assert_eq!(outcome, CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.read("f.txt"), "1\n2\n3\n4\n5\n");
assert_eq!(fx.read("untouched.txt"), "new\n", "untracked files survive");
}
#[test]
fn checkout_remote_branch_with_existing_local_namesake() {
let (fx, bare) = with_remote();
let repo = fx.repo();
// Another clone advances origin/main.
let other = fx._tmp.path().join("other");
git_in(fx._tmp.path(), &["clone", "-q", bare.to_str().unwrap(), other.to_str().unwrap()]);
configure(&other);
std::fs::write(other.join("b.txt"), "remote\n").unwrap();
git_in(&other, &["add", "-A"]);
git_in(&other, &["commit", "-q", "-m", "remote work"]);
git_in(&other, &["push", "-q", "origin", "main"]);
fx.git(&["fetch", "-q"]);
fx.git(&["checkout", "-q", "-b", "topic"]);
let none = CheckoutOptions::default();
// Local main is only behind: it is fast-forwarded and checked out.
assert_eq!(repo.checkout_with("origin/main", false, &none).unwrap(), CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.git(&["rev-parse", "main"]), fx.git(&["rev-parse", "origin/main"]));
// Local main has its own commit: the user must choose; nothing changes meanwhile.
fx.write("c.txt", "local\n");
let local_tip = fx.commit_all("local work");
fx.git(&["checkout", "-q", "topic"]);
let outcome = repo.checkout_with("origin/main", false, &none).unwrap();
assert_eq!(outcome, CheckoutOutcome::LocalBranchAhead { local: "main".into(), remote: "origin/main".into() });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
// Rebase onto Remote keeps the local commit on top of origin/main.
let rebase = CheckoutOptions { diverged: Some(DivergedLocal::Rebase), ..Default::default() };
assert_eq!(repo.checkout_with("origin/main", false, &rebase).unwrap(), CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.git(&["rev-parse", "main~1"]), fx.git(&["rev-parse", "origin/main"]));
assert_eq!(fx.git(&["log", "-1", "--format=%s"]), "local work");
// Drop Local Commits resets main to origin/main.
fx.git(&["checkout", "-q", "topic"]);
let reset = CheckoutOptions { diverged: Some(DivergedLocal::Reset), ..Default::default() };
assert_eq!(repo.checkout_with("origin/main", false, &reset).unwrap(), CheckoutOutcome::Done);
assert_eq!(fx.git(&["rev-parse", "main"]), fx.git(&["rev-parse", "origin/main"]));
assert_ne!(fx.git(&["rev-parse", "main"]), local_tip);
assert_eq!(repo.branch_info().unwrap().upstream.as_deref(), Some("origin/main"));
}
#[test]
fn delete_branch_without_asking_and_restore_it() {
let (fx, _bare) = with_remote();
let repo = fx.repo();
fx.git(&["checkout", "-q", "-b", "merged", "--track", "origin/main"]);
fx.git(&["checkout", "-q", "-b", "work"]);
fx.write("w.txt", "work\n");
let work_tip = fx.commit_all("work");
fx.git(&["checkout", "-q", "main"]);
let merged = repo.delete_branch_restorable("merged").unwrap();
assert!(!merged.unmerged);
assert_eq!(merged.upstream.as_deref(), Some("origin/main"));
let work = repo.delete_branch_restorable("work").unwrap();
assert!(work.unmerged, "not fully merged branches are force-deleted and reported");
assert_eq!(work.tip, work_tip);
assert!(!repo.branches().unwrap().iter().any(|b| b.name == "work"));
assert!(repo.delete_branch_restorable("main").is_err(), "the current branch cannot be deleted");
repo.restore_branch(&work).unwrap();
repo.restore_branch(&merged).unwrap();
let branches = repo.branches().unwrap();
let find = |n: &str| branches.iter().find(|b| !b.remote && b.name == n).unwrap().clone();
assert_eq!(find("work").commit, work_tip);
assert_eq!(find("merged").upstream.as_deref(), Some("origin/main"));
}
fn range(h: &LineHunk) -> HunkRange {
HunkRange { start: h.start, lines: h.lines, old_start: h.old_start, old_lines: h.old_lines }
}
#[test]
fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() {
let fx = Fixture::new();
let base = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
fx.write("f.txt", base);
fx.write("other.txt", "o\n");
fx.write("staged.txt", "s\n");
fx.commit_all("base");
let repo = fx.repo();
let edited = "A\nb\nc\nd\ne\nf\ng\nh\ni\nJ\nk\n";
fx.write("f.txt", edited);
fx.write("other.txt", "o2\n");
fx.write("staged.txt", "s2\n");
repo.stage(&[fx.path("other.txt")]).unwrap();
let hunks = diff_hunks(base, edited);
assert_eq!(hunks.len(), 2);
// Commit the first hunk of f.txt plus the staged other.txt; staged.txt is not staged.
let options = CommitOptions {
partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }],
..Default::default()
};
repo.commit_with("partial", &options).unwrap();
assert_eq!(fx.git(&["show", "HEAD:f.txt"]), "A\nb\nc\nd\ne\nf\ng\nh\ni\nj");
assert_eq!(fx.git(&["show", "HEAD:other.txt"]), "o2");
assert_eq!(fx.git(&["show", "HEAD:staged.txt"]), "s");
// The working tree is untouched.
assert_eq!(fx.read("f.txt"), edited);
assert_eq!(fx.read("staged.txt"), "s2\n");
// The index matches the commit; the rest of f.txt is an unstaged change.
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "");
let st = repo.status().unwrap();
assert_eq!(status_of(&st, "f.txt").unstaged, Some(ChangeKind::Modified));
assert_eq!(status_of(&st, "f.txt").staged, None);
assert!(!fx.dir.join(".git/openidea-partial-index").exists());
// A stale hunk (the file changed since the UI computed it) refuses to commit anything.
let before = fx.git(&["rev-parse", "HEAD"]);
let stale = CommitOptions {
partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }],
..Default::default()
};
let err = repo.commit_with("stale", &stale).unwrap_err();
assert!(err.message.contains("changed"), "{}", err.message);
assert_eq!(fx.git(&["rev-parse", "HEAD"]), before);
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "");
assert!(!fx.dir.join(".git/openidea-partial-index").exists());
// The remaining hunk commits on its own; then nothing is left.
let rest = diff_hunks(&repo.file_at(&fx.path("f.txt"), None).unwrap().unwrap(), edited);
assert_eq!(rest.len(), 1);
let options = CommitOptions {
partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&rest[0])] }],
..Default::default()
};
repo.commit_with("rest", &options).unwrap();
assert_eq!(repo.file_at(&fx.path("f.txt"), None).unwrap().as_deref(), Some(edited));
assert!(repo.status().unwrap().iter().all(|f| f.rel_path != "f.txt"));
assert_eq!(fx.read("staged.txt"), "s2\n");
// A failing pre-commit hook leaves everything as it was.
fx.write("f.txt", "Z\nb\nc\nd\ne\nf\ng\nh\ni\nJ\nk\nl\n");
let hook = fx.dir.join(".git/hooks/pre-commit");
std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
std::fs::write(&hook, "#!/bin/sh\nexit 1\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let head = fx.git(&["rev-parse", "HEAD"]);
let hunks = diff_hunks(edited, &fx.read("f.txt"));
let options = CommitOptions {
run_hooks: true,
partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }],
..Default::default()
};
assert!(repo.commit_with("hooked", &options).is_err());
assert_eq!(fx.git(&["rev-parse", "HEAD"]), head);
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "");
assert_eq!(fx.read("f.txt"), "Z\nb\nc\nd\ne\nf\ng\nh\ni\nJ\nk\nl\n");
}
#[test]
fn partial_staging_with_built_patch() {
let fx = Fixture::new();
+8 -4
Переглянути файл
@@ -37,8 +37,10 @@ pub struct FileEntry {
pub size: u64,
/// Milliseconds since the Unix epoch.
pub mtime_ms: f64,
/// Matched by .gitignore / exclude settings (shown dimmed, like IDEA "excluded").
/// Matched by .gitignore or the exclude settings.
pub ignored: bool,
/// Matched by the exclude settings (IDEA's "excluded": dimmed, excluded-folder icon).
pub excluded: bool,
pub hidden: bool,
/// For symlinks: what the link points to (`None` when dangling); `None`
/// for other entries.
@@ -96,8 +98,8 @@ pub fn natural_cmp(a: &str, b: &str) -> Ordering {
/// case-insensitively with natural number ordering.
///
/// Symlinks are reported as [`EntryKind::Symlink`] but sorted (and sized) by
/// what they point to. `ignored` reflects `excludes` (relative to the enclosing
/// repository root, else to `dir`) and the applicable `.gitignore`/`.ignore` files.
/// what they point to. `excluded` reflects `excludes` (relative to the enclosing
/// repository root, else to `dir`); `ignored` also the applicable `.gitignore`/`.ignore` files.
pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
if !fs::metadata(dir)?.is_dir() {
return Err(IdeError::invalid(format!("{} is not a directory", dir.display())));
@@ -133,7 +135,8 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
};
let is_dir = meta.is_dir();
let rel = path.strip_prefix(&base).unwrap_or(&path);
let ignored = excludes.is_excluded(rel) || gitignore.is_ignored(&path, is_dir);
let excluded = excludes.is_excluded(rel);
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
entries.push((
is_dir,
FileEntry {
@@ -144,6 +147,7 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
path: path.into(),
kind,
ignored,
excluded,
target_kind,
},
));
+4 -1
Переглянути файл
@@ -71,6 +71,9 @@ fn read_dir_sorting_and_flags() {
assert!(get("build").ignored);
assert!(get("a.log").ignored);
assert!(get("node_modules").ignored);
// Excluded (settings) vs only git-ignored, like IDEA's excluded folders.
assert!(get("node_modules").excluded && get(".git").excluded);
assert!(!get("build").excluded && !get("a.log").excluded);
assert!(!get("src").ignored && !get("B.md").ignored && !get(".gitignore").ignored);
assert_eq!(get("src").kind, EntryKind::Dir);
assert_eq!(get("B.md").kind, EntryKind::File);
@@ -99,7 +102,7 @@ fn read_dir_sorting_and_flags() {
assert_eq!(ignored, BTreeSet::from(["local.txt", "other.log"]));
let nm = read_dir(&r.join("node_modules"), &excludes).unwrap();
assert!(nm.iter().all(|e| e.ignored), "children of excluded dirs are excluded");
assert!(nm.iter().all(|e| e.ignored && e.excluded), "children of excluded dirs are excluded");
assert_eq!(read_dir(&r.join("B.md"), &excludes).unwrap_err().kind, ErrorKind::InvalidInput);
assert_eq!(read_dir(&r.join("missing"), &excludes).unwrap_err().kind, ErrorKind::NotFound);
+21
Переглянути файл
@@ -0,0 +1,21 @@
[package]
name = "ide-web"
description = "Web browsers: the built-in static web server that serves project files on 127.0.0.1 (IDEA's built-in server) and detection / launching of installed browsers"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ide-core.workspace = true
open = "5"
parking_lot.workspace = true
percent-encoding = "2"
serde.workspace = true
specta.workspace = true
tokio = { workspace = true, features = ["net"] }
tracing.workspace = true
uuid.workspace = true
[dev-dependencies]
tempfile.workspace = true
tokio = { workspace = true, features = ["net", "rt-multi-thread", "macros"] }
+129
Переглянути файл
@@ -0,0 +1,129 @@
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
/// An installed browser.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Browser {
/// `chrome`, `firefox`, `safari`, `edge`, `brave`, `chromium`.
pub id: String,
pub name: String,
}
struct Known {
id: &'static str,
name: &'static str,
/// macOS application bundle names.
mac: &'static [&'static str],
/// Windows executables relative to Program Files / Local AppData.
windows: &'static [&'static str],
/// Linux commands on `PATH`.
linux: &'static [&'static str],
}
const KNOWN: &[Known] = &[
Known {
id: "chrome",
name: "Chrome",
mac: &["Google Chrome"],
windows: &[r"Google\Chrome\Application\chrome.exe"],
linux: &["google-chrome", "google-chrome-stable"],
},
Known {
id: "firefox",
name: "Firefox",
mac: &["Firefox", "Firefox Developer Edition"],
windows: &[r"Mozilla Firefox\firefox.exe"],
linux: &["firefox"],
},
Known { id: "safari", name: "Safari", mac: &["Safari"], windows: &[], linux: &[] },
Known {
id: "edge",
name: "Edge",
mac: &["Microsoft Edge"],
windows: &[r"Microsoft\Edge\Application\msedge.exe"],
linux: &["microsoft-edge", "microsoft-edge-stable"],
},
Known {
id: "brave",
name: "Brave",
mac: &["Brave Browser"],
windows: &[r"BraveSoftware\Brave-Browser\Application\brave.exe"],
linux: &["brave-browser", "brave"],
},
Known {
id: "chromium",
name: "Chromium",
mac: &["Chromium"],
windows: &[r"Chromium\Application\chrome.exe"],
linux: &["chromium", "chromium-browser"],
},
];
/// Where browser `k` is installed, if it is.
fn locate(k: &Known) -> Option<PathBuf> {
if cfg!(target_os = "macos") {
let mut dirs = vec![PathBuf::from("/Applications")];
if let Some(home) = std::env::var_os("HOME") {
dirs.push(PathBuf::from(home).join("Applications"));
}
// Safari moved into the cryptex; /Applications keeps a link to it.
dirs.push(PathBuf::from("/System/Volumes/Preboot/Cryptexes/App/System/Applications"));
k.mac.iter().flat_map(|app| dirs.iter().map(move |d| d.join(format!("{app}.app")))).find(|p| p.exists())
} else if cfg!(windows) {
let bases: Vec<PathBuf> = ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"]
.iter()
.filter_map(std::env::var_os)
.map(PathBuf::from)
.collect();
k.windows.iter().flat_map(|exe| bases.iter().map(move |b| b.join(exe))).find(|p| p.is_file())
} else {
let path = std::env::var_os("PATH")?;
let dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
k.linux.iter().flat_map(|cmd| dirs.iter().map(move |d| d.join(cmd))).find(|p| p.is_file())
}
}
/// The known browsers installed on this machine, in a fixed order.
pub fn installed() -> Vec<Browser> {
KNOWN.iter().filter(|k| locate(k).is_some()).map(|k| Browser { id: k.id.into(), name: k.name.into() }).collect()
}
/// Opens `url` in browser `id`, or in the system default browser.
pub fn open(url: &str, id: Option<&str>) -> IdeResult<()> {
if !(url.starts_with("http://") || url.starts_with("https://") || url.starts_with("file://")) {
return Err(IdeError::invalid(format!("not a web URL: {url}")));
}
let result = match id {
None => open::that_detached(url),
Some(id) => {
let known =
KNOWN.iter().find(|k| k.id == id).ok_or_else(|| IdeError::invalid(format!("unknown browser: {id}")))?;
let app = locate(known).ok_or_else(|| IdeError::unavailable(format!("{} is not installed", known.name)))?;
open::with_detached(url, app.to_string_lossy().as_ref())
}
};
result.map_err(|e| IdeError::unavailable(format!("cannot open the browser: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_are_unique() {
let mut ids: Vec<_> = KNOWN.iter().map(|k| k.id).collect();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), KNOWN.len());
}
#[test]
fn refuses_non_web_urls() {
assert!(open("/etc/passwd", None).is_err());
assert!(open("javascript:alert(1)", None).is_err());
assert!(open("http://127.0.0.1/", Some("netscape")).is_err());
}
}
+14
Переглянути файл
@@ -0,0 +1,14 @@
//! Web browsers, like IDEA's "Open In › Browser" and the editor's browser bar.
//!
//! [`WebServer`] is the built-in server: it serves project files read-only on
//! `127.0.0.1`, so pages opened from the IDE load relative scripts, styles and
//! ES modules the way they would from a real server. Every URL starts with a
//! random per-run token, and requests whose `Host` is not the server itself are
//! refused (DNS rebinding). [`installed`] lists the browsers found on this
//! machine and [`open`] launches one, or the system default.
mod browsers;
mod server;
pub use browsers::{Browser, installed, open};
pub use server::WebServer;
+355
Переглянути файл
@@ -0,0 +1,355 @@
use ide_core::{IdeError, IdeResult};
use parking_lot::RwLock;
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
/// IDEA's built-in server port, tried first so bookmarked URLs keep working.
const PREFERRED_PORT: u16 = 63342;
const MAX_HEAD: usize = 16 * 1024;
const READ_TIMEOUT: Duration = Duration::from_secs(10);
/// Characters escaped in one URL path segment.
const SEGMENT: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'%')
.add(b'/')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'^')
.add(b'`')
.add(b'{')
.add(b'|')
.add(b'}');
struct Shared {
token: String,
/// URL key (`/<token>/<key>/…`) → served directory.
roots: RwLock<HashMap<String, PathBuf>>,
}
/// The built-in web server; started on the first [`WebServer::url_for`].
pub struct WebServer {
shared: Arc<Shared>,
port: tokio::sync::OnceCell<u16>,
}
impl Default for WebServer {
fn default() -> Self {
Self::new()
}
}
impl WebServer {
pub fn new() -> Self {
Self {
shared: Arc::new(Shared { token: uuid::Uuid::new_v4().simple().to_string(), roots: RwLock::default() }),
port: tokio::sync::OnceCell::new(),
}
}
/// The URL serving `file`: under `root` (the project) when it contains the
/// file, else under the file's directory. Starts the server if needed.
pub async fn url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
let base = match root {
Some(r) if file.starts_with(r) && file != r => r,
_ => file.parent().ok_or_else(|| IdeError::invalid(format!("no directory: {}", file.display())))?,
};
let rel = file.strip_prefix(base).map_err(|e| IdeError::internal(e.to_string()))?;
let port = self.port().await?;
let key = self.register(base);
let mut url = format!("http://127.0.0.1:{port}/{}/{}", self.shared.token, enc(&key));
for c in rel.components() {
url.push('/');
url.push_str(&enc(&c.as_os_str().to_string_lossy()));
}
Ok(url)
}
/// The key `dir` is served under: its name, made unique.
fn register(&self, dir: &Path) -> String {
let mut roots = self.shared.roots.write();
if let Some((k, _)) = roots.iter().find(|(_, d)| d.as_path() == dir) {
return k.clone();
}
let name: String = dir
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
.chars()
.map(|c| if c.is_alphanumeric() || "._-".contains(c) { c } else { '_' })
.collect();
let name = if name.is_empty() || name == "." || name == ".." { "root".to_string() } else { name };
let key = (1..)
.map(|i| if i == 1 { name.clone() } else { format!("{name}-{i}") })
.find(|k| !roots.contains_key(k))
.expect("unbounded");
roots.insert(key.clone(), dir.to_path_buf());
key
}
async fn port(&self) -> IdeResult<u16> {
self.port
.get_or_try_init(|| async {
let listener = match TcpListener::bind(("127.0.0.1", PREFERRED_PORT)).await {
Ok(l) => l,
Err(_) => TcpListener::bind(("127.0.0.1", 0)).await?,
};
let port = listener.local_addr()?.port();
let shared = self.shared.clone();
tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((sock, _)) => {
let shared = shared.clone();
tokio::spawn(async move {
if let Err(e) = serve(sock, &shared, port).await {
tracing::debug!("web server: {e}");
}
});
}
Err(e) => {
tracing::warn!("web server accept: {e}");
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
});
tracing::info!("built-in web server on 127.0.0.1:{port}");
Ok::<_, std::io::Error>(port)
})
.await
.copied()
.map_err(|e| IdeError::unavailable(format!("cannot start the built-in web server: {e}")))
}
}
fn enc(s: &str) -> String {
utf8_percent_encode(s, SEGMENT).to_string()
}
struct Request {
method: String,
target: String,
host: Option<String>,
}
async fn read_head(sock: &mut TcpStream) -> std::io::Result<Option<Request>> {
let mut reader = BufReader::new(sock).take(MAX_HEAD as u64);
let mut line = String::new();
if reader.read_line(&mut line).await? == 0 {
return Ok(None);
}
let mut parts = line.split_whitespace();
let (Some(method), Some(target)) = (parts.next(), parts.next()) else { return Ok(None) };
let (method, target) = (method.to_string(), target.to_string());
let mut host = None;
loop {
line.clear();
if reader.read_line(&mut line).await? == 0 {
return Ok(None);
}
let l = line.trim_end();
if l.is_empty() {
break;
}
if let Some((name, value)) = l.split_once(':')
&& name.eq_ignore_ascii_case("host")
{
host = Some(value.trim().to_ascii_lowercase());
}
}
Ok(Some(Request { method, target, host }))
}
enum Response {
File { path: PathBuf, len: u64 },
Redirect(String),
Error(u16, &'static str),
}
async fn serve(mut sock: TcpStream, shared: &Shared, port: u16) -> std::io::Result<()> {
let Ok(head) = tokio::time::timeout(READ_TIMEOUT, read_head(&mut sock)).await else { return Ok(()) };
let Some(req) = head? else { return Ok(()) };
let head_only = req.method == "HEAD";
let response = if !matches!(req.method.as_str(), "GET" | "HEAD") {
Response::Error(405, "Method Not Allowed")
} else if !host_allowed(req.host.as_deref(), port) {
Response::Error(403, "Forbidden")
} else {
resolve(shared, &req.target).await
};
let mut out = String::new();
match &response {
Response::File { path, len } => {
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)));
}
Response::Redirect(to) => {
out.push_str(&format!("HTTP/1.1 301 Moved Permanently\r\nLocation: {to}\r\nContent-Length: 0\r\n"));
}
Response::Error(code, reason) => {
out.push_str(&format!(
"HTTP/1.1 {code} {reason}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\n",
reason.len()
));
}
}
out.push_str("Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n");
sock.write_all(out.as_bytes()).await?;
if !head_only {
match response {
Response::File { path, .. } => {
let mut file = tokio::fs::File::open(&path).await?;
tokio::io::copy(&mut file, &mut sock).await?;
}
Response::Error(_, reason) => sock.write_all(reason.as_bytes()).await?,
Response::Redirect(_) => {}
}
}
sock.shutdown().await
}
fn host_allowed(host: Option<&str>, port: u16) -> bool {
host.is_some_and(|h| h == format!("127.0.0.1:{port}") || h == format!("localhost:{port}"))
}
async fn resolve(shared: &Shared, target: &str) -> Response {
const NOT_FOUND: Response = Response::Error(404, "Not Found");
let path = target.split(['?', '#']).next().unwrap_or("");
let Some(rest) = path.strip_prefix('/') else { return NOT_FOUND };
let mut segments = rest.split('/');
if segments.next() != Some(shared.token.as_str()) {
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;
for seg in segments {
trailing_slash = seg.is_empty();
if seg.is_empty() {
continue;
}
match dec(seg) {
Some(s) if s != "." && s != ".." && !s.contains(['/', '\\', ':', '\0']) => file.push(s),
_ => return NOT_FOUND,
}
}
let Ok(meta) = tokio::fs::metadata(&file).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() },
_ => NOT_FOUND,
};
}
Response::File { path: file, len: meta.len() }
}
fn dec(s: &str) -> Option<String> {
percent_decode_str(s).decode_utf8().ok().map(|s| s.into_owned())
}
fn content_type(path: &Path) -> &'static str {
let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
match ext.as_str() {
"html" | "htm" | "xhtml" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" | "mjs" | "cjs" => "text/javascript; charset=utf-8",
"json" | "map" | "webmanifest" => "application/json; charset=utf-8",
"xml" => "application/xml; charset=utf-8",
"txt" | "md" | "csv" => "text/plain; charset=utf-8",
"svg" => "image/svg+xml",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"avif" => "image/avif",
"ico" => "image/x-icon",
"bmp" => "image/bmp",
"woff" => "font/woff",
"woff2" => "font/woff2",
"ttf" => "font/ttf",
"otf" => "font/otf",
"wasm" => "application/wasm",
"pdf" => "application/pdf",
"mp4" => "video/mp4",
"webm" => "video/webm",
"mp3" => "audio/mpeg",
"wav" => "audio/wav",
"ogg" => "audio/ogg",
_ => "application/octet-stream",
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn get(url: &str, host: Option<&str>) -> String {
let rest = url.strip_prefix("http://").unwrap();
let (authority, path) = rest.split_at(rest.find('/').unwrap());
let mut sock = TcpStream::connect(authority).await.unwrap();
let host = host.unwrap_or(authority);
sock.write_all(format!("GET {path} HTTP/1.1\r\nHost: {host}\r\n\r\n").as_bytes()).await.unwrap();
let mut out = String::new();
sock.read_to_string(&mut out).await.unwrap();
out
}
#[tokio::test]
async fn serves_project_files() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("my app");
std::fs::create_dir_all(root.join("web/sub")).unwrap();
std::fs::write(root.join("web/index.html"), "<h1>hi</h1>").unwrap();
std::fs::write(root.join("web/sub/a b.js"), "export {}").unwrap();
std::fs::write(dir.path().join("secret.txt"), "no").unwrap();
let server = WebServer::new();
let url = server.url_for(Some(&root), &root.join("web/index.html")).await.unwrap();
assert!(url.ends_with("/my_app/web/index.html"), "{url}");
let page = get(&url, None).await;
assert!(page.starts_with("HTTP/1.1 200"), "{page}");
assert!(page.contains("text/html") && page.ends_with("<h1>hi</h1>"));
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: /"));
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"));
assert!(get(&format!("{base}/web/..%2f..%2fsecret.txt"), None).await.starts_with("HTTP/1.1 404"));
// Wrong token, foreign Host (DNS rebinding).
let other = url.replacen(&server.shared.token, "0123", 1);
assert!(get(&other, None).await.starts_with("HTTP/1.1 404"));
assert!(get(&url, Some("evil.example:80")).await.starts_with("HTTP/1.1 403"));
}
#[tokio::test]
async fn files_outside_the_project_get_their_own_root() {
let dir = tempfile::tempdir().unwrap();
let (a, b) = (dir.path().join("x/site"), dir.path().join("y/site"));
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
let server = WebServer::new();
let ua = server.url_for(None, &a.join("p.html")).await.unwrap();
let ub = server.url_for(Some(&a), &b.join("p.html")).await.unwrap();
assert!(ua.ends_with("/site/p.html") && ub.ends_with("/site-2/p.html"), "{ua} {ub}");
assert_eq!(server.url_for(None, &a.join("q.html")).await.unwrap(), ua.replace("p.html", "q.html"));
}
}
+212
Переглянути файл
@@ -0,0 +1,212 @@
//! File references in text (`href="css/a.css"`, `url(../img/x.png)`,
//! `open("data/x.csv")`), resolved like IDEA's file references: relative to the
//! referencing file, `/`-rooted paths against the project root and its resource
//! roots (`public/`, `src/main/resources`), which web servers serve at `/`.
use std::path::{Component, Path, PathBuf};
/// Whether `value` names a local file at all (not a URL, an anchor, a data URI
/// or a template expression), so an unresolved one is worth reporting.
pub fn is_file_reference(value: &str) -> bool {
let v = value.trim();
!(v.is_empty()
|| v.starts_with('#')
|| v.starts_with("//")
|| v.starts_with('~')
|| has_scheme(v)
|| ["{{", "${", "<%", "{%", "<?", "@{"].iter().any(|t| v.contains(t)))
}
/// `http:`, `mailto:`, `data:`, `javascript:`… (a Windows drive `C:` is a path).
fn has_scheme(v: &str) -> bool {
match v.find(':') {
Some(i) if i > 1 => v[..i].chars().all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)),
_ => false,
}
}
/// The path part: no `?query` / `#fragment`, percent-decoded.
pub fn path_part(value: &str) -> String {
let bare = value.trim().split(['?', '#']).next().unwrap_or_default();
percent_decode(bare)
}
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = s.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8(out).unwrap_or_else(|_| s.to_owned())
}
/// Removes `.` and resolves `..` lexically.
fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in path.components() {
match c {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
out.push("..");
}
}
other => out.push(other),
}
}
out
}
/// Directories a reference's path is looked up in, most likely first.
pub fn base_dirs(path: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Vec<PathBuf> {
// A file outside the project is not served from its roots.
let root = root.filter(|r| from.starts_with(r));
let mut dirs: Vec<PathBuf> = Vec::new();
if path.starts_with('/') {
dirs.extend(root.map(Path::to_path_buf));
if root.is_some() {
dirs.extend(resource_roots.iter().cloned());
}
dirs.push(PathBuf::from("/"));
} else {
dirs.extend(from.parent().map(Path::to_path_buf));
// `img/a.png` from a page served at the root; never for `./` or `../`.
if !path.starts_with('.') {
dirs.extend(root.map(Path::to_path_buf));
}
}
let mut seen = Vec::new();
dirs.retain(|d| {
let fresh = !seen.contains(d);
seen.push(d.clone());
fresh
});
dirs
}
/// Paths `value` may point at, most likely first.
pub fn candidates(value: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Vec<PathBuf> {
let path = path_part(value);
let rel = path.trim_start_matches('/');
base_dirs(&path, from, root, resource_roots).iter().map(|d| normalize(&d.join(rel))).collect()
}
/// The existing file or directory `value` names, if any.
pub fn resolve(value: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Option<PathBuf> {
if !is_file_reference(value) || path_part(value).is_empty() {
return None;
}
candidates(value, from, root, resource_roots).into_iter().find(|p| p.exists())
}
/// An entry offered when completing a path.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct PathCompletion {
pub name: String,
pub dir: bool,
}
/// Entries of the directories `prefix` (the path typed so far) continues in:
/// the part before its last `/`, looked up like a reference. Dot files only
/// when the last segment starts with `.`.
pub fn complete(prefix: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Vec<PathCompletion> {
let prefix = percent_decode(prefix);
let (dir_part, last) = prefix.rsplit_once('/').map_or(("", prefix.as_str()), |(d, l)| (d, l));
let dir_value =
if prefix.starts_with('/') { format!("/{}", dir_part.trim_start_matches('/')) } else { dir_part.to_owned() };
let show_hidden = last.starts_with('.');
let rel = dir_value.trim_start_matches('/');
let mut out: Vec<PathCompletion> = Vec::new();
for base in base_dirs(&dir_value, from, root, resource_roots) {
// The file system root only as a last resort for `/` paths.
if base == Path::new("/") && !out.is_empty() {
continue;
}
let Ok(entries) = std::fs::read_dir(normalize(&base.join(rel))) else { continue };
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
if (name.starts_with('.') && !show_hidden) || out.iter().any(|c| c.name == name) {
continue;
}
let dir = e.file_type().is_ok_and(|t| t.is_dir()) || e.path().is_dir();
out.push(PathCompletion { name, dir });
}
}
out.sort_by(|a, b| b.dir.cmp(&a.dir).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())));
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn what_counts_as_a_file_reference() {
for v in ["a.css", "./a", "../img/x.png", "/splash.css", "a%20b.png?v=1#x", "C:/x"] {
assert!(is_file_reference(v), "{v}");
}
for v in [
"",
"#top",
"https://x.org",
"//cdn.x/a.js",
"mailto:a@b",
"data:image/png;base64,x",
"{{ url }}",
"${base}/a.js",
"~/x",
] {
assert!(!is_file_reference(v), "{v}");
}
assert_eq!(path_part(" img/a%20b.png?v=2#i "), "img/a b.png");
}
#[cfg(unix)]
#[test]
fn candidates_follow_ideas_rules() {
let from = Path::new("/p/web/pages/index.html");
let root = Some(Path::new("/p"));
let res = [PathBuf::from("/p/public")];
let s = |v| candidates(v, from, root, &res).into_iter().map(|p| p.display().to_string()).collect::<Vec<_>>();
assert_eq!(s("../img/a.png"), ["/p/web/img/a.png"]);
assert_eq!(s("img/a.png"), ["/p/web/pages/img/a.png", "/p/img/a.png"]);
assert_eq!(s("/splash.css"), ["/p/splash.css", "/p/public/splash.css", "/splash.css"]);
}
#[test]
fn resolves_and_completes_against_the_file_system() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for f in ["web/index.html", "web/css/a.css", "web/css/.hidden", "public/splash.css", "public/img/logo.svg"] {
let p = root.join(f);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "").unwrap();
}
let from = root.join("web/index.html");
let res = [root.join("public")];
let r = |v| resolve(v, &from, Some(root), &res);
assert_eq!(r("css/a.css?v=1"), Some(root.join("web/css/a.css")));
assert_eq!(r("/splash.css"), Some(root.join("public/splash.css")));
assert_eq!(r("css/missing.css"), None);
assert_eq!(r("https://x.org/a.css"), None);
let names = |p| complete(p, &from, Some(root), &res).into_iter().map(|c| (c.name, c.dir)).collect::<Vec<_>>();
assert_eq!(names("css/"), [("a.css".into(), false)]);
assert_eq!(names("css/."), [(".hidden".into(), false), ("a.css".into(), false)]);
assert_eq!(
names("/im"),
[("img".into(), true), ("public".into(), true), ("web".into(), true), ("splash.css".into(), false)]
);
assert_eq!(names("/img/"), [("logo.svg".into(), false)]);
}
}
+1
Переглянути файл
@@ -5,6 +5,7 @@ pub mod documents;
pub mod editorconfig;
pub mod file_defaults;
pub mod file_moves;
pub mod file_refs;
pub mod history;
pub mod memory;
pub mod process;
+4
Переглянути файл
@@ -192,6 +192,8 @@ fn module_roots(root: &Path, rel: &str, files: &[String], out: &mut Vec<SourceFo
// A JVM build's `src` holds source sets, not JavaScript.
if !has("pom.xml") && !GRADLE_FILES.iter().any(|f| has(f)) {
add("src", RootKind::Source, "package.json");
// Served at `/` by Vite, Next and Create React App: `href="/logo.svg"` resolves here.
add("public", RootKind::Resources, "package.json");
for t in ["test", "tests", "__tests__"] {
add(t, RootKind::Test, "package.json");
}
@@ -330,6 +332,7 @@ mod tests {
"flat/tests/",
"web/package.json",
"web/src/",
"web/public/",
"web/__tests__/",
"web/node_modules/x/package.json",
"web/dist/",
@@ -351,6 +354,7 @@ mod tests {
"web/__tests__=Test@web/package.json",
"web/dist=Excluded@web/package.json",
"web/node_modules=Excluded@web/package.json",
"web/public=Resources@web/package.json",
"web/src=Source@web/package.json",
]
);
+5
Переглянути файл
@@ -107,6 +107,11 @@ impl ProjectRoots {
}
}
/// Effective resource folders (project-relative): served at `/` for web file references.
pub fn resource_dirs(&self) -> Vec<&str> {
self.roots.iter().filter(|r| r.kind == RootKind::Resources).map(|r| r.path.as_str()).collect()
}
/// Effective excluded folders as anchored globs (`/target`), for the index, watcher and search.
pub fn excluded_globs(&self) -> Vec<String> {
self.roots
+1 -1
Переглянути файл
@@ -20,7 +20,7 @@ test("Search Everywhere finds and runs an action", async ({ workbench: page }) =
await expect(option).toBeVisible();
await page.keyboard.press("Enter");
await expect(page.getByRole("dialog", { name: "Settings" })).toBeVisible();
await expect(page.getByRole("table", { name: /language servers/i })).toBeVisible();
await expect(page.getByRole("list", { name: /language servers/i })).toBeVisible();
});
test("Search Everywhere finds a file and opens it", async ({ workbench: page }) => {
+12 -10
Переглянути файл
@@ -17,17 +17,19 @@ test("Language Servers page installs a tool with progress (in-memory installer)"
// The page tree is virtualized; search brings the page into view.
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Language Servers");
await dialog.getByRole("treeitem", { name: "Language Servers", exact: true }).click();
const table = dialog.getByRole("table", { name: /language servers/i });
await expect(table).toBeVisible();
const list = dialog.getByRole("list", { name: /language servers/i });
await expect(list).toBeVisible();
const row = table.locator('tr[data-tool="gopls"]');
await expect(row).toContainText("Missing");
await row.getByRole("button", { name: "Install gopls" }).click();
await expect(table.getByRole("progressbar", { name: "Installing gopls" })).toBeVisible();
await expect(row).toContainText("Installed");
await expect(row).toContainText("1.0.0");
await expect(row.getByRole("button", { name: "Uninstall gopls" })).toBeVisible();
await list.locator('[data-tool="gopls"]').click();
const details = dialog.getByLabel("gopls details");
await expect(details).toContainText("Missing");
await details.getByRole("button", { name: "Install gopls" }).click();
await expect(details.getByRole("progressbar", { name: "Installing gopls" })).toBeVisible();
await expect(details).toContainText("Installed");
await expect(details).toContainText("1.0.0");
await expect(details.getByRole("button", { name: "Uninstall" })).toBeVisible();
// Tools without an installer explain how to get them.
await expect(table).toContainText("gem install solargraph");
await list.locator('[data-tool="solargraph"]').click();
await expect(dialog.getByLabel("solargraph details")).toContainText("gem install solargraph");
});
+1 -1
Переглянути файл
@@ -16,7 +16,7 @@
<rect x="43" y="18" width="8" height="28" rx="1.5" fill="#FF4F1A" />
</svg>
<span>OpenIDEA</span>
<div class="splash-bar" role="progressbar" aria-label="Loading"></div>
<div class="splash-bar" role="progressbar" aria-label="Loading"><i></i></div>
</div>
<script type="module" src="/src/main.tsx"></script>
</body>
+1 -1
Переглянути файл
@@ -14,6 +14,6 @@ root-markers = ["mix.exs"]
install-hint = "Install ElixirLS (https://github.com/elixir-lsp/elixir-ls/releases) and expose language_server.sh as `elixir-ls`"
[debugger]
adapter = "elixir-ls"
adapter = "elixir-ls-debugger"
command = "elixir-ls-debugger"
install-hint = "Install ElixirLS and expose debug_adapter.sh as `elixir-ls-debugger`"
+2 -2
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.4",
"version": "0.1.12",
"license": "Apache-2.0",
"type": "module",
"scripts": {
@@ -41,12 +41,12 @@
"@tauri-apps/plugin-opener": "^2",
"@xterm/addon-fit": "^0.11.0",
"@xterm/addon-search": "^0.16.0",
"@xterm/addon-webgl": "^0.19.0",
"@xterm/xterm": "^6.0.0",
"anser": "^2.3.5",
"clsx": "^2.1.1",
"codemirror": "^6.0.2",
"dompurify": "^3.4.17",
"emmet": "2.4.11",
"immer": "^11.1.21",
"marked": "^18.1.1",
"react": "^19.1.0",
Створено
+30 -8
Переглянути файл
@@ -65,9 +65,6 @@ importers:
'@xterm/addon-search':
specifier: ^0.16.0
version: 0.16.0
'@xterm/addon-webgl':
specifier: ^0.19.0
version: 0.19.0
'@xterm/xterm':
specifier: ^6.0.0
version: 6.0.0
@@ -83,6 +80,9 @@ importers:
dompurify:
specifier: ^3.4.17
version: 3.4.17
emmet:
specifier: 2.4.11
version: 2.4.11
immer:
specifier: ^11.1.21
version: 11.1.21
@@ -386,6 +386,15 @@ packages:
resolution: {integrity: sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==}
engines: {node: '>=20.19.0'}
'@emmetio/[email protected]':
resolution: {integrity: sha512-mgv58UrU3rh4YgbE/TzgLQwJ3pFsHHhCLqY20aJq+9comytTXUDNGG/SMtSeMJdkpxgXSXunBGLD8Boka3JyVA==}
'@emmetio/[email protected]':
resolution: {integrity: sha512-s9yjhJ6saOO/uk1V74eifykk2CBYi01STTK3WlXWGOepyKa23ymJ053+DNQjpFcy1ingpaO7AxCcwLvHFY9tuw==}
'@emmetio/[email protected]':
resolution: {integrity: sha512-IqRuJtQff7YHHBk4G8YZ45uB9BaAGcwQeVzgj/zj8/UdOhtQpEIupUhSk8dys6spFIWVZVeK20CzGEnqR5SbqA==}
'@eslint-community/[email protected]':
resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
@@ -918,9 +927,6 @@ packages:
'@xterm/[email protected]':
resolution: {integrity: sha512-9OeuBFu0/uZJPu+9AHKY6g/w0Czyb/Ut0A5t79I4ULoU4IfU5BEpPFVGQxP4zTTMdfZEYkVIRYbHBX1xWwjeSA==}
'@xterm/[email protected]':
resolution: {integrity: sha512-b3fMOsyLVuCeNJWxolACEUED0vm7qC0cy4wRvf3oURSzDTYVQiGPhTnhWZwIHdvC48Y+oLhvYXnY4XDXPoJo6A==}
'@xterm/[email protected]':
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
@@ -1056,6 +1062,9 @@ packages:
[email protected]:
resolution: {integrity: sha512-4SC9HHSFjO/liAhifpdOL5hG9b4BP7/5G3y3UPZVO8trlAXr1CaUEEJL0gWK3kOcYcZrOA5rkwG45Gra/lTIgg==}
[email protected]:
resolution: {integrity: sha512-23QPJB3moh/U9sT4rQzGgeyyGIrcM+GH5uVYg2C6wZIxAIJq7Ng3QLT79tl8FUwDXhyq9SusfknOrofAKqvgyQ==}
[email protected]:
resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==}
engines: {node: '>=20.19.0'}
@@ -2162,6 +2171,16 @@ snapshots:
'@csstools/[email protected]': {}
'@emmetio/[email protected]':
dependencies:
'@emmetio/scanner': 1.0.4
'@emmetio/[email protected]':
dependencies:
'@emmetio/scanner': 1.0.4
'@emmetio/[email protected]': {}
'@eslint-community/[email protected]([email protected])':
dependencies:
eslint: 10.13.0
@@ -2657,8 +2676,6 @@ snapshots:
'@xterm/[email protected]': {}
'@xterm/[email protected]': {}
'@xterm/[email protected]': {}
[email protected]([email protected]):
@@ -2780,6 +2797,11 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
'@emmetio/abbreviation': 2.3.3
'@emmetio/css-abbreviation': 2.1.8
[email protected]: {}
[email protected]: {}
+5 -1
Переглянути файл
@@ -1,4 +1,4 @@
/* global document, localStorage */
/* global document, localStorage, window */
// Runs before the app's CSS loads: restores the last theme (theme.ts stores it)
// so a new window starts in it instead of flashing the light default.
// An external file because the CSP forbids inline scripts.
@@ -9,3 +9,7 @@ try {
} catch {
/* storage unavailable */
}
// Settings windows (`settings-<parent>`) load this page too: splash.css drops the logo for them.
if (window.__TAURI_INTERNALS__?.metadata?.currentWindow?.label?.startsWith("settings-")) {
document.documentElement.dataset.window = "settings";
}
+12 -7
Переглянути файл
@@ -2,7 +2,8 @@
which voids style-src 'unsafe-inline' and blocks the editor's runtime-injected styles. */
/* Start-up splash over the page until the window's launch project is open (platform/splash.ts).
Tokens aren't loaded yet, so the colours mirror --bg-frame / --fg-muted / --accent. */
html, body, .splash { background: #e9eaee; }
/* Not on html: the canvas then takes body's (themed) background, which a fast resize shows before relayout. */
body, .splash { background: #e9eaee; }
:root[data-theme="dark"] :is(body, .splash) { background: #26282c; }
:root:is([data-theme="dark-hc"], [data-theme="dark"][data-contrast="high"]) :is(body, .splash) { background: #1a1b1e; }
.splash {
@@ -28,16 +29,20 @@ html, body, .splash { background: #e9eaee; }
:root[data-theme^="dark"] .splash { color: #8c8f95; }
.splash svg { width: 56px; height: 56px; }
.splash-bar { width: 120px; height: 2px; border-radius: 1px; overflow: hidden; background: rgb(127 127 127 / 0.18); }
.splash-bar::after {
content: "";
/* Fake progress: eases towards ~90% over the 4 s cap; hideSplash() fills it before fading out. */
.splash-bar > i {
display: block;
width: 40%;
height: 100%;
background: #3871e1;
animation: splash-bar 1.1s ease-in-out infinite;
transform-origin: left;
animation: splash-fill 4s cubic-bezier(0.1, 0.7, 0.3, 1) both;
}
/* Settings window: a dialog, not a launch. Only the bar, and only if loading takes a while. */
:root[data-window="settings"] .splash { animation-delay: 400ms; }
:root[data-window="settings"] .splash > :not(.splash-bar) { display: none; }
@keyframes splash-in { from { opacity: 0; } }
@keyframes splash-bar { from { transform: translateX(-100%); } to { transform: translateX(250%); } }
@keyframes splash-fill { from { transform: scaleX(0.04); } to { transform: scaleX(0.92); } }
/* The fill stays: it grows in place, which reduced motion allows. */
@media (prefers-reduced-motion: reduce) {
.splash, .splash-bar::after { animation: none; }
.splash { animation: none; }
}
+1
Переглянути файл
@@ -53,6 +53,7 @@ ide-coverage.workspace = true
ide-profiler.workspace = true
ide-http.workspace = true
ide-db.workspace = true
ide-web.workspace = true
ide-tools = { path = "../crates/ide-tools" }
ide-plugin = { path = "../crates/ide-plugin" }
ide-docker = { path = "../crates/ide-docker" }
+1
Переглянути файл
@@ -16,6 +16,7 @@
"core:window:allow-set-title",
"core:window:allow-set-background-color",
"core:webview:allow-set-webview-zoom",
"core:webview:allow-set-webview-background-color",
"opener:default",
"opener:allow-reveal-item-in-dir",
"dialog:default",
+11 -3
Переглянути файл
@@ -71,7 +71,7 @@ pub async fn open_project(window: Window, path: PathBuf) -> IdeResult<ProjectInf
fn project_info(project: &crate::state::Project) -> ProjectInfo {
ProjectInfo {
name: project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
is_git: project.repo.lock().is_some(),
is_git: !project.repos.read().is_empty(),
settings: project.settings.effective(),
root: project.root.clone().into(),
}
@@ -109,6 +109,14 @@ pub fn settings_get(window: Window, state: State<'_, AppState>) -> Settings {
}
}
/// Defaults plus the global layer, without any project's values: what new
/// projects (and projects without their own value) get.
#[tauri::command]
#[specta::specta]
pub fn settings_get_global(state: State<'_, AppState>) -> Settings {
state.global_settings.effective()
}
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
/// value: that project's windows) is told (`IdeEvent::SettingsChanged`) so it
/// re-reads its effective settings.
@@ -148,8 +156,8 @@ pub fn settings_set(
.set_file_defaults(ide_workspace::FileDefaults::from_settings(&effective, Some(&project.root)));
}
}
// A new interpreter / toolchain restarts the language servers it affects.
if key == "languages" || key.starts_with("languages.") {
// A new interpreter / toolchain / server executable restarts the language servers it affects.
if ["languages", "tools"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
let affected = if project_scope { current.iter().cloned().collect() } else { state.projects() };
for project in affected {
let lsp = project.lsp.clone();
+32 -14
Переглянути файл
@@ -4,6 +4,7 @@
use crate::state::AppState;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
use ide_core::settings::Settings;
use ide_core::{IdeError, IdeEvent, IdeResult, RequestId};
use std::collections::BTreeMap;
use std::path::Path;
@@ -14,22 +15,32 @@ fn join_err(e: tauri::Error) -> IdeError {
IdeError::internal(e.to_string())
}
/// `JAVA_HOME` of the installed JDK matching `release` (none when the project names no version).
fn java_env(release: Option<u32>) -> BTreeMap<String, String> {
/// `JAVA_HOME`: the project JDK, else the installed JDK matching `release` (none
/// when the project names no version).
fn java_env(project_jdk: Option<&ide_sdk::java::Jdk>, release: Option<u32>) -> BTreeMap<String, String> {
let jdks = ide_sdk::java::installed_jdks();
let jdk = release.and_then(|r| ide_sdk::java::pick_jdk(&jdks, Some(r)));
let jdk = project_jdk.or_else(|| release.and_then(|r| ide_sdk::java::pick_jdk(&jdks, Some(r))));
jdk.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())])).unwrap_or_default()
}
pub(crate) fn load(root: &Path, cache: &Path) -> BuildModel {
let mut model = ide_build::load(root, cache);
/// The build model with the launch settings applied: the JDK (`JAVA_HOME`), and
/// the Maven home and options from Settings › Maven.
pub(crate) fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
let mut model = ide_build::load(root, cache, ide_sdk::apply::maven_local_repository(root, settings));
let jdk = ide_sdk::apply::project_jdk(root, settings);
if let Some(m) = &mut model.maven {
let mvn = ide_sdk::apply::maven_command(root, settings);
let options = ide_sdk::apply::maven_options(root, settings);
for p in &mut m.projects {
p.env = java_env(p.java_version);
p.env = java_env(jdk.as_ref(), p.java_version);
if let Some(mvn) = &mvn {
p.command = mvn.to_string_lossy().into_owned();
}
p.options = options.clone();
}
}
if let Some(g) = &mut model.gradle {
g.env = java_env(g.java_version);
g.env = java_env(jdk.as_ref(), g.java_version);
}
model
}
@@ -39,8 +50,8 @@ pub(crate) fn load(root: &Path, cache: &Path) -> BuildModel {
#[specta::specta]
pub async fn build_model(window: Window, state: State<'_, AppState>) -> IdeResult<BuildModel> {
let project = state.project(window.label())?;
let (root, cache) = (project.root.clone(), project.build_cache_dir());
tauri::async_runtime::spawn_blocking(move || load(&root, &cache)).await.map_err(join_err)
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
tauri::async_runtime::spawn_blocking(move || load(&root, &cache, &settings)).await.map_err(join_err)
}
/// Runs Maven (`help:effective-pom dependency:tree`) or Gradle (`tasks --all`) in the
@@ -58,10 +69,10 @@ pub async fn build_sync(
on_progress: Channel<SyncProgress>,
) -> IdeResult<BuildModel> {
let project = state.project(window.label())?;
let (root, cache) = (project.root.clone(), project.build_cache_dir());
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
let token = state.begin_request(request);
let result = tauri::async_runtime::spawn_blocking(move || {
let current = load(&root, &cache);
let current = load(&root, &cache, &settings);
let env = match tool {
BuildTool::Maven => current
.maven
@@ -71,7 +82,13 @@ pub async fn build_sync(
.unwrap_or_default(),
BuildTool::Gradle => current.gradle.as_ref().map(|g| g.env.clone()).unwrap_or_default(),
};
let options = SyncOptions { offline, profiles, env };
let options = SyncOptions {
offline,
profiles,
env,
maven_command: ide_sdk::apply::maven_command(&root, &settings).map(|p| p.to_string_lossy().into_owned()),
maven_options: ide_sdk::apply::maven_options(&root, &settings),
};
let progress = |p: SyncProgress| {
let _ = on_progress.send(p);
};
@@ -79,7 +96,7 @@ pub async fn build_sync(
BuildTool::Maven => ide_build::sync_maven(&root, &cache, &options, &token, &progress)?,
BuildTool::Gradle => ide_build::sync_gradle(&root, &cache, &options, &token, &progress)?,
}
Ok(load(&root, &cache))
Ok(load(&root, &cache, &settings))
})
.await
.map_err(join_err);
@@ -104,6 +121,7 @@ pub async fn build_run(
) -> IdeResult<BuildResult> {
let project = state.project(window.label())?;
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
let settings = project.settings.effective();
let token = state.begin_request(request);
let result = tauri::async_runtime::spawn_blocking(move || {
for path in clear {
@@ -113,7 +131,7 @@ pub async fn build_run(
items: Vec::new(),
});
}
let plan = compile::plan(&root, &load(&root, &cache), kind, file.as_deref())?;
let plan = compile::plan(&root, &load(&root, &cache, &settings), kind, file.as_deref())?;
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
})?;
+10 -1
Переглянути файл
@@ -14,7 +14,16 @@ pub async fn debug_start(
) -> IdeResult<DebugSessionId> {
let label = window.label();
let owner = SessionOwner::new(AppState::owner_window(label), state.window_sink(label));
state.debugger.start(config, owner).await
let settings = match state.project(label) {
Ok(project) => project.settings.effective(),
Err(_) => state.global_settings.effective(),
};
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
let custom = |command: &str| {
let path = ide_sdk::apply::setting_path(&root, settings.tool_path(command)?)?;
Some(path.to_string_lossy().into_owned())
};
state.debugger.start_with(config, owner, custom).await
}
#[tauri::command]
+17 -1
Переглянути файл
@@ -1,6 +1,6 @@
use crate::state::AppState;
use ide_core::{ChangeSet, DocId, IdeError, IdeResult, OutlineItem, Range};
use ide_language::FoldRange;
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentInfo, HistoryEntry};
use std::path::PathBuf;
@@ -136,6 +136,22 @@ pub async fn doc_folding(window: Window, state: State<'_, AppState>, doc: DocId)
.await
}
/// Tree-sitter highlighting for languages the UI has no CodeMirror mode for;
/// empty when the grammar has no highlights query or the document is large.
#[tauri::command]
#[specta::specta]
pub async fn doc_highlights(window: Window, state: State<'_, AppState>, doc: DocId) -> IdeResult<SyntaxHighlights> {
let project = state.project(window.label())?;
blocking(move || {
let snap = project.documents.text_snapshot(doc)?;
if snap.large {
return Ok(SyntaxHighlights::default());
}
Ok(project.syntax.highlights(doc, &snap.language, snap.version, &snap.text))
})
.await
}
/// Extend Selection (⌥↑): syntax ranges around `offset`, innermost first.
/// Large documents fall back to word / line / document ranges.
#[tauri::command]
+9 -4
Переглянути файл
@@ -22,10 +22,12 @@ pub async fn java_resolve_launch(
) -> IdeResult<JavaLaunchInfo> {
let project = state.project(window.label())?;
let module = project.root.join(module);
let settings = project.settings.effective();
let built = if build && compile::has_non_java_sources(&module) {
let (root, cache, module) = (project.root.clone(), project.build_cache_dir(), module.clone());
let (root, cache, module, settings) =
(project.root.clone(), project.build_cache_dir(), module.clone(), settings.clone());
tauri::async_runtime::spawn_blocking(move || {
compile::build_for_launch(&root, &load(&root, &cache), &module, test, &CancellationToken::new())
compile::build_for_launch(&root, &load(&root, &cache, &settings), &module, test, &CancellationToken::new())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??
@@ -40,19 +42,22 @@ pub async fn java_resolve_launch(
}
}
info.class_paths = class_paths;
// The project JDK, else the JDK jdtls compiles the module against, else one matching its Java version.
let project_jdk = ide_sdk::apply::project_jdk(&project.root, &settings);
let from_jdtls = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file());
let java = from_jdtls.or_else(|| {
let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_jdtls).or_else(|| {
let release = ide_sdk::java::project_java_version(&module);
let jdks = ide_sdk::java::installed_jdks();
ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home))
});
info.java_exec = Some(java.map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "java".to_owned()));
if info.error_count > 0 {
let vm_args = project.settings.effective().languages.java.jdtls_vm_args;
let vm_args = &settings.languages.java.jdtls_vm_args;
let lombok = ide_sdk::lombok::lombok_agent(
&project.root,
ide_sdk::lombok::agent_in_args(vm_args.split_whitespace()),
ide_tools::managed_bundle(&state.data_dir, "lombok"),
ide_sdk::apply::maven_local_repository(&project.root, &settings),
);
info.hints.extend(lombok.problem());
}
Loaded 100 of 496 files, more files were not shown because too many files have changed in this diff. Show more