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

...
Автор SHA1 Повідомлення Дата
Deng Liu b5521c2605 feat(remote-dev): show used and total disk space in resources dashboard
Show <used> / <total> in the Remote Host Resources Disk card header to match the Memory card above it, keeping free space alongside live read/write rates in the subtitle and status bar tooltip.
2026-11-27 09:23:19 -08:00
l0ng-ai 26992ec4ce fix(syntax): comments between a start tag's attributes are not XML syntax errors (#6551)
Without an XML language server, the built-in parser's syntax check flagged a comment inside a start tag, which is read as whitespace. For the XML grammar the check now runs on the text with such comments blanked (lines and UTF-16 columns kept); an unclosed comment or an unterminated tag still reports.
2026-11-28 01:03:23 +08:00
Akbar Husain 2c22574be0 fix(lsp): drop LemMinX's comment-in-start-tag error in XML (#6548)
XML files can keep attributes commented out inside a start tag (JGroups' configs do). Such a comment is accepted as whitespace, but LemMinX (Xerces) stops at <!-- and reports the whole tag as ElementUnterminated. That diagnostic is now dropped only when the reported tag is well-formed with its comments removed; real parser and schema errors stay.

Co-authored-by: akbar1214 <[email protected]>
2026-11-28 01:00:09 +08:00
LU XIANGRUIтаwildcatDownstairs 93368d4379 feat(profiler): profile Python runs with cProfile (#6512)
Profile on a Python configuration runs it under cProfile from the standard library when py-spy can't sample without root (always on macOS), or when Settings > Python > Profiler chooses cProfile. Scripts, modules and pytest configurations run with their own interpreter; stopping the run still writes the snapshot, which opens in the profiler view.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 00:54:42 +08:00
l0ng-ai 14741101bd perf(agents): don't keep the slash command list of archived tasks (#6528)
Each saved task kept the slash commands its agent last offered (up to ~200 entries) in memory and in the task list, archived ones included. Archiving now drops the list and tasks loaded archived start without it; completion for a task without a list uses what its agent last offered in the project.
2026-11-28 00:47:38 +08:00
l0ng-ai db60deede5 perf(agents): read a task's conversation from disk when it is first needed (#6527)
Opening a project parsed every saved agent task in full and kept every conversation in memory for the whole session, archived ones included. Startup now decodes only each task's own fields; the conversation and turn checkouts are read from the task file on first use. A conversation that cannot be read shows empty and is never saved over. agent_entries runs on the blocking pool since its first call parses the file.
2026-11-28 00:46:31 +08:00
l0ng-ai ab2a7767c7 feat(plugins): plugin commands can run a configuration through the plugin's executor (#6547)
The Run/Debug with <title> actions of a plugin executor took only an object argument, while a plugin command passes text, so a plugin's own entry could start a configuration only as a plain run without the executor's Java agent. They now take a configuration id, or a services.context / services.toolbar command's argument as it came (the first selected service's configuration).

Fixes #6516
2026-11-28 00:20:48 +08:00
LU XIANGRUIтаwildcatDownstairs 49c917880d feat(python): find usages and rename for pytest fixtures (#6520)
Find Usages and Rename on a pytest fixture (its definition or a test parameter that requests it) now cover every test and fixture that requests it by parameter name, including conftest.py fixtures used across the directory tree, overrides and usefixtures markers.

Closes #6513

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 00:15:16 +08:00
l0ng-ai f0db09aca5 fix(java): remove jdtls temporary files left in the workspace by earlier versions (#6538)
A workspace whose path has a space (every workspace on macOS) keeps jdtls' temporary files in the system temp folder, but the old <workspace>/.tmp was never read again, and a workspace in use is never removed as unused. Each jdtls start now removes that folder when the temporary files live elsewhere.

Fixes #6515
2026-11-27 23:54:53 +08:00
LU XIANGRUIтаwildcatDownstairs 979cce1175 feat(python): show matplotlib figures in a Plots tool window (#6529)
Python runs, debug sessions and the Python Console get MPLBACKEND pointing at a small bundled Agg backend (unless the run or the environment already sets it). plt.show() saves each open figure as a PNG in the project's cache folder; a watcher sends PlotAdded and the Plots tool window lists the figures with thumbnails, the image viewer, save, copy and delete. Settings > Python > Plots turns it off.

Closes #6514

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 23:53:40 +08:00
Muuтаmuutot faa7571038 feat(scratch): add New Scratch Buffer (#6525)
New Scratch Buffer (NewScratchBuffer, no default shortcut) cycles through buffer1.txt to buffer5.txt in the scratches folder: an existing buffer is opened with its contents (matched case-insensitively), a missing one is created empty. Listed in the keymap presets and the scratch guide.

Co-authored-by: muutot <[email protected]>
2026-11-27 23:40:52 +08:00
Deng Liuтаdengliu 264bf6969f feat(remote-dev): add remote host resource indicator and dashboard (#6425)
A remote window (SSH, WSL, Dev Container) shows a compact CPU and memory indicator beside the connection status; network and disk badges appear only when saturated. Clicking it, or Show Remote Host Resources, opens a dashboard with 60-second sparklines for CPU (cores, load), memory, network (with RPC round-trip latency) and disk (I/O and free space), the OpenIDEA processes on the host grouped by kind, and the top other host processes.

End Process asks for confirmation naming the process and PID, and ends only processes in the backend's own tree. Linux /proc and cgroup v2 limits are read for containers.

Co-authored-by: dengliu <[email protected]>
2026-11-27 23:34:21 +08:00
Vadim LazukтаInf1mum 66e17df216 feat(dotnet): show discovered solutions and projects as project-view tree nodes (#6224)
The Project view lists the discovered .NET workspace above the project folder: a Solution '<name>' group per solution with a leaf per project, and standalone projects as roots of their own. Each leaf is the real project file, so run/debug, build, selection and Select In work on it, and the same file still shows in its own folder.

The shared workspace scan starts only when the file index holds .sln, .slnx or project files; the check retries once the index settles, so a fresh open still gets the nodes, and a workspace without .NET is never scanned at open. Project view roots gain an optional file leaf for this.

Co-authored-by: Inf1mum <[email protected]>
2026-11-27 23:17:00 +08:00
LU XIANGRUIтаwildcatDownstairs 4ff5739854 feat(notebook): show the running kernel's variables in a Jupyter Variables tool window (#6517)
A Jupyter Variables tool window (bottom, under the stripe's overflow until first opened; also in Find Action) lists the variables of the last active notebook's kernel: name, type and a truncated repr, hiding private names, modules and IPython's own names. It refreshes after a run, a kernel restart and a switch of notebook, and never starts a kernel.

The variables are read with a silent execute_request carrying a user expression (no output, history, execution count or busy/idle status), only while the kernel is idle; a run started meanwhile waits for it, bounded to 10 seconds. A notebook tab restored at startup picks up its session once it opens.

Closes #6508

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 23:02:19 +08:00
Muuтаmuutot a0c03447a0 feat(editor): add Transpose action (#6524)
Transpose (EditorTranspose, no default shortcut) swaps the code points before and after each caret and moves the caret past them; at a line end it swaps the line's last two code points. With several selections it rotates their texts (the rightmost moves to the leftmost) and keeps each replacement selected; mixed carets and selections do nothing. Listed in the IntelliJ and VS Code keymap presets and documented in the editor guide.

Co-authored-by: muutot <[email protected]>
2026-11-27 22:51:50 +08:00
Vladislav Kuzmin c4e0900485 test: keep the stale Replace All buffer outside the project watcher and fix Windows path tests (#6498)
The Replace All fixture wrote its external change inside the watched project, so the watcher sometimes refreshed the clean buffer before the stale-buffer path ran. The stale file now lives just outside the project and is reached through a directory search scope; the test also checks the unsaved replacement text.

Includes the Windows fixes from #6459/#6460: Cobertura keeps rooted (drive-less) paths instead of joining them onto the checkout's drive, and the tsconfig plugin shim test compares the decoded path.

Closes #6494

Co-authored-by: principalwater <[email protected]>
2026-11-27 22:36:22 +08:00
Dimas Avrian Fachriza a42f13edc2 fix(editor): keep color swatches while typing so the gutter doesn't shift (#6519)
Language server and plugin color fields were cleared on every document change, so the color gutter collapsed on each keystroke until the debounced documentColor request answered, shifting the code left and right. Existing colors are now mapped through the change; only a color whose text the edit touches is dropped until the provider answers again.

Closes #6518

Co-authored-by: FForFachriza <[email protected]>
2026-11-27 22:33:39 +08:00
l0ng-ai 18d6041f2f fix(ci): run language smoke when LSP snippet conversion changes (#6523)
The breakpoint condition completion (#6509) imports src/editor/lsp/snippet.ts from the debugger code the frontend smoke loads, so scripts/smoke-paths.test.ts failed on main. The file is now in the workflow's paths and the Changes step's smoke pattern.
2026-11-27 22:31:46 +08:00
l0ng-ai 15c5e921df feat(agents): show links in the composer as chips and reference pasted GitHub file links (#6470)
Bare https URLs and [label](url) links show as chips in the agent composer and in sent messages: issues and pull requests as repo#12 (GitLab repo!3, Linear ENG-42), commits as repo@abc1234, other pages as host and path. A click opens the page; the text sent to the agent is unchanged. A link stays text while the caret is at its end, and a URL ends at CJK text and full-width punctuation.

Pasting a URL over selected text on one line makes [text](url). A pasted GitHub blob or tree link into this repository (matched against the git remotes, refs with / resolved) becomes an @path:lines or @dir/ reference when the file exists; other links paste as the URL.
2026-11-27 22:30:09 +08:00
LU XIANGRUIтаwildcatDownstairs bc64188c38 feat(python): go to definition and completion for pytest fixtures (#6510)
A fixture parameter of a test or fixture now resolves to the fixture that pytest would inject: the nearest definition in the same class or module, then the conftest.py chain up to the root, pytest_plugins modules, pytest11 entry points and the _pytest builtins. Go to Declaration opens it, and completion in a test's parameter list offers the fixtures in scope with their source file. Named fixtures (name=...) and usefixtures("...") strings are covered; the fixture layers are cached by file mtime.

Closes #6490

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 22:12:59 +08:00
LU XIANGRUIтаwildcatDownstairs a3c819e064 feat(debugger): complete breakpoint conditions from the language server (#6509)
The Condition field and the {...} parts of the log message in breakpoint properties offer code completion without a debug session. The expression is spliced on its own line before the breakpoint's line, indented like it, and a new lsp_snapshot_completion command asks the language server on a transient snapshot of the file, so locals in scope, fields and members after . are offered while the open document and its diagnostics stay untouched. The popup and keys are those of Evaluate; the field claims Ctrl+Space so the non-modal popover doesn't also run the editor's completion.

Fixes #6403

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 22:05:41 +08:00
audichuang 1f2e92b433 feat(project-tree): copy a Java class's fully qualified name from Copy Path/Reference… (#6503)
The Project view's Copy Path/Reference… chooser gains a Reference row, backed by a project.copyReference action: com.example.App for App.java and the package name for a folder under a JVM source or test root. The name comes from the path below the source root, so no file is read. The row is left out where there is no valid name: other files, package-info.java / module-info.java, folders that aren't Java identifiers, the source root itself, non-JVM roots, library files and selections that are only partly Java.

Closes #6495

Co-authored-by: audichuang <[email protected]>
2026-11-27 21:58:36 +08:00
LU XIANGRUIтаwildcatDownstairs 8dfca955a5 fix(profiler): harden the pstats reader (#6511)
A pstats file can point many functions at one stats tuple by marshal reference, so a few kilobytes could unfold into millions of caller edges; the reader now refuses a file whose callers tables add up to more edges than it has bytes. The format is decided by content first, so a V8 profile saved as cpu.prof opens as V8 instead of a broken cProfile snapshot. A function recorded under two names of one file is now one method row with its stats and edges added up. Open Snapshot also offers .pstat and All files.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 21:53:52 +08:00
l0ng-ai 91aba61c97 fix(agents): keep the caret in the composer after Quote (#6419)
Choosing Quote on a conversation selection focused the composer, but when the context menu closed it put the conversation's text selection back (a WebKit workaround), after the chosen row had moved focus into the composer, so the caret was lost. The context menu now leaves the selection alone when focus has moved into an editable element.
2026-11-27 20:57:12 +08:00
l0ng-ai 1fb4135b5b fix(ui): keep context menu labels whole when the menu meets the window edge (#6497)
A context menu a few pixels taller than the room below its point was capped and scrolled, and in WebKit the scrollbar that appeared took its width from the popup's content, so labels were cut. A popup opened at a point now moves up to fit the window before it is capped, and a capped popup always shows its scrollbar so the popup widens instead of cutting its labels.
2026-11-27 20:49:21 +08:00
LU XIANGRUIтаwildcatDownstairs 24598e0dae feat(notebook): convert a notebook to a Python script and back (#6491)
Adds Convert to Python File to the Project view context menu of a .ipynb and Convert to Jupyter Notebook to that of a .py file, both also in Find Action for the active editor.

The script uses # %% cell markers; Markdown and raw cells become commented # %% [markdown] / # %% [raw] cells, and IPython-only lines (%magic, !shell) and whole %%cell-magic cells are commented out so the script runs with plain python. The result is written next to the source without overwriting (<name>-1.py, ...) and opened; an open notebook or script is converted as shown, unsaved edits included. Back to a notebook gives nbformat 4.5 with a Python 3 kernelspec, where # %% / #%% lines start cells and a script without markers becomes one code cell. A notebook that is not nbformat 4 reports an error and writes nothing.

Closes #6372

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:42:23 +08:00
Bake Yam 2436ad6fe9 fix(notebook): give a cell the intentions menu a text editor has (#6492)
Alt+Enter in a notebook code cell offered only the server's code actions and the inspection controls: cellLspExtensions never included intentionsExtension, so a language's own intentions and quick fixes (Python's create function / class) were missing in cells. Cells now get the same intention providers as a text editor, looked up by the cell document's language; each cell is its own document, so the edits stay in the cell.

Part of #5846

Co-authored-by: Renjiankang <[email protected]>
2026-11-27 20:41:53 +08:00
LU XIANGRUIтаwildcatDownstairs c2c6931f0e feat(database): open .csv / .tsv files as a table (#6493)
.csv and .tsv files now open with Text / Data tabs under the editor. Data shows the file as a read-only table in the result grid, with header sort, the local column filter and search. The delimiter (comma, semicolon, tab or pipe) is guessed from the first 64 KB (.tsv is always tab), and the header row is guessed with a First row is header override. Quoted fields, line breaks inside quotes and a UTF-8 BOM are handled; ragged rows are padded, unnamed columns numbered and repeated names suffixed. Parsing runs in a Web Worker and the table re-reads the editor text (debounced) only while Data is shown; Text stays mounted so undo history and unsaved edits are kept.

visibleRows also computes each row's sort key once instead of per comparison, which speeds up local sorting of query results too.

Closes #6368

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:38:44 +08:00
Dimas Avrian Fachriza 2e0c8dd527 perf(editor): prune huge completion lists before mapping (#6477)
Tailwind answers every completion request with its full utility list (about 26k items), and each item was mapped to a CodeMirror option and re-filtered on every keystroke, which showed as input lag.

Lists above 2000 items now keep only the items whose filter text contains the typed token as a subsequence, before mapping. That is a superset of what CodeMirror's fuzzy matcher can show for text that grows from the token, so typing forward loses nothing; the pruned list stays valid only while the text still starts with that token, so backspacing asks the server again.

Co-authored-by: FForFachriza <[email protected]>
2026-11-27 20:33:39 +08:00
faysouтаfaysou f4be752dda fix(markdown): keep reading position when toggling Structure (#6483)
Showing or hiding a docked Structure pane changes the Markdown editor's width. CodeMirror could keep an old pixel offset within a wrapped line, and the preview measured its position after some blocks had already reflowed, so both jumped. The source view now anchors the first visible character across a side-dock change and restores it in the resize frame; the preview remembers its line and offset on scroll, pauses following the source while blocks reflow, and restores the position once the width settles. A navigation made while paused is applied on resume. Works in all three Markdown modes.

Co-authored-by: faysou <[email protected]>
2026-11-27 20:32:41 +08:00
LU XIANGRUIтаwildcatDownstairs a52a639b8e fix(coverage): import coverage.py data below fail_under and in monorepo members (#6478)
coverage xml (import) and coverage lcov (Run with Coverage) exit 2 when the data misses a [report] fail_under, which failed the import and lost the run's report; both now get --fail-under=0.

coverage.py now runs in the nearest folder above the data file with a coverage.py configuration (.coveragerc, setup.cfg, tox.ini, pyproject.toml), else the project root, so a monorepo member's [paths] and relative_files apply. Files without source come from the combined data's measured_files() instead of parsing warnings, and Python runs with -W ignore, so disable_warnings and PYTHONWARNINGS=error no longer drop files or fail the import. coverage.py runs with a 10-minute timeout, and coverage.py 4 data or a coverage.py older than 6.3 get clear errors.

Closes #6474

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:30:50 +08:00
LU XIANGRUIтаwildcatDownstairs 1b0bf4d741 fix(python): fix edge cases of import updates on module moves (#6479)
Fixes for the Python import updates on module and package moves:

- Nested attribute chains got overlapping edits and the move failed; each expression now gets one edit, on its longest moved prefix.
- Cancelling ends the request after the import scan and returns cancelled instead of partial edits.
- In monorepos, module names come only from Python roots (detected from a Python project file or marked by the user), a moved folder counts only when it holds .py/.pyi files, and an import is left alone when the importing file's own root has a module of that name.
- Files are read through the documents layer, so a BOM or another encoding no longer shifts the edits.
- Moving a .pyi stub without its .py changes no imports.
- Rewriting import pkg.models keeps pkg bound when the file still uses pkg.helper().
- Statements sharing a line stay valid, and moved names are removed line by line, keeping the remaining names' layout and comments.

Closes #6475

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:29:48 +08:00
LU XIANGRUIтаwildcatDownstairs 13597e40a1 fix(debugger): keep Python's debugpy config and pick Django or Jinja templates by language (#6476)
django-html declared a debugpy [debugger], and find_config takes the first language declaring an adapter, so a user's languages/python.toml debugger override no longer applied. The block is gone; breakpoint placement accepts Django Templates by language instead.

django: true came only from manage.py / -m django / django-admin, so template breakpoints never stopped under uvicorn, gunicorn, daphne or pytest-django, and the templates/*.html rule sent jinja: true for them. At debug start each file with an enabled breakpoint (other than .py) is asked for its language with the editor's detection: a Django Template turns on django, other templates turn on jinja. Disabled breakpoints no longer turn either on, and templates/*.txt and *.xml accept breakpoints.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:26:34 +08:00
LU XIANGRUIтаwildcatDownstairs aa1aa91b0d fix(debugger): keep Python Debug Server loopback hosts on loopback (#6487)
The port check retried every bind error for 5 s; it now retries only AddrInUse (the previous adapter still shutting down) and reports any other bind error at once.

Every loopback form of the host (127.1, LOCALHOST, 0:0:0:0:0:0:0:1, ::ffff:127.0.0.1) is normalised with the URL parser and stays on loopback: localhost and IPv6 loopback listen on 127.0.0.1, since debugpy's adapter before 1.8 listens on IPv4 only, and the connect line and waiting note say 127.0.0.1 then. Another 127.x address listens on itself. Docs explain that an imported VS Code listen.host of 0.0.0.0 becomes localhost and how to reach the IDE from a container.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:25:27 +08:00
LU XIANGRUIтаwildcatDownstairs 032a3b0453 fix(python): correct doctest results, module imports and docstring detection (#6489)
Skipped examples, examples after a first failure under REPORT_ONLY_FIRST_FAILURE, and examples after a FAIL_FAST stop were all reported as passed: the reporter only kept failures and marked every other example passed. It now records each example that ran (and reports skipped ones as skipped), applying REPORT_ONLY_FIRST_FAILURE itself so later examples still reach it.

Modules are imported by their dotted name from the deepest sys.path root that holds them (working directory, PYTHONPATH, source roots), falling back to loading the file when the import fails or resolves to another module. Docstring detection now skips lines inside triple-quoted strings and no longer gives a one-line def the next object's docstring; -v is passed through to the runner.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:24:03 +08:00
LU XIANGRUIтаwildcatDownstairs 07750ad984 fix(python): Create Test keeps imports, indentation and module paths valid (#6488)
Create Test wrote invalid Python in several cases: a new import glued to a last import without a final newline; the first import above a shebang, coding line or module docstring; methods added to a tab- or differently-indented Test class in the editor's indent unit; repeated definitions (@overload, conditional) tested several times; import paths not relative to the innermost source root; and an import of a module no import can name (my-tool.py). Each is fixed: the new import gets its own line below the header, methods use the class's indentation, a name is offered once, the module path is relative to its source root (no import when it has no valid name), and an uneditable test file shows a hint.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:21:22 +08:00
Muuтаmuutot ba38f070d9 feat(analysis): manage a producer's suppressed rules from the problem menus (#6472)
The submenu of a problem's inspection (Alt+Enter on a fix, Problems, Inspection Results) lists the codes the inspection profile in effect turns off for that producer, each checked (unchecking removes the rule), plus Add rule… to suppress a code before it has ever reported (for example Ruff's UP045). Rules are plain profile entries, so the editor, Problems and Inspect Code hide those codes. The rows show only for inspections split by code (language servers, code-split built-ins); the input dialog is provided by the workbench.

Co-authored-by: muutot <[email protected]>
2026-11-27 20:20:12 +08:00
l0ng-ai c77f4db777 fix(usages): show what the server found in its scope before the widened search (#6485)
A project-wide usages search asks the server, then opens the other files that mention the name and asks again. Only Java's library search streamed an early answer, so for Python (pyright) and the other servers the popup waited for the second pass. The first answer is now shown while the other files are searched, for a single answering server (not the CSS server, whose answer is filtered afterwards) and for Java's sources.

Fixes #6441
2026-11-27 20:05:53 +08:00
l0ng-ai d3067c8d3a feat(database): rebuild a PostgreSQL table's comments, owner, grants and triggers in its DDL (#6481)
Go to DDL on a PostgreSQL table gave the table, its constraints and indexes only. It now also gives the table and column comments, the owner, the privileges granted beyond the owner's (none while the ACL was never changed) and the user triggers, in the order a script runs them. Views keep their single statement.

Fixes #6439
2026-11-27 20:01:33 +08:00
l0ng-ai 7bf2702565 fix(kotlin): show the Kotlin bridge build as a background task (#6480)
The Maven build that compiles a project's Kotlin for JDT (on opening the project and after saved Kotlin or POM changes) ran with no sign in the UI, for about a minute on a large project, while Java code using the Kotlin API stayed red. It now shows in the status bar as Compiling Kotlin for Java with Maven's reactor progress, and can be stopped there; the next saved change builds again.

Fixes #6434
2026-11-27 19:56:49 +08:00
Dimas Avrian Fachriza 65c45ffe05 fix(editor): complete hyphenated tokens such as Tailwind classes (#6463)
Typing a hyphenated token such as items-c never offered items-center: the server's replace range covers the whole class, but the client filtered on the last word segment (c), and CodeMirror matches a one-character pattern only at a label's start. Typing - also closed the popup and re-queried. The completion now starts where the servers' single-token replace ranges start when they reach back over hyphens (the most common start wins), and the list stays valid across - while an option still starts with the typed text. Other punctuation, and lists with no option continuing the hyphen, re-query as before. CSS properties (background-c → background-color) benefit too.

Closes #6462

Co-authored-by: FForFachriza <[email protected]>
2026-11-27 19:51:26 +08:00
LU XIANGRUIтаwildcatDownstairs 84b528f0cd feat(profiler): open cProfile snapshots (.pstats / .prof) (#6466)
Open Snapshot… and Open in Profiler accept pstats files written by cProfile / profile (and yappi's pstat export), told apart from a V8 .cpuprofile by content. The marshal'd pstats dict is read in Rust without a Python interpreter. The method list shows exact own time, total time and call counts (total/primitive for recursion); selecting a method lists its callers and callees, exact for cProfile and summed from the call tree for sampled profiles. The flame graph and call tree are rebuilt from the caller/callee totals, sharing each function's time among its callers in proportion, with a notice that they are estimated; recursion is not unfolded, roots are the strongly connected components of the call graph, and the tree is bounded in share and node count. Recorded files resolve against the project root, then the snapshot's folder, each file looked up once.

Closes #6367

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 19:48:03 +08:00
LU XIANGRUIтаwildcatDownstairs 8621764813 feat(python): Create Test generates pytest tests for the chosen functions and methods (#6465)
On a Python module, Create New Test… (and the new Create Test… action) opens a chooser of the module's functions and its classes' methods, preselecting the one at the caret or every method of the class there. OK writes pytest stubs (test_<name> / class Test<Class> with test_<method>, body assert False) into the module's test file, or a new test_<module>.py in the mirrored package under the test root, importing only names the file doesn't import yet. Existing tests are kept, methods go into an existing Test<Class>, and the edit is one undo step. Imports spanning several lines (parenthesized or backslash-continued) are read too, so their names are not imported again and a new import goes after them. Other languages keep the template flow.

Closes #6387

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 19:40:40 +08:00
rolicon 22e1c4b927 fix(run): import JetBrains Dockerfile run configurations (#6469)
JetBrains docker-deploy configurations with a dockerfile deployment were skipped as UnsupportedType. The importer now keeps the Dockerfile path, image tag, container name and server name; the Dockerfile run type completes the import through a new prepareImport hook, resolving the server name to this machine's connection (the default daemon when none is saved and the name is Docker) and generating the run and stop commands. A missing or ambiguous server is left for the user to choose and reported as unmapped; running such a configuration asks for a server instead of using the default daemon. Other deployment types are still skipped.

Co-authored-by: rolicon <[email protected]>
2026-11-27 19:30:15 +08:00
Ernstjan FreriksтаEjaYF e2817656e8 fix(ui): end tree rows at the scrollbar track (#6468)
While a tree's vertical scrollbar thumb is shown, Scrollbar sets data-scrollbar-shown on its scroller and Tree reserves 8px on the right (the 10px track minus the thumb's 2px border), clipping its rows there. Rows wider than the panel no longer show their text, selection or hover background through the translucent thumb. Trees without a vertical scrollbar keep their 6px inset.

Co-authored-by: EjaYF <[email protected]>
2026-11-27 19:26:04 +08:00
LU XIANGRUIтаwildcatDownstairs 306c71290c fix(debugger): address review of the Python Debug Server (#6464)
Follow-up to #6421. A waiting Python Debug Server no longer lends its run configuration to other debug starts: each start's configuration is kept by name and taken by its own started event. Listening again retries the port for up to 5 s while the previous adapter shuts down instead of failing with Address already in use. An IDE host of ::1 listens on ::1 (other IPv6 hosts on ::) and the connect line strips the brackets. A VS Code listen host of 0.0.0.0 imports as localhost.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 19:21:53 +08:00
l0ng-ai 51ccb68b72 fix(diff): open a diff at its first difference (#6471)
A diff opened without a line to show (double-click in the Commit tool window, Show Diff) started at the top of the file. The two-pane and staging-area diffs now open at their first difference unless a line or a remembered caret is given. The all-in-one diff opens at the first difference of the file it was opened for, once, repeating the scroll until the change is drawn since lines below the drawn ones have estimated heights.

Fixes #6427
2026-11-27 19:19:02 +08:00
l0ng-ai 2e965810e9 feat(color-scheme): Java interface, abstract class, enum and type parameter colours (#6467)
The Java colour page gets Interface name, Abstract class name, Enum name and Type parameter under Classes. jdtls's interface, enum and typeParameter tokens, and class tokens with the abstract modifier, carry their own classes, which keep the class name colour until set. INTERFACE_NAME_ATTRIBUTES, ABSTRACT_CLASS_NAME_ATTRIBUTES, ENUM_NAME_ATTRIBUTES and TYPE_PARAMETER_NAME_ATTRIBUTES in an imported .icls land on them, and the default Interface name colours Java's interface until its own key does.

Fixes #6415
2026-11-27 19:09:20 +08:00
Vladislav Kuzmin 31b70cf0ac test(e2e): use the configured shortcuts for editor zoom and aggregate copy (#6457) 2026-11-27 19:00:02 +08:00
Muuтаmuutot d0989e2a4b fix(plugins): keep line-end annotations on their line when Enter splits it (#6454)
A plugin line-end annotation is a side: 1 point widget at the end of its line, and CodeMirror maps such a widget across an insertion at its position, so Enter at the end of an annotated line carried the label into the new line and down with every further Enter. The decorations field now re-places its items on every edit: marks and hover data map with the text, while an after label re-anchors at the end of the line its range's end maps onto. An empty range stays a point before text typed at it, so its label is kept.

Co-authored-by: muutot <[email protected]>
2026-11-27 18:59:15 +08:00
LU XIANGRUIтаwildcatDownstairs d96ed8d154 feat(python): run doctests from the gutter and the context menu (#6451)
Modules, classes and functions whose docstrings have >>> examples get a gutter run icon, and a module with examples and no if __name__ == "__main__": runs its doctests from the project tree and editor context menus ("Doctests in …"). A new Python doctest run configuration takes files or file.py::Class.method targets and doctest's -o options; PyCharm Doctests configurations import as it. Runs go through a stdlib-only reporter built on DocTestFinder / DocTestRunner that reports each example as a test under its object, so gutter icons show results, failures open Expected / Got in the comparison view, and Rerun Failed Tests reruns the failed objects.

Closes #6389

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:56:35 +08:00
l0ng-ai 6b41870368 fix(agents): keep the conversation painted when sending from far up (#6446)
Sending a message while scrolled up jumps the conversation to its end. The rows there had
skipped rendering (content-visibility: auto); WebKit turned them visible but didn't repaint
them, so the view stayed blank until the reply changed the conversation. A row whose
remembered height went stale the same way also kept the end of a streaming reply out of reach.

Rows within a viewport of the view are now tracked with an IntersectionObserver (data-near)
and always render, and a programmatic jump marks the rows around its target before moving.
2026-11-27 18:54:58 +08:00
LU XIANGRUIтаwildcatDownstairs 660becbaa4 feat(coverage): import coverage.py data files (.coverage) (#6450)
Import a Coverage Report now reads coverage.py's .coverage data file; choosing one .coverage.* file of a parallel run imports all of them. The data only records executed lines and arcs, so coverage.py in the project's interpreter combines it into a scratch file (combine --keep, the user's files untouched) and writes Cobertura XML (xml -i) for the existing importer, run in the project directory so [paths] and excluded lines apply. Running the interpreter needs a trusted project; without trust, an interpreter or coverage.py the error says so and points to coverage xml output. Files without source in the project are listed without lines and the notification says to map them with [paths].

Closes #6392

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:50:40 +08:00
LU XIANGRUIтаwildcatDownstairs a0afc478c1 fix(debugger): stop at breakpoints in Jinja2 and Flask templates (#6453)
debugpy reads a breakpoint in a non-.py file as a template breakpoint only when the launch has jinja: true, which was never set. A Python debug launch now gets it when it starts Flask (flask, -m flask) or when a breakpoint is already in a Jinja2 template (.jinja / .jinja2 / .j2, or markup or text in a templates folder). Django launches keep django: true alone, since debugpy reads one or the other. .jinja / .jinja2 / .j2 files now accept breakpoints.

Closes #6371

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:47:37 +08:00
LU XIANGRUIтаwildcatDownstairs 07a88c6fa4 fix(debugger): accept breakpoints in Django templates without the any-file setting (#6452)
Only languages with a debugger accept new breakpoints, and the Django Template language (files in a Django project's templates folders) had none, so breakpoints there needed "Allow placing breakpoints in any file". It now declares debugpy. debugpy also gets django: true for python -m django and django-admin launches, not only manage.py, and django-admin now runs as python -m django instead of a module that doesn't exist.

Closes #6370

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:46:23 +08:00
Bake Yam 46bd6fad3c fix(notebook): refresh cell documents when the backend changes their DocId (#6440)
The backend hands a notebook cell a new DocId when its servers open the notebook again (a restarted language server, a reopened notebook) while the cell ids stay the same. The session refetched cell documents only when the set of code cells changed, so it kept a spent DocId and editor shortcuts in a cell answered "DocId#N is not open". The lookup now runs on every snapshot, ordered by a sequence number, and publishes only when a cell's document or uri moved.

Part of #5846

Co-authored-by: Renjiankang <[email protected]>
2026-11-27 18:44:46 +08:00
薛纪克таxuejike f64dbe65b4 feat(agents): show the command a tool call ran in the session UI (#6429)
A command tool call showed only the agent's own title ("Run command"). The timeline now keeps the command from the call's structured input (rawInput.command / rawInput.cmd, a string or an argv array, <shell> -c <script> unwrapped), and the session UI uses it as the row title, its tooltip and the $ line of the expanded terminal block, falling back to the output's $ line and then the title. Saved sessions without the field still load.

Closes #6428

Co-authored-by: xuejike <[email protected]>
2026-11-27 18:42:02 +08:00
l0ng-ai e2a5a5db81 fix(debugger): flash only the stopped project's window on a breakpoint (#6449)
A breakpoint hit while the app was in the background requested attention for every webview window, so on Windows the taskbar button of another open project flashed too. Only the window of the project whose session stopped asks now; an event without a window still reaches every window. No other place requests attention for all windows.

Fixes #6404
2026-11-27 18:35:01 +08:00
LU XIANGRUIтаwildcatDownstairs 6eb7abff9f feat(debugger): add Python Debug Server configurations (#6421)
Python Debug Server run configuration (Debug only): the IDE's debugpy adapter listens (attach with listen) and the program connects with debugpy.connect. The form shows the line to add; a loopback host listens on 127.0.0.1 only, any other host on all interfaces (with a warning, since debugpy's listen mode has no authentication); local/remote roots map paths and redirectOutput sends the program's output to the console. While waiting, the session is Starting and the console shows the address and the line; Stop cancels the wait. When the connected program ends by itself, the configuration listens again in the same tab, keeping the output. A port in use fails the start up front (debugpy's adapter would otherwise wait forever), and on the first stop the program's debugpy version is compared with the IDE's, with a warning when they differ. VS Code attach configurations with listen import as Python Debug Server.

Closes #6369

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:30:11 +08:00
Waiting-Night b46112fe0b feat(database): organize data sources into folders (#6423)
Project-local data source folders in the Database tree: New › Folder…, rename and delete (members move back to the root), Move to Folder (also for several selected sources, including a new folder) and drag-and-drop onto a folder. Folders live in .openidea/data-source-folders.toml, written atomically and validated (one folder per source, known parents, no cycles), and are reloaded when the file changes on disk; removing data sources drops them from their folders.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 18:20:04 +08:00
Waiting-Night 4507dc172d feat(database): support batch actions on selected data sources (#6420)
Several selected data sources in the Database tree share Refresh, Deactivate and Remove: the context menu shows only those, with the number of affected sources. Refresh runs every selected source and reports failures once; Deactivate disconnects only the connected ones; Remove asks once (listing the names), disconnects, saves the project once and keeps the rest of the selection. The toolbar's Deactivate and Properties follow the multi-selection.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 18:08:08 +08:00
LU XIANGRUIтаwildcatDownstairs 8442c0c339 feat(typescript): CSS Modules navigation through CSS Modules Kit (#6345)
Go to Declaration, completion, Find Usages and Rename for CSS Module class names between TS/JSX and *.module.css, through the CSS Modules Kit tsserver plugin on vtsls. The plugin is an IDE-managed tool pinned to @css-modules-kit/[email protected]; a project turns it on with "cmkOptions": { "enabled": true } in tsconfig.json (also inherited through a local extends), which the editor offers to add, installing the plugin if needed. CSS files reach vtsls only once the plugin is installed; references from a selector drop the CSS server's own rule, and rename takes vtsls' edit so the selector keeps its dot.

CSS Modules Kit loads before the Vue tsserver plugin outside a Vue project: both are Volar plugins sharing one @volar/typescript, which decorates a project once, so with the Vue language server installed the Vue plugin had claimed every vtsls and CSS Modules Kit did nothing.

Closes #6071

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:00:08 +08:00
l0ng-ai 8ffe3bd230 fix(i18n): translate the Run tool window's agent configuration action (#6436)
The hidden run.mcpStart action added in #6431 had no Chinese title and description, which the locale catalog tests require.
2026-11-27 17:41:48 +08:00
l0ng-ai 1babff55fc feat(mcp): run execute_run_configuration's runs in the Run tool window (#6431)
A run configuration started through execute_run_configuration ran out of sight, with no Run tool window tab, console or Stop. The tool now asks the project window to start the prepared configuration (before launch tasks already done), tagged with mcp.configRun; run_start recognises the tag on the first start, tees the output into the call's output file and reports the run it started, so exitCode, runId, stop_run and fullOutputPath keep working. A project loaded for MCP alone (no window, brave mode) still runs it directly.

Fixes #6330
2026-11-27 17:30:39 +08:00
l0ng-ai 2ad95150eb fix(refactoring): undo an extract refactoring with its rename and reformatting in one step (#6424)
The history group around a server refactoring kept every transaction out of the undo history, including the workspace refactoring's history marker, so Cmd+Z reverted only the current file's text locally and the notification's Undo failed with "Undo newer editor changes".

The marker now stays in the history. Local edits after the server's within the group (reformatting, the in-place rename) are recorded as the refactoring's follow-up edits: undoing the refactoring reverts them before the backend restores the files, redoing applies them again, and a refused restore puts them back. The notification's Undo first finishes an open in-place rename. Quick fixes group the server's edit with its reformatting the same way, so their reformatting no longer sits above the marker as a separate step.

Fixes #6327
2026-11-27 17:19:13 +08:00
Waiting-Night fe3e647abb feat(database): list query consoles under a Database Consoles root (#6408)
Query consoles stay in <dataDir>/consoles/db; the database feature registers that folder as a Database Consoles root in the Project view's Scratches and Consoles scope, re-registered when a remote session starts or ends. Console folders show the data source's name and icon ("Orders", "Orders: sales") through new display-only label/icon file decorations, which also order siblings when sorting by name. Consoles announce their creation so the tree refreshes, deleted console files close their editors, and a console's data source is recovered from its path when the binding is missing.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 17:06:51 +08:00
Waiting-Night 62cc6768fe feat(search): show data source names for recent query consoles (#6411)
Recent Files listed every query console as console.sql, so consoles of different data sources looked the same. Rows for files without an open editor now use the file decoration's tab title and icon, so a console shows as console [Orders] with its data source icon; match highlighting is dropped when the shown title differs from the file name.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 16:49:38 +08:00
Waiting-Night 2e93422270 feat(database): show table comments in the database tree (#6416)
Tables and views in the Database tree now show their comment in grey after the name, with the full comment as the row tooltip. Built-in drivers read it in the same catalog query that lists relations (PostgreSQL, MySQL, Oracle, ClickHouse, Snowflake, SQL Server extended properties) and JDBC sources from REMARKS. The new Show Table Comments view option is on by default and toggles from the Database window options; TableInfo.comment is optional on the wire.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 16:48:31 +08:00
audichuang 3a1353cc0e feat(vcs): show a file's diff from the Rollback, Shelve and Create Patch file lists (#6417)
In the Rollback Changes dialog, double-click and Enter only toggled a file's checkbox and Show Diff did nothing. The file checklist shared by Rollback, Shelve and Create Patch now opens the file's diff in a front dialog on double-click, Enter and Show Diff, with the listed files as the next/previous chain; Space toggles the selected rows and clicking a box still toggles it. Rollback Unstaged Changes shows the index against the working copy. Closes #5295.

Co-authored-by: audichuang <[email protected]>
2026-11-27 16:44:28 +08:00
audichuang c5eab0a4a3 fix(editor): show color swatches for Java new Color(0x...) literals (#6413)
The hex rule required a leading #, so java.awt.Color int literals never matched. In Java files, a 0x literal that is the whole argument of new Color(...) or new ColorUIResource(...) (unqualified or qualified as java.awt / javax.swing.plaf) is now a color, read as Color(int) reads it (the low 24 bits); picking a color writes it back as 0x hex in the literal's case. Other overloads, suffixed literals, other Color classes and Kotlin stay without a swatch. Closes #5529 together with #6412.

Co-authored-by: audichuang <[email protected]>
2026-11-27 16:42:28 +08:00
audichuang 581c8cf025 fix(editor): show color swatches for HTML style attributes and embedded scripts (#6412)
Named colors only counted in style sheet languages, and in markup only matches inside style nodes were kept, so embedded script code was dropped. Named colors now count in markup (still limited to <style> and style attributes by the syntax tree), and a match inside a Script node is kept when a standalone script file would accept it: quoted hex and color functions, never names. The property-colon check now looks only after the last colon, so long markup lines no longer cost quadratic time. Refs #5529.

Co-authored-by: audichuang <[email protected]>
2026-11-27 16:41:56 +08:00
l0ng-ai 807c447792 feat(database): Revert Selected and Copy Aggregation Result in the data grid (#6418)
Revert Selected drops the pending edits, deletes and added rows of the selected rows only, from the row menu of the table editor and editable results; it takes Cmd+Alt+Z / Ctrl+Alt+Z while the selection has changes, and Revert keeps the shortcut otherwise. Copy Aggregation Result copies one aggregate of the selected cells as the Aggregates panel shows it: Cmd+Shift+C / Ctrl+Shift+C copies the Sum of numbers or the Count otherwise, and the grid context menu lists every aggregate the selection has. Fixes #6308.
2026-11-27 16:40:46 +08:00
l0ng-ai 217693a56f test: make three Rust tests pass on Windows (#6386)
Three tests failed on the Windows Rust job after Clippy: the tsc solution test built expected paths with mixed separators, the gutter plugin test compared a path argument as a string although the plugin sees /-separated Windows paths, and the run configuration completion fixture approved /bin/echo, which is not executable on Windows. Expectations use chained joins, the gutter test compares paths, and the fixture approves the test binary itself.
2026-11-27 16:21:12 +08:00
Deng Liuтаdengliu 557295b1df feat(agents): surface OAuth device-code banner in Sign In dialog (#6399)
The agent Sign In dialog parses OAuth device-authorization URLs and one-time codes from the sign-in PTY output and shows them above the terminal with Copy and Copy Code & Open Browser, using the desktop clipboard and browser. On openidea-server, sign-in PTYs are marked as a remote session (REMOTE_CONTAINERS=1 when no SSH or Codespaces marker exists, GH_BROWSER=true for gh without a browser override), so CLIs pick device-code sign-in instead of a remote-only loopback callback.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:20:24 +08:00
Deng Liuтаdengliu 7c674e70e5 fix(agents): pick Linux Copilot archive from host dynamic linker (#6398)
openidea-server on Linux is a static musl binary, so choosing the Copilot archive with cfg!(target_env = "musl") installed the linuxmusl build on glibc hosts, where execve fails with ENOENT. The archive variant now comes from the host's runtime dynamic linker: linuxmusl only when ld-musl is present and glibc's loader is absent or symlinked to musl.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:17:35 +08:00
Deng Liuтаdengliu 1602a5d010 fix(services): route Docker Services to the remote host daemon (#6379)
Docker commands moved from the desktop crate into the ide-host project_host domain, so a remote window reaches the Docker daemon on the remote host through openidea-server instead of the local one. The SSH tunnel reuses the existing resolve logic, docker_executable only caches a found path, and the Services store drops event streams, timers and in-flight requests when the host changes.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:16:20 +08:00
wangfeiтаhapput a6d135d66f feat(agents): add separate chat and code font settings (#6395)
Settings > Agents > Chat gets Font and Code Font groups like Terminal's: chat text and code each take a family, a fallback and a size. Defaults follow the interface font and the built-in code font, so nothing changes until a choice is made. Chat zoom steps on top of the chosen size, and a chosen code size also applies to fenced code blocks while inline code stays with the chat text.

Co-authored-by: happut <[email protected]>
2026-11-27 16:07:51 +08:00
LU XIANGRUIтаwildcatDownstairs 924bf6d3b9 feat(coverage): import Cobertura XML reports (#6390)
Import a Coverage Report now reads Cobertura XML (coverage.py's coverage xml and many other tools): line hits, partial branches from condition-coverage, relative file names resolved against <sources>, foreign paths mapped by suffix as for the other formats, and <methods> lines not counted twice. The import notification says how many files of a report are not in the project. Missing directories are now looked up once, which makes reports with CI paths under macOS's autofs /home import in under a second instead of tens of seconds.

Closes #6359

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 16:03:41 +08:00
l0ng-ai 318c227b0c fix(database): show column comments in the SQL table and column hover (#6402)
The completion metadata the SQL console hover reads carried no column comments, though Modify Table and the Database view already read them. completion_columns now returns the comment on PostgreSQL, MySQL, Oracle, ClickHouse and Snowflake (NULL on SQL Server and SQLite), Snowflake's SHOW COLUMNS path and the JDBC bridge's schemaColumns (REMARKS, jar rebuilt) carry it too, and the hover shows a comment column in the table card and the comment under a single column.

Fixes #6374
2026-11-27 16:01:45 +08:00
l0ng-ai 2ce7621abb fix(terminal): write shell integration scripts atomically into a content-keyed folder (#6400)
The shell integration scripts went to a temp folder named by version only and were rewritten in place, so a shell starting while another process rewrote them could source a truncated file, and two builds of the same version with different scripts (a dev build next to a release, two checkouts' tests on one runner) overwrote each other; zsh_restores_zdotdir_and_histfile_for_login_shells failed on macOS CI that way. The folder name now carries a hash of the scripts, and each file is written to a unique temporary name and renamed into place.
2026-11-27 15:54:12 +08:00
Deng Liuтаdengliu 7ecccb3b75 feat(agents): preview Copilot subscription models immediately on account switch (#6346)
Switching Sign In > GitHub account for GitHub Copilot used to hide New Tasks models behind an Apply step. A new trusted command, agent_preview_copilot_models, probes Copilot's model catalog for the staged account in memory without touching copilot.toml, models.json or active sessions, so the account and default model can be chosen together and saved with one Apply / OK, and Cancel discards both. Account logins are validated before they reach gh, and applying the account refreshes the stored catalog.

Co-authored-by: dengliu <[email protected]>
2026-11-27 15:45:27 +08:00
Muuтаmuutot 7cbf17b10e feat(vcs): drag the Unversioned Files group and multi-selections onto a changelist (#6299)
In the Commit tool window the Unversioned Files group header is now a drag source whose files are the payload, and a selection of unversioned files drags together. The drag gate in ChangesTree excluded every group row without a changelist id; it now also allows the unversioned group. Dropping reuses addToChangelist, which adds the files to Git and assigns the list; ignored rows stay non-draggable.

Co-authored-by: muutot <[email protected]>
2026-11-27 15:41:46 +08:00
LU XIANGRUIтаwildcatDownstairs cb0d02620d feat(python): run unittest tests without pytest (#6385)
Adds a Python unittest run configuration and Settings > Python > Testing > Default test runner (Autodetect / pytest / unittest). Autodetect keeps pytest for projects that use it; projects whose test modules import unittest and not pytest get a detected python -m unittest configuration, and gutter / context runs of such modules use unittest. Runs go through a stdlib-only reporter that wraps unittest's main() and prints one record per test and subtest, so the tree shows passed, failed, error, skipped, expected failure and unexpected success, subtests as children, captured output, failure locations, import and setUpClass failures; project, folder (discover), module, class and method targets and Rerun Failed (-k) are supported. PyCharm Unittests configurations import as this type. Jump to Source and MCP run / select-tests also handle unittest configurations (file and dotted-name narrowing) instead of falling back to pytest.

Closes #6361

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:40:08 +08:00
LU XIANGRUIтаwildcatDownstairs d6ca43cba4 feat(mdx): add MDX language support through @mdx-js/language-server (#6355)
Adds an mdx language backed by @mdx-js/language-server and moves .mdx out of markdown.toml; the prose keeps Markdown highlighting, outline and folding. The server needs typescript.tsdk, which the launcher fills with the TypeScript vtsls uses (selected version, else vtsls' bundled one, else the one installed with the server, else the project's); an explicit tsdk setting wins, and the managed install adds typescript@6. Places keyed on markdown (live rendering, large-file outline, spell checking as prose, auto-indent, Surround With, colour preview) now include mdx. Formatting follows the Markdown entry of the Prettier / oxfmt language lists so saved lists keep formatting .mdx, and Prettier gets --parser mdx from mdx.toml instead of an extension special case.

Closes #6340

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:33:09 +08:00
l0ng-ai 165d4f7d76 test(plugins): record the plain HTTP request before replying (#6396)
The local server in net_http_setting_grants_reach_plain_http_per_transport recorded a served request only after writing the response, so the client could read it and assert seen.len() == 2 before the second push (1 != 2 on ubuntu CI). The request is now recorded before the reply.
2026-11-27 15:29:03 +08:00
LU XIANGRUIтаwildcatDownstairs 5785ebadd8 feat(typescript): import style code style settings, sent to tsserver (#6342)
Editor > Code Style > JavaScript and TypeScript get an Imports tab: import paths (shortest / relative / non-relative / relative within the project), import path ending (automatic / minimal / index / .js), and glob and regex lists of what not to auto-import. They are stored with the code style, added to the servers' typescript/javascript preferences under both vtsls and typescript-language-server key names, and sent to running servers with didChangeConfiguration; a server's own Language Servers settings still win. The two exclusion lists are always sent (as [] when unset) so clearing one takes effect without a restart. Adds the typescript_import_style language smoke test.

Closes #6072

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:26:29 +08:00
LU XIANGRUIтаwildcatDownstairs 0c67a4eea2 feat(typescript): load the tsserver plugins a project's tsconfig declares (#6353)
tsserver only looks for tsconfig plugins next to the TypeScript it runs from, so with vtsls' bundled TypeScript plugins such as Next.js' were never found. When a tsconfig.json / jsconfig.json under the server root declares compilerOptions.plugins (directly or through extends), vtsls now gets one extra tsserver pluginPaths entry: a folder under the IDE data dir with a small re-exporting package per declared plugin. Plugins the IDE registers globally are left out so they keep resolving to the IDE's copies; missing plugins are logged and skipped; only valid npm package names are used. Changes to tsconfig/jsconfig files trigger a reconfigure, and the probe folder is keyed by the declaring configurations' text, so vtsls restarts instead of stacking plugin instances. Untrusted projects start no language servers, so no project plugin loads there.

Closes #6336

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:23:33 +08:00
LU XIANGRUIтаwildcatDownstairs 5e2deed81e feat(new-project): add Expo, Electron and create-vue generators (#6351)
New Project gains three JavaScript generators that run the official packages through the chosen package manager: Vue (create-vue) with TypeScript, Vue Router, Pinia, Vitest and ESLint options; Expo (React Native) with blank, blank TypeScript and tabs templates; and Electron (Electron Forge) with Vite, Vite + TypeScript and webpack + TypeScript. create-vue gets a kebab-case folder renamed to the project name and a no-op flag when every option is off so it never prompts. Electron always installs, since Forge writes the dependencies by installing them. Static Website moves to the end of the group. Brand icons and en/zh strings added.

Closes #6338

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:21:11 +08:00
LU XIANGRUIтаwildcatDownstairs cae7c05fb1 feat(sass): language server for indented Sass files (#6348)
Indented .sass files now run some-sass-language-server (MIT, installed through npm from the Tools list): completion for variables and mixins across @use, Go to Declaration, hover with SassDoc comments and syntax diagnostics. vscode-css-language-server does not parse the indented syntax; SCSS, CSS and Less stay on it. The server throws on a null somesass configuration, so the definition passes an empty settings table to keep its defaults.

Closes #6339

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:18:58 +08:00
LU XIANGRUIтаwildcatDownstairs be83458161 feat(run): choose the Python interpreter of a run configuration from a list (#6382)
Python and Django test run configurations get an Interpreter dropdown: Project default, each detected interpreter (minus those removed on All Interpreters), or Custom command, which shows the Command field for runners such as uv or poetry. The chosen interpreter's path is stored as the command, so command lines, the backend and .run.xml import are unchanged; existing configurations open with the choice their command stands for, and a missing interpreter is shown as not found. With a run-target project interpreter only Project default and Custom command are offered. RunConfigTypeField gains an optional set(value, params) so a select can stand for other params.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:17:30 +08:00
LU XIANGRUIтаwildcatDownstairs 661124d0d4 fix(run): group pytest parametrized cases under their test (#6384)
Parametrized pytest cases now appear as children of their test, with the combined status on the parent, and Run / Rerun Failed on either runs exactly that node id. The parser split node ids at every :: and failure titles at every dot and only matched ids without spaces, so cases were flat siblings, cases with spaces were missing, and a failing [v1.2 ...] case became a bogus chain under the run root. The [id] part is now kept whole. Tests without a failure line, and the grouping node, now navigate to the test's def.

Closes #6360

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:15:04 +08:00
LU XIANGRUIтаwildcatDownstairs 0dae111b2d feat(navigation): Related Symbol for JS/TS components, templates, styles, tests and stories (#6347)
Navigate > Related Symbol now switches between a JS/TS component and the same-named files beside it: an Angular component, directive, pipe or service and its template, styles and spec (also following templateUrl / styleUrl / styleUrls), and Button.tsx with Button.module.css, Button.test.tsx and Button.stories.tsx. Targets are grouped as Source File, Template, Styles, Test and Stories. It reads only the folder listing and the open file's text; two same-named sources (Button.ts and a compiled Button.js) are not offered for each other.

Closes #6337

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:13:19 +08:00
Mansur Akhmadiтаmansur-akhmadi 61d269045b feat(vcs): Compare File with Editor action (#6364)
Adds Compare File with Editor: the file selected in the Project view (or passed as the argument) is diffed against the active editor's file, opened at the editor's caret line, with swappable sides. The Project view context menu offers it right after Compare With… for a single file other than the editor's; virtual documents, folders, multiple files and the editor's own file get an explanatory notification instead. It is unbound in the presets and mapped from imported keymaps via CompareFileWithEditor.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:12:02 +08:00
Mansur Akhmadiтаmansur-akhmadi 266d85fa1a feat(run): Search with Google in the console context menu (#6358)
Adds Search with Google to the Run console context menu: it opens a web search for the trimmed, URL-encoded selected output in the browser, and is disabled when nothing (or only whitespace) is selected.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:08:59 +08:00
Mansur Akhmadiтаmansur-akhmadi f964d79e10 feat(terminal): Close All Tabs in the session tab menu (#6344)
Adds Close All Tabs to the terminal tab context menu. Close Tab / Close Other Tabs / Close All Tabs now share requestCloseTabs, which closes the tabs in order, confirms each running command like Close Tab, stops at a tab the user keeps open, and skips tabs whose shell already exited.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:07:43 +08:00
Mansur Akhmadiтаmansur-akhmadi 4a3eacff62 feat(code-insight): Export to Text File in the Find Usages tool window (#6292)
Adds Export to Text File… to the Find Usages toolbar and Find Action. It writes the active search as shown (access filter applied, excluded usages left out) as an indented text report to a file picked in the save dialog, and reports write errors as a notification.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:06:50 +08:00
Mansur Akhmadiтаmansur-akhmadi aebc2fe02d feat(templates): Save as Live Template from the editor selection (#6305)
Adds Tools > Save as Live Template…: with a selection in a text editor it adds a User live template whose text is the selection (dedented like $SELECTION$, with $ escaped as $$), in the file's language, and opens Settings > Live Templates on it. The page now accepts a focus target and selects that template.

The action is unbound in the presets and is reachable from imported keymaps and IdeaVim via SaveAsTemplate.

Closes #6304

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:05:34 +08:00
Mansur Akhmadiтаmansur-akhmadi 9b63aa9526 feat(editor): Increase / Decrease Font Size in All Editors actions (#6350)
Adds Increase / Decrease Font Size in All Editors actions that change the editor font size setting for every open editor, next to the existing single-editor zoom actions.

The default keymaps bind Alt+Shift+. / Alt+Shift+, (Ctrl+Shift+. / Ctrl+Shift+, on macOS) to the All Editors actions; the single-editor actions stay available from Find Action and can be bound in Keymap settings. Docs and keymap tests updated.

Closes #6349

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:00:39 +08:00
Mansur Akhmadiтаmansur-akhmadi df07073886 feat(editor): Delete Duplicate Lines action (#6323)
IDEA's Edit > Delete Duplicate Lines (EditorUniqueLines): in the selected lines, or the whole file without a selection, keeps the first of each repeated line and deletes the later ones.

Closes #6322

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:55:06 +08:00
Mansur Akhmadiтаmansur-akhmadi 3433ee951b feat(editor): Scroll Left / Scroll Right actions (#6303)
IDEA's Scroll Left / Scroll Right: move the editor viewport by one column without moving the caret, counted in whole columns. Unbound by default, as in IDEA.

Closes #6302

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:53:36 +08:00
Mansur Akhmadiтаmansur-akhmadi 8f5b281486 feat(editor): Kill to Word Start / Kill to Word End actions (#6294)
IDEA's Kill to Word Start / Kill to Word End: cut from each caret back to the previous word start or on to the next word end, across blank lines, by hump with CamelHumps on. Repeated kills at the same caret collect into one clipboard entry like Cut up to Line End, backward kills before the collected text. Unbound by default, as in IDEA's default keymaps.

Closes #6293

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:52:04 +08:00
Mansur Akhmadiтаmansur-akhmadi 43aee8058c feat(editor): Toggle Sticky Selection action (#6325)
IDEA's Toggle Sticky Selection: while on, every caret move (keys, IDE actions, clicks, Find) extends the selection from its anchor. Turning it off, Esc, an edit of the document or a copy end it and remove the selection, as in IDEA. Swap Selection Boundaries keeps it going from the other end. No default shortcut, as in IDEA's default keymaps.

Closes #6324

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:49:18 +08:00
audichuang 4016c3c905 fix(vcs): show the merge result in a background tab of the file (#6378)
After Apply in the merge editor, a tab of the file behind the merge editor kept showing the conflict markers although disk and index held the result. Without an editor view, writeFileText edited a transient doc_open/doc_edit/doc_save reference; doc_edit is not echoed to the document's other references, so the background tab never got the change. The write now goes through the file's document (attachDocument), so every tab of the file follows; the file is still saved as is. Get from Revision in the log uses the same helper.

Closes #5567

Co-authored-by: audichuang <[email protected]>
2026-11-27 14:40:00 +08:00
audichuang e6cb7df653 fix(run): count every test when JUnit runs them in parallel (#6377)
With JUnit's parallel concurrent mode, OpenIDEA's JUnit runner could report fewer tests than finished: the listener is called from several worker threads, Reporter's counters were plain ints incremented without a lock and PlatformRunner's start times a HashMap. The counting methods are synchronized now and the start times a ConcurrentHashMap. build.py --test runs a 4000-invocation parallel sample and expects the exact summary.

Closes #6334

Co-authored-by: audichuang <[email protected]>
2026-11-27 14:37:21 +08:00
Muuтаmuutot 2a26c82357 fix(vcs): the Git Log branch filter follows a branch rename (#6341)
Renaming a branch left the Git Log filtering the old name: the Branch chip kept it and the query failed with unknown revision. renameBranchInLogFilters now rewrites the shown view's branch filter, parked log views, the per-repository remembered choice and Log: <branch> tab targets, and reloads the log when the shown view filtered by the old name. A batch rename follows only when every repository was renamed.

Co-authored-by: muutot <[email protected]>
2026-11-27 14:27:05 +08:00
eclix-del 66f0bce92f fix(editor): keep a re-dropped file saveable (#6328)
A file from outside the project, dropped into the editor again, stopped saving after the first save, silently. Three paths led there:
- onLocal set the dirty flag after updating the touched ranges, so an exception there left the buffer clean and every save a no-op. Dirty is now set first, and a failure to map the ranges falls back to treating the whole document as touched.
- A reused model kept the touched ranges of the previous tab; they are cleared when a clean model is reacquired.
- A file opened under its native Windows spelling (E:\code\a.sql) and the editor's E:/code/a.sql got two models sharing one backend document, and dirty/patch/language events reached only one. Events now go to every model of the document, and dropped paths are normalized with ipcPath (extended-length paths too).
save() also writes when the dirty flag lags but edits are still pending.

Refs #5528

Co-authored-by: eclix-del <[email protected]>
2026-11-27 14:24:00 +08:00
Mollo-i dfbd13e2af fix(run): keep console soft wrap across run tabs (#6331)
The Run/Services and Debug console toolbars kept soft wrap in component state, so switching run tabs reset it to the Settings default. The toolbar toggle now writes Settings > Console > Use soft wraps in console (console.softWrap) and every console reads it, so one toggle applies to all consoles and survives a restart. The e2e settings-write stub moves into the shared fixtures.

Co-authored-by: Greenker <[email protected]>
2026-11-27 14:19:24 +08:00
aconeshanaтаaconeshana 944b57dead fix(run): open a stack frame's file from the run module's scope (#6366)
Clicking a stack frame in the Run console opened another module's copy of a class when several modules of a multi-module Maven build declare the same package and class: the lookup went by file name, and the package check cannot tell same-package copies apart.

Candidates are now narrowed to the run configuration's module and the modules it depends on (transitively, all scopes) before the name and package checks. The module reaches the Run console links, the test tree's Jump to Source and the Debug console links. Without a Maven model, for an unlisted module, or when the scope matches no candidate, the lookup behaves as before.

Closes #6313

Co-authored-by: aconeshana <[email protected]>
2026-11-27 14:16:59 +08:00
LU XIANGRUIтаwildcatDownstairs 5bcb37492f fix(run): print each line of a JUnit test's output once (#6333)
With Run tests using: OpenIDEA, every line a JUnit Platform test printed showed twice: the runner enabled JUnit's output capture, whose StreamInterceptor also writes each line to the original System.out, and then reported the captured text again as testStdOut.

The runner now captures System.out / System.err per thread itself, as Junit4Runner does: a thread's lines while it runs a test or a class's set-up go only into that test's or class's testStdOut / testStdErr, other output passes through, and JUnit's capture is turned off explicitly. The console now shows testStdErr as stderr, and "Show console when a message is printed to stderr" fires for it (also for Junit4Runner and the Gradle test init script).

Fixes #6332

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 14:14:49 +08:00
Yann d5bde9af67 fix(agents): preserve Codex failure diagnostics (#6354)
Codex turns blocked under cyberPolicy were turned into a successful ACP refusal, dropping the server's explanation and showing only "The agent declined to continue." They now fail like other turns, and a failed turn's message carries Codex's additional details, its diagnostic code and any reported HTTP status. Authentication and usage-limit classification are unchanged.

Co-authored-by: YannABC <[email protected]>
2026-11-27 14:13:03 +08:00
Deng Liuтаdengliu 5b3e2b7a3d fix(editor): skip whitespace-only selections in selection match highlighting (#6318)
Selecting indentation (spaces or tabs) flooded the editor with occurrence highlights, because CodeMirror's highlightSelectionMatches matches whitespace-only selections verbatim. heavyExtension now uses a selectionMatches view plugin with the same bounds (min length 2, max length 200, at most 500 visible matches) that skips whitespace-only selections, as the terminal and Markdown preview already do.

Co-authored-by: dengliu <[email protected]>
2026-11-27 14:11:22 +08:00
薛纪克таxuejike dbb6fa51c3 fix(database): start new query consoles in the selected schema (#6375)
New Query Console and Query Console opened from a schema, folder or table node started in the connection's default schema: the commands passed only the node's data source id, and bindConsole clears the console schema when the binding changes. The commands now pass the invoking node's schema (else the selected tree node's on the same connection) and the console switches to it after binding.

Closes #6329

Co-authored-by: xuejike <[email protected]>
2026-11-27 14:09:04 +08:00
l0ng-ai 3d1769ef00 chore(plugins): rebuild the net-setting test fixture from its sources 2026-11-27 12:28:25 +08:00
l0ng-ai c966429f92 chore: v0.1.54 2026-11-27 11:40:15 +08:00
l0ng-ai dfcc05dd41 fix(vcs): keep the combined diff's stuck file header flush with the top (#6326)
A stuck file header left a gap the size of the list's top padding and showed
the diff scrolling by through it and outside its rounded corners. It now sticks
past the padding, draws its own top border, and covers the area behind it.
2026-11-27 10:53:31 +08:00
Fabio Nunes d41feefc07 feat(editor): remember the encoding chosen for a file or folder (#5510)
The encoding chosen for a file from the status bar (Reload or Convert) is remembered for that file across reopening and restarts, and a folder can have an encoding its files inherit (project settings). A converted file keeps its new encoding once saved. Precedence: a file's own choice, then the .editorconfig charset, then the folder mapping.

Co-authored-by: LittleGuava <[email protected]>
2026-11-27 10:43:43 +08:00
l0ng-ai f0fe910017 fix(agents): use a declared radius token for the sign-in terminal (#6320) 2026-11-27 10:37:24 +08:00
l0ng-ai b932220b41 fix(plugins): color Java annotations from a theme plugin's annotation key (#6317)
Java annotations are drawn with --syn-decorator, but a theme plugin's
ANNOTATION_NAME_ATTRIBUTES only set --syn-annotation, so they kept the
DEFAULT_METADATA color. The annotation key now sets both, and
DEFAULT_METADATA applies only when neither the file nor its bundled parent
(Default, Darcula) defines the annotation key, as for imported schemes.
2026-11-27 10:35:42 +08:00
l0ng-ai bcad8f61cb fix(debugger): don't sync the closed project's breakpoint files (#6315)
Closing a project reloads the breakpoints with no project, which rescheduled
every file the project had breakpoints in with an empty list. Each sync then
failed in the backend (no project in the window) and logged
debugSetBreakpoints failed. Per-file syncs now wait for a project as well.
2026-11-27 10:35:32 +08:00
l0ng-ai 2cdcb888cf fix(viewers): update the SVG preview's size when the typed source changes it (#6314)
WebKit keeps the natural size of an <img> that has a CSS size when its src
changes to another SVG, so editing the root's width or height left the live
preview and its dimension readout at the old size. The preview now measures
each typed source with a detached image.
2026-11-27 10:35:22 +08:00
l0ng-ai 9ed0fd9fa7 fix(ci): format the API 1.18 run output test and fit the commit chooser's macOS Close button (#6319)
The Plugins job's rustfmt check failed on `sdk/rust/openidea-plugin/tests/api18_run_output_mode.rs`. Since dialogs on macOS show as sheets (#6208), a dialog without footer buttons gets a Close button and a taller title, so the Git Log commit chooser is taller than `e2e/gitLogCommitChooser.spec.ts` allowed.
2026-11-27 10:35:14 +08:00
Vladislav Kuzmin fe76dc4573 test(viewers): select SVG source with the fixture keymap (#6297)
The browser fixture uses macOS shortcuts on every host. Playwright resolves `ControlOrMeta+A` to Ctrl+A on Linux, so the test inserts the new SVG without replacing the existing source. Use `Meta+A` to match the fixture's keymap.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:55 +08:00
Vladislav Kuzmin 45a75f782a fix(ci): scope the managed gh test helper to Unix (#6287)
Windows Clippy fails because the managed GitHub CLI accessor is compiled on every test target and its only caller is Unix-only. Give the accessor the same test and Unix conditions as its caller.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:47 +08:00
Vladislav Kuzmin bd1fd011e4 test(editor): include File Color in tab menu groups (#6280)
The editor tab menu gained a File Color group in #6105. The layout test still expected Copy Path/Reference in that position and compared four groups, so it failed before it could check splitting and pinning. Include File Color and compare all five original and new groups in order.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:38 +08:00
Vladislav Kuzmin b44015b2ce fix(frontend): remove unused VCS and Markdown exports (#6279)
Remove the unused VCS date wrapper and the Markdown layout-mode alias left behind after their callers moved to the shared formatting and viewer code. The VCS model also drops its unused import. The author-hint comment now describes the shared formatting behavior without pointing to a removed function.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:30 +08:00
l0ng-ai 0cce0a9840 fix(problems): start TypeScript Project Errors when the option is turned on (#6316)
The desktop app's settings_set has its own copy of the side effects of a
changed setting, and the tsc --watch watcher was only started from the host
command's copy, so turning on Problems › TypeScript Project Errors did
nothing until the project was reopened. Both commands now share
apply_setting, which also applies the terminal frame rate on desktop.
2026-11-27 10:28:13 +08:00
l0ng-ai db8224f74e perf(agents): stop a running task's Changes tab from reloading every diff on each update (#6298)
While a task runs, it is published again with every token count. The Changes tab rebuilt its
diff items from the whole task object, so each update re-read the base text of every changed
file over IPC, hashed all of them, and handed the view a new array that rendered every mounted
diff block and every row of the file tree again. The diffs now depend only on the task fields
they use (id, base, isolation, branch, cwd), an unchanged list keeps its array, and the file
tree is memoized. The all-in-one diff also works out each diff's key once per list instead of
hashing every file's text on every scroll frame (autosave off).
2026-11-27 10:03:35 +08:00
Fabio Nunes b075f5de2a feat(editorconfig): apply charset to existing files and accept the listed encodings (#5509)
An .editorconfig charset now applies to existing files when they are opened and decoded, not only to new ones, and every charset EditorConfig lists is accepted (latin1, utf-8, utf-8-bom, utf-16be, utf-16le). Find in Files decodes closed files with that charset too, so a Latin-1 file is found by its accented text.

Co-authored-by: LittleGuava <[email protected]>
2026-11-27 09:51:49 +08:00
Nguyen Thinh 3240164840 feat(database): warn before running a statement that changes a whole table (#1496)
Before the SQL console runs a statement that changes or clears a whole table (a DELETE or UPDATE without WHERE, and similar cases), it shows a warning banner with Execute, Execute and Suppress (no more warnings in this console) and close; nothing runs until the user chooses. The statement also gets a squiggle, a gutter icon and a hover. The check runs on the text after parameter substitution, and works with the console's streaming execution.

Co-authored-by: kidp2h <[email protected]>
2026-11-27 09:39:21 +08:00
l0ng-ai f70f362a3d feat(ui): open New Project, Get from VCS and Remote Development in their own windows (#6208)
* feat(ui): open New Project, Get from VCS and Remote Development in their own windows

Each dialog gets a native window over its project window: a full-height
sidebar under the traffic lights, the title heading the content and the
buttons in its corner. The windows hand their result back to the project
window, which opens the created or cloned project or makes the remote
connection and reports its progress. Remote windows and the browser build
keep the dialogs in the page.

* feat(ui): show dialogs in the page as sheets without window buttons on macOS

The title heads the content instead of a title bar with drawn traffic
lights; Esc and Cancel close the dialog, and the title dims while the
window is inactive.

* fix(ui): give a macOS dialog without footer buttons a Close button

A sheet has no window buttons, so a dialog with neither buttons nor a
footer could only be closed with Esc. The Extract Interface members
table may shrink to two rows so the dialog still fits a short window
under the taller sheet title.
2026-11-27 08:59:33 +08:00
l0ng-ai 806bb4c78d ci(homebrew): push the cask to the tap with a deploy key (#6205) 2026-11-27 08:59:26 +08:00
Mansur Akhmadiтаmansur-akhmadi 57094bc285 feat(run): Track Running Test in Test Runner Options (#6285)
Test Runner Options gets Track Running Test (also in Find Action as run.toggleTrackRunningTest), remembered with the other test tree options and on by default. While a run is in progress, each test that starts is selected, its collapsed suites opened and its output shown; when several start together the last in tree order wins. A test finishing doesn't move the selection, so a test picked by hand stays selected until the next one starts, and focus doesn't move.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 08:18:37 +08:00
Deng Liuтаdengliu a5e0c41663 feat(github): add project-scoped GitHub CLI account selection (#6277)
A project can pin a GitHub CLI account in vcs.github.account (.openidea/settings.toml, a login, never a token), chosen in Settings > Version Control > GitHub or from the Pull Requests tool window header. With an account chosen, its token is resolved through gh and set as GH_TOKEN in the project environment for the project root and its agent worktrees; a .envrc GH_TOKEN still wins, and the token is cleared when the project closes or loses trust. Copilot keeps billing to its own account through COPILOT_GITHUB_TOKEN.

Automatic (the default) sets no GH_TOKEN and makes no GitHub calls on project open. When the settings page or the Pull Requests window asks for the status with several gh accounts signed in, the project's GitHub remote is probed to suggest a non-active account with access ("Use <login> for this project").

New commands: gh_project_account_status, gh_set_project_account. The gh account listing is shared with the Copilot account selector.

Co-authored-by: dengliu <[email protected]>
2026-11-27 08:16:10 +08:00
742 змінених файлів з 34873 додано та 2773 видалено

No files matched your search

+7 -6
Переглянути файл
@@ -3,7 +3,8 @@ name: Homebrew
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
# l0ng-ai/homebrew-tap).
on:
workflow_call:
inputs:
@@ -27,17 +28,17 @@ jobs:
env:
TAG: ${{ inputs.tag }}
TAP: l0ng-ai/homebrew-tap
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
GH_TOKEN: ${{ github.token }}
steps:
- name: Check tag and token
- name: Check tag and deploy key
id: check
run: |
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "::notice::$TAG is not a stable release: the cask stays as is"
echo "skip=true" >> "$GITHUB_OUTPUT"
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
@@ -47,7 +48,7 @@ jobs:
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
path: tap
- uses: actions/setup-node@v5
if: steps.check.outputs.skip != 'true'
+2 -1
Переглянути файл
@@ -39,6 +39,7 @@ on:
- "src/editor/lsp/hint.ts"
- "src/editor/lsp/lsp.ts"
- "src/editor/lsp/positions.ts"
- "src/editor/lsp/snippet.ts"
- "src/bindings.ts"
- "src/styles/tokens.css"
- "src/test/setup.ts"
@@ -106,7 +107,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+1 -1
Переглянути файл
@@ -179,7 +179,7 @@ jobs:
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
secrets: inherit
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
homebrew:
needs: publish
uses: ./.github/workflows/homebrew.yml
Створено
+50 -48
Переглянути файл
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4182,7 +4182,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"serde",
@@ -4205,7 +4205,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"chardetng",
@@ -4223,7 +4223,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4248,7 +4248,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4259,7 +4259,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4281,7 +4281,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-run",
@@ -4294,7 +4294,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4323,7 +4323,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4362,7 +4362,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"serde",
@@ -4375,7 +4375,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4389,7 +4389,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4409,7 +4409,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-android",
"ide-core",
@@ -4420,7 +4420,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4432,7 +4432,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4444,7 +4444,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"ide-core",
@@ -4463,7 +4463,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4519,6 +4519,7 @@ dependencies = [
"ide-workspace",
"ignore",
"jsonschema",
"notify",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"regex-lite",
@@ -4544,7 +4545,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"hyper-util",
"ide-core",
@@ -4563,7 +4564,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"criterion",
@@ -4586,7 +4587,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4598,7 +4599,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4614,7 +4615,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"libc",
"tempfile",
@@ -4623,7 +4624,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"futures",
"serde",
@@ -4634,7 +4635,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"criterion",
@@ -4693,7 +4694,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"dunce",
@@ -4704,6 +4705,7 @@ dependencies = [
"ide-jsonrpc",
"ide-jvm-inspect",
"ide-language",
"ide-sdk",
"ide-text",
"ide-vfs",
"ignore",
@@ -4722,7 +4724,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"bytes",
"dunce",
@@ -4741,7 +4743,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4762,7 +4764,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"dunce",
@@ -4784,7 +4786,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4798,7 +4800,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dunce",
"futures",
@@ -4818,7 +4820,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dunce",
"encoding_rs",
@@ -4843,7 +4845,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-tools",
@@ -4859,7 +4861,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4885,7 +4887,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"encoding_rs",
@@ -4906,7 +4908,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"parking_lot 0.12.5",
@@ -4919,7 +4921,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4944,7 +4946,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-language",
@@ -4957,7 +4959,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-language",
@@ -4972,7 +4974,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"libc",
@@ -4986,7 +4988,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"ide-core",
@@ -4999,7 +5001,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"flate2",
"hex",
@@ -5022,7 +5024,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"dunce",
@@ -5044,7 +5046,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"chardetng",
"dunce",
@@ -5071,7 +5073,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5087,7 +5089,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"dunce",
@@ -6726,7 +6728,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.53"
version = "0.1.54"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
Err(err)
if !prefer_stored
&& crate::provider::is_copilot_provider(&spec.id)
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
&& super::auth_required(0, &err) =>
{
let retry = run_once(shared, spec, true, model).await;
+34
Переглянути файл
@@ -627,6 +627,40 @@ impl crate::AgentManager {
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
}
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
.into_iter()
.find(|p| p.id == "copilot")
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
let account = account.trim();
if !account.is_empty() {
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
}
match discover(&self.shared, spec, model).await {
Ok(found) => Ok(AgentModelCatalog {
provider: "copilot".into(),
config: self.shared.config_for_new_task(found.config, "copilot"),
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
refreshing: false,
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
retry_at_ms: None,
error: None,
}),
Err(error) => Ok(AgentModelCatalog {
provider: "copilot".into(),
config: Vec::new(),
thought_levels: BTreeMap::new(),
refreshing: false,
refreshed_at_ms: None,
retry_at_ms: None,
error: Some(error),
}),
}
}
}
async fn discover(
+275 -73
Переглянути файл
@@ -505,6 +505,84 @@ struct TaskFile {
pending_native_fork: Option<ForkStart>,
}
/// A task file with its history left unread: what is decoded for every task at startup.
#[derive(Deserialize)]
struct SavedHead {
entries: Counted,
#[serde(default, rename = "subagents")]
_subagents: serde::de::IgnoredAny,
#[serde(default, rename = "turn")]
_turn: serde::de::IgnoredAny,
#[serde(default, rename = "turns")]
_turns: serde::de::IgnoredAny,
#[serde(flatten)]
rest: serde_json::Map<String, Value>,
}
/// The history in a task file, the rest left unread.
#[derive(Deserialize)]
struct SavedBody {
entries: Vec<Value>,
#[serde(default)]
subagents: Vec<SavedSubagent>,
#[serde(default)]
turn: Option<worktree::TurnStart>,
#[serde(default)]
turns: Vec<Option<worktree::TurnStart>>,
}
/// The length of a JSON array, its items skipped.
struct Counted(usize);
impl<'de> Deserialize<'de> for Counted {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Counted;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("an array")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Counted, A::Error> {
let mut n = 0;
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
n += 1;
}
Ok(Counted(n))
}
}
deserializer.deserialize_seq(Visitor)
}
}
/// A task file without its history (empty in the result), and how many entries its
/// conversation has.
fn read_head(bytes: &[u8]) -> Result<(TaskFile, usize), String> {
let head: SavedHead = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
let mut rest = head.rest;
rest.insert("entries".into(), json!([]));
let file = serde_json::from_value::<TaskFile>(upgrade(Value::Object(rest))).map_err(|e| e.to_string())?;
Ok((file, head.entries.0))
}
/// The history saved in the task file at `path`.
fn read_body(path: &Path) -> Result<History, String> {
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
let body: SavedBody = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
drop(bytes);
let entries = body
.entries
.into_iter()
.map(|mut entry| {
upgrade_entry(&mut entry);
serde_json::from_value::<AgentEntry>(entry)
})
.collect::<Result<Vec<_>, _>>()
.map_err(|e| e.to_string())?;
Ok(History::new(entries, body.subagents, body.turn, body.turns))
}
/// A session to start as a fork of the recorded one: its source, and the id the host
/// chooses for the fork (claude); codex assigns its own.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -568,10 +646,97 @@ impl Drop for BusyGuard {
}
}
/// A task's conversation and the checkout as each of its turns started.
#[derive(Default)]
struct History {
conversation: Conversation,
/// See `TaskFile::turns`.
turns: Vec<Option<Arc<worktree::TurnStart>>>,
/// The task file's conversation couldn't be read: the task shows an empty one, and saving
/// it is refused so the file keeps what it has.
unreadable: bool,
}
impl History {
fn new(
entries: Vec<AgentEntry>,
subagents: Vec<SavedSubagent>,
turn: Option<worktree::TurnStart>,
turns: Vec<Option<worktree::TurnStart>>,
) -> Self {
let conversation = Conversation::restore(entries, subagents);
let mut turns: Vec<_> = turns.into_iter().map(|t| t.map(Arc::new)).collect();
// Saved with the last turn's only: the turns before it have none.
if turns.is_empty()
&& let Some(last) = turn
{
turns.resize(turn_starts(&conversation.main.entries).len().saturating_sub(1), None);
turns.push(Some(Arc::new(last)));
}
Self { conversation, turns, unreadable: false }
}
/// The history saved in the task file at `path`, settled: the agent that was running
/// when it was saved did not survive the restart.
fn read(path: &Path) -> Self {
match read_body(path) {
Ok(mut history) => {
history.conversation.settle(now_ms());
history
}
Err(e) => {
tracing::warn!("reading the conversation of agent task {}: {e}", path.display());
Self { unreadable: true, ..Self::default() }
}
}
}
}
/// A task's [`History`], read from its file the first time anything needs it: most tasks of
/// a project aren't opened between two starts, and their conversations are most of what the
/// task store holds.
struct StoredHistory {
/// The task file, for a history not read yet.
file: Option<PathBuf>,
history: std::cell::OnceCell<History>,
}
impl StoredHistory {
fn loaded(history: History) -> Self {
Self { file: None, history: std::cell::OnceCell::from(history) }
}
fn on_disk(file: PathBuf) -> Self {
Self { file: Some(file), history: std::cell::OnceCell::new() }
}
/// Whether the history is in memory (tests).
#[cfg(test)]
fn is_loaded(&self) -> bool {
self.history.get().is_some()
}
}
impl std::ops::Deref for StoredHistory {
type Target = History;
fn deref(&self) -> &History {
self.history.get_or_init(|| self.file.as_deref().map(History::read).unwrap_or_default())
}
}
impl std::ops::DerefMut for StoredHistory {
fn deref_mut(&mut self) -> &mut History {
let _ = &**self;
self.history.get_mut().expect("the history was just read")
}
}
struct TaskState {
task: AgentTask,
session_id: Option<String>,
conversation: Conversation,
/// The conversation and its turns' checkouts, read from the task file on first use.
history: StoredHistory,
wanted: Vec<AgentConfigChoice>,
pending_model: Option<PendingModel>,
model_choice: u64,
@@ -580,8 +745,6 @@ struct TaskState {
saved: Option<String>,
/// See `TaskFile::touched`.
touched: Option<Arc<BTreeSet<String>>>,
/// See `TaskFile::turns`.
turns: Vec<Option<Arc<worktree::TurnStart>>>,
pending_rollback: u32,
/// The user named the task; see `TaskFile::title_renamed`.
title_renamed: bool,
@@ -767,20 +930,21 @@ impl AgentManager {
if path.extension().is_none_or(|e| e != "json") {
continue;
}
match std::fs::read(&path)
.map_err(|e| e.to_string())
.and_then(|b| serde_json::from_slice::<Value>(&b).map_err(|e| e.to_string()))
.and_then(|v| serde_json::from_value::<TaskFile>(upgrade(v)).map_err(|e| e.to_string()))
{
Ok(mut f) => {
// Only the task's own fields: its conversation is read when something needs it.
match std::fs::read(&path).map_err(|e| e.to_string()).and_then(|b| read_head(&b)) {
Ok((mut f, entries)) => {
// The agent process did not survive the restart: whatever was in flight is over.
if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) {
f.task.status = AgentStatus::Ready;
}
f.task.retry = None;
f.task.background.clear();
let task = Task::restore(f, shared.clone());
task.state.lock().conversation.settle(now_ms());
// What an archived task's agent offered is only a cache, and a long list
// repeated in every archived task: its next session reports its own.
if f.task.status == AgentStatus::Archived {
f.task.commands = Vec::new();
}
let task = Task::restore_saved(f, entries, path, shared.clone());
tasks.insert(task.id.clone(), task);
}
Err(e) => tracing::warn!("skipping agent task {}: {e}", path.display()),
@@ -832,6 +996,11 @@ impl AgentManager {
*self.shared.git_executable.write() = Some(hook);
}
/// Directory holding linked Git worktrees created for agent tasks of this project.
pub fn worktrees_dir(&self) -> &Path {
&self.shared.paths.worktrees_dir
}
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
pub fn providers(&self) -> Vec<AgentProvider> {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
@@ -979,7 +1148,14 @@ impl AgentManager {
Some(id) => {
let task = self.task(id)?;
let s = task.state.lock();
(s.task.provider.clone(), s.task.commands.clone(), s.task.cwd.0.clone())
// A task without a session's list yet (archived, or just unarchived) offers
// what its agent offered last time in the project.
let offered = if s.task.commands.is_empty() {
self.shared.known_commands(&s.task.provider)
} else {
s.task.commands.clone()
};
(s.task.provider.clone(), offered, s.task.cwd.0.clone())
}
None => (provider.to_owned(), self.shared.known_commands(provider), self.shared.paths.project_root.clone()),
};
@@ -1068,7 +1244,8 @@ impl AgentManager {
pub fn entries(&self, id: &str, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
let task = self.task(id)?;
let s = task.state.lock();
let timeline = s.conversation.timeline(&subagent).ok_or_else(|| IdeError::not_found("no such subagent"))?;
let timeline =
s.history.conversation.timeline(&subagent).ok_or_else(|| IdeError::not_found("no such subagent"))?;
Ok(timeline.entries.clone())
}
@@ -1673,7 +1850,7 @@ impl AgentManager {
return Err(IdeError::invalid("wait until the agent is done"));
}
let live = source.ensure_session().await.map_err(IdeError::internal)?;
let total = turn_starts(&source.state.lock().conversation.main.entries).len() as u32;
let total = turn_starts(&source.state.lock().history.conversation.main.entries).len() as u32;
let keep = turns.unwrap_or(total).min(total);
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
@@ -1707,7 +1884,7 @@ impl AgentManager {
.to_owned();
let file = {
let s = source.state.lock();
let mut entries = s.conversation.main.entries.clone();
let mut entries = s.history.conversation.main.entries.clone();
if let Some(&cut) = turn_starts(&entries).get(keep as usize) {
entries.truncate(cut);
}
@@ -1739,7 +1916,7 @@ impl AgentManager {
// The copies are the source's: the fork's turns are recorded as it runs them.
turn: None,
turns: Vec::new(),
subagents: s.conversation.saved_subagents(),
subagents: s.history.conversation.saved_subagents(),
pending_rollback: total - keep,
title_renamed: s.title_renamed,
ephemeral: s.ephemeral,
@@ -1767,7 +1944,7 @@ impl AgentManager {
if s.busy {
return Err(IdeError::invalid("wait until the agent is done"));
}
let starts = turn_starts(&s.conversation.main.entries);
let starts = turn_starts(&s.history.conversation.main.entries);
let Some(&cut) = starts.get(turns as usize) else { return Ok(None) };
s.busy = true;
(starts, cut)
@@ -1783,7 +1960,7 @@ impl AgentManager {
let restamped = self.write_rewind(&task, planned).await?;
let (first, dir, kept) = {
let mut s = task.state.lock();
let first = match s.conversation.main.entries.get(cut) {
let first = match s.history.conversation.main.entries.get(cut) {
Some(AgentEntry::User { text, .. }) => {
Some(AgentPrompt { text: text.clone(), ..Default::default() })
}
@@ -1793,13 +1970,13 @@ impl AgentManager {
s.pending_model = None;
s.model_choice += 1;
s.discovering_model = None;
s.conversation = Conversation::default();
s.history.conversation = Conversation::default();
// The fresh session reports its own usage; nothing carries over.
s.task.usage = None;
s.pending_rollback = 0;
s.task.updated_ms = now_ms();
Self::finish_rewind(&mut s, 0, restamped);
(first, task.turn_dir(), s.turns.clone())
(first, task.turn_dir(), s.history.turns.clone())
};
drop(guard);
task.streamed.lock().clear();
@@ -1822,14 +1999,14 @@ impl AgentManager {
let restamped = self.write_rewind(&task, planned).await?;
let (first, dir, kept) = {
let mut s = task.state.lock();
let first = match s.conversation.main.entries.get(cut) {
let first = match s.history.conversation.main.entries.get(cut) {
Some(AgentEntry::User { text, .. }) => Some(AgentPrompt { text: text.clone(), ..Default::default() }),
_ => None,
};
s.conversation.truncate(cut);
s.history.conversation.truncate(cut);
s.task.updated_ms = now_ms();
Self::finish_rewind(&mut s, turns as usize, restamped);
(first, task.turn_dir(), s.turns.clone())
(first, task.turn_dir(), s.history.turns.clone())
};
drop(guard);
task.streamed.lock().clear();
@@ -2004,7 +2181,8 @@ impl AgentManager {
let _answering = task.answering_questions.lock().await;
let questions = {
let s = task.state.lock();
s.conversation
s.history
.conversation
.main
.entries
.iter()
@@ -2032,7 +2210,7 @@ impl AgentManager {
};
let changed = {
let mut s = task.state.lock();
s.conversation.main.entries.iter_mut().enumerate().find_map(|(index, entry)| match entry {
s.history.conversation.main.entries.iter_mut().enumerate().find_map(|(index, entry)| match entry {
AgentEntry::Question { id, chosen: current, .. } if id == question => {
*current = Some(chosen.clone());
Some((None, index))
@@ -2049,6 +2227,8 @@ impl AgentManager {
pub fn archive(&self, id: &str) -> IdeResult<()> {
let task = self.task(id)?;
task.kill();
// Not kept while archived; see `AgentManager::new`.
task.state.lock().task.commands = Vec::new();
task.set_status(AgentStatus::Archived, None);
Ok(())
}
@@ -2203,8 +2383,8 @@ impl AgentManager {
) -> IdeResult<Vec<worktree::PutBack>> {
let (cwd, start, before, saved, touched, dropped_changed) = {
let s = task.state.lock();
let start = s.turns.get(turn).cloned().flatten();
let dropped = s.turns.get(turn..).unwrap_or(&[]);
let start = s.history.turns.get(turn).cloned().flatten();
let dropped = s.history.turns.get(turn..).unwrap_or(&[]);
let dropped_changed = (dropped.len() == total_turns - turn
&& dropped.iter().all(|t| t.as_ref().is_some_and(|t| t.changed.is_some())))
.then(|| {
@@ -2270,7 +2450,7 @@ impl AgentManager {
/// Drops the records of the turns from `turn` on and applies any restamps to `before`.
fn finish_rewind(s: &mut TaskState, turn: usize, restamped: Vec<(String, worktree::Stamp)>) {
s.turns.truncate(turn);
s.history.turns.truncate(turn);
if !restamped.is_empty() {
let mut before = (*s.before).clone();
before.extend(restamped);
@@ -2342,7 +2522,7 @@ impl AgentManager {
s.before = Arc::new(before);
}
// Rolled back further than the last turn: what it changed there is gone, not the turn's to list.
if let Some(Some(turn)) = s.turns.last_mut()
if let Some(Some(turn)) = s.history.turns.last_mut()
&& let Some(changed) = &turn.changed
&& restored.iter().any(|rel| changed.contains(rel))
{
@@ -2600,19 +2780,29 @@ impl Task {
}
}
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
/// A task whose conversation is at hand (a new task, a copy).
fn restore(mut file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let adopt = file.entries.is_empty() && file.session_id.is_some();
let history = History::new(
std::mem::take(&mut file.entries),
std::mem::take(&mut file.subagents),
file.turn.take(),
std::mem::take(&mut file.turns),
);
Self::assemble(file, StoredHistory::loaded(history), adopt, shared)
}
/// A task read from the store without its conversation (`head`, see [`read_head`]): the
/// conversation is read from `path` once something needs it.
fn restore_saved(head: TaskFile, entries: usize, path: PathBuf, shared: Arc<Shared>) -> Arc<Self> {
let adopt = entries == 0 && head.session_id.is_some();
Self::assemble(head, StoredHistory::on_disk(path), adopt, shared)
}
/// The task from the parts of `file` other than its history, which `history` holds.
fn assemble(file: TaskFile, history: StoredHistory, adopt: bool, shared: Arc<Shared>) -> Arc<Self> {
let mut task = file.task;
config::add_client_options(&task.provider, &mut task.config);
let adopt = file.entries.is_empty() && file.session_id.is_some();
let conversation = Conversation::restore(file.entries, file.subagents);
let mut turns: Vec<_> = file.turns.into_iter().map(|t| t.map(Arc::new)).collect();
// Saved with the last turn's only: the turns before it have none.
if turns.is_empty()
&& let Some(last) = file.turn
{
turns.resize(turn_starts(&conversation.main.entries).len().saturating_sub(1), None);
turns.push(Some(Arc::new(last)));
}
let mut wanted = file.wanted;
let mut pending_model = file.pending_switch.or_else(|| {
let id = file.pending_model?;
@@ -2643,7 +2833,7 @@ impl Task {
state: Mutex::new(TaskState {
task,
session_id: file.session_id,
conversation,
history,
wanted,
pending_model,
model_choice: 0,
@@ -2651,7 +2841,6 @@ impl Task {
before: Arc::new(file.before),
saved: file.saved,
touched: file.touched.map(Arc::new),
turns,
pending_rollback: file.pending_rollback,
title_renamed: file.title_renamed,
ephemeral: file.ephemeral,
@@ -2700,7 +2889,7 @@ impl Task {
/// The checkout as the last turn started, with the folder of its copies.
fn last_turn(&self) -> (PathBuf, Option<Arc<worktree::TurnStart>>, PathBuf) {
let s = self.state.lock();
(s.task.cwd.0.clone(), s.turns.last().cloned().flatten(), self.turn_dir())
(s.task.cwd.0.clone(), s.history.turns.last().cloned().flatten(), self.turn_dir())
}
/// Records the checkout as a turn starts (its message shown): what the turn's changes are
@@ -2708,8 +2897,8 @@ impl Task {
async fn checkout_before_turn(self: &Arc<Self>) {
let (cwd, dir, index, earlier) = {
let s = self.state.lock();
let index = turn_starts(&s.conversation.main.entries).len().saturating_sub(1);
let earlier: Vec<_> = s.turns.iter().take(index).cloned().collect();
let index = turn_starts(&s.history.conversation.main.entries).len().saturating_sub(1);
let earlier: Vec<_> = s.history.turns.iter().take(index).cloned().collect();
(s.task.cwd.0.clone(), self.turn_dir(), index, earlier)
};
let kept = earlier.clone();
@@ -2728,9 +2917,9 @@ impl Task {
};
{
let mut s = self.state.lock();
s.turns = earlier;
s.turns.resize(index, None);
s.turns.push(turn);
s.history.turns = earlier;
s.history.turns.resize(index, None);
s.history.turns.push(turn);
}
self.persist_soon();
}
@@ -2753,7 +2942,7 @@ impl Task {
touched.extend(in_worktree);
s.touched = Some(Arc::new(touched));
}
if let Some(last) = s.turns.last_mut() {
if let Some(last) = s.history.turns.last_mut() {
*last = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
}
}
@@ -2918,10 +3107,14 @@ impl Task {
}
let copy = {
let s = self.state.lock();
if s.history.unreadable {
tracing::warn!("not saving agent task {}: its conversation couldn't be read", self.id);
return;
}
TaskFile {
task: s.task.clone(),
session_id: s.session_id.clone(),
entries: s.conversation.main.entries.clone(),
entries: s.history.conversation.main.entries.clone(),
wanted: s.wanted.clone(),
pending_model: None,
pending_switch: s.pending_model.clone(),
@@ -2929,8 +3122,8 @@ impl Task {
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
turn: None,
turns: s.turns.iter().map(|t| t.as_deref().cloned()).collect(),
subagents: s.conversation.saved_subagents(),
turns: s.history.turns.iter().map(|t| t.as_deref().cloned()).collect(),
subagents: s.history.conversation.saved_subagents(),
pending_rollback: s.pending_rollback,
title_renamed: s.title_renamed,
ephemeral: s.ephemeral,
@@ -2966,7 +3159,7 @@ impl Task {
indices
.into_iter()
.filter_map(|(subagent, i)| {
let entry = s.conversation.timeline(&subagent)?.entries.get(i)?;
let entry = s.history.conversation.timeline(&subagent)?.entries.get(i)?;
entry_event(&self.id, &mut streamed, subagent, i, entry)
})
.collect()
@@ -2978,7 +3171,7 @@ impl Task {
/// Folds an update made here (not by the agent) into the main conversation.
fn apply_local(self: &Arc<Self>, update: &Value) {
let changed = self.state.lock().conversation.apply(None, update, now_ms());
let changed = self.state.lock().history.conversation.apply(None, update, now_ms());
self.mark_dirty(changed);
}
@@ -3007,8 +3200,8 @@ impl Task {
fn take_entries(self: &Arc<Self>) -> Vec<AgentEntry> {
let entries = {
let mut s = self.state.lock();
let entries = s.conversation.main.entries.clone();
s.conversation.truncate(0);
let entries = s.history.conversation.main.entries.clone();
s.history.conversation.truncate(0);
entries
};
self.streamed.lock().clear();
@@ -3017,7 +3210,7 @@ impl Task {
}
fn push_entry(self: &Arc<Self>, entry: AgentEntry) -> usize {
let i = self.state.lock().conversation.main.push(entry);
let i = self.state.lock().history.conversation.main.push(entry);
self.mark_dirty([(None, i)]);
i
}
@@ -3033,7 +3226,7 @@ impl Task {
self.cancel_pending.store(false, Ordering::Release);
tokio::time::sleep(TURN_GRACE).await;
self.record_turn_changes().await;
let changed = self.state.lock().conversation.end_turn(Some(now_ms()));
let changed = self.state.lock().history.conversation.end_turn(Some(now_ms()));
self.mark_dirty(changed);
let send_now = self.send_now.swap(false, Ordering::AcqRel);
let next = {
@@ -3280,7 +3473,7 @@ impl Task {
self.cancel_permissions();
let gone = self.live.lock().as_ref().is_none_or(|l| l.peer.is_closed());
if gone {
let changed = self.state.lock().conversation.settle(now_ms());
let changed = self.state.lock().history.conversation.settle(now_ms());
self.mark_dirty(changed);
}
self.push_entry(AgentEntry::Error { message: failure.message.clone() });
@@ -3682,7 +3875,7 @@ impl Task {
if let Some(shown) = shown {
if loaded.is_ok() {
self.adopting_replay.store(false, Ordering::Release);
let changed = self.state.lock().conversation.end_turn(None);
let changed = self.state.lock().history.conversation.end_turn(None);
self.mark_dirty(changed);
} else {
// A failed load may still have replayed part of it.
@@ -4017,7 +4210,7 @@ impl Task {
fn on_update(self: &Arc<Self>, session: Option<&str>, update: &Value) {
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
// A subagent's title, settings and usage are its own, not the task's.
if self.state.lock().conversation.owner(session).is_some() {
if self.state.lock().history.conversation.owner(session).is_some() {
if !SESSION_STATE.contains(&kind) && (!self.replaying.load(Ordering::Acquire) || self.adopts_replay()) {
self.apply(session, kind, update);
}
@@ -4167,14 +4360,14 @@ impl Task {
}
let changed = {
let mut s = self.state.lock();
let entries = &mut s.conversation.main.entries;
let entries = &mut s.history.conversation.main.entries;
// The chunks of one message arrive in a row.
if let Some(AgentEntry::User { text: shown, images, .. }) = entries.last_mut() {
shown.push_str(&text);
images.extend(image);
entries.len() - 1
} else {
s.conversation.main.push(AgentEntry::User {
s.history.conversation.main.push(AgentEntry::User {
text,
attachments: Vec::new(),
images: image.into_iter().collect(),
@@ -4190,7 +4383,7 @@ impl Task {
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
// Output again: the retried request went through.
self.set_retry(None);
let applied = self.state.lock().conversation.apply(session, update, now_ms());
let applied = self.state.lock().history.conversation.apply(session, update, now_ms());
self.mark_dirty(applied);
// A subagent can start or finish after the turn that started it: nothing else saves it then.
if matches!(kind, "subagent_update" | "user_question") {
@@ -4342,7 +4535,7 @@ impl Task {
/// A request from a subagent is answered in the task's conversation, named after the subagent.
fn labelled(&self, params: &Value, title: String) -> String {
let session = params.get("sessionId").and_then(Value::as_str);
match session.and_then(|s| self.state.lock().conversation.label(s)) {
match session.and_then(|s| self.state.lock().history.conversation.label(s)) {
Some(label) => format!("{label}: {title}"),
None => title,
}
@@ -4381,7 +4574,9 @@ impl Task {
fn settle(self: &Arc<Self>, entry: usize, chosen: String) {
{
let mut s = self.state.lock();
if let Some(AgentEntry::Permission { chosen: answer, .. }) = s.conversation.main.entries.get_mut(entry) {
if let Some(AgentEntry::Permission { chosen: answer, .. }) =
s.history.conversation.main.entries.get_mut(entry)
{
*answer = Some(chosen);
}
}
@@ -4403,7 +4598,7 @@ impl Task {
return;
}
let mut pending = self.permissions.lock();
for entry in s.conversation.main.entries.iter().rev() {
for entry in s.history.conversation.main.entries.iter().rev() {
// A request with questions is never satisfied by a bypass: its Submit option
// would answer with no answers.
if let AgentEntry::Permission { id, options, questions, chosen: None, .. } = entry
@@ -4644,15 +4839,20 @@ fn upgrade(mut file: Value) -> Value {
}
}
for entry in file.get_mut("entries").and_then(Value::as_array_mut).into_iter().flatten() {
if entry.get("type").and_then(Value::as_str) == Some("user")
&& let Some(e) = entry.as_object_mut()
{
e.entry("attachments").or_insert(json!([]));
}
upgrade_entry(entry);
}
file
}
/// Fills in what an entry saved by an earlier version leaves out.
fn upgrade_entry(entry: &mut Value) {
if entry.get("type").and_then(Value::as_str) == Some("user")
&& let Some(e) = entry.as_object_mut()
{
e.entry("attachments").or_insert(json!([]));
}
}
/// Why a turn failed.
struct Failure {
message: String,
@@ -5100,7 +5300,8 @@ fn tool_event(
i: usize,
entry: &AgentEntry,
) -> Option<AgentEvent> {
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms } = entry
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms, command } =
entry
else {
return None;
};
@@ -5115,6 +5316,7 @@ fn tool_event(
diffs: diffs.clone(),
started_ms: *started_ms,
ended_ms: *ended_ms,
command: command.clone(),
};
let text = output.as_deref().unwrap_or_default();
let key = (subagent, i);
+3
Переглянути файл
@@ -547,6 +547,9 @@ pub enum AgentEntry {
started_ms: Option<f64>,
#[serde(default)]
ended_ms: Option<f64>,
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
#[serde(default)]
command: Option<String>,
},
Plan {
items: Vec<AgentPlanItem>,
+1 -2
Переглянути файл
@@ -1481,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
let message = translate::error_message(&e);
return match translate::classify(&e, rate_limits) {
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
Failure::UsageLimit(resets) => Err(ResponseError {
code: codes::INTERNAL_ERROR,
message,
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
}),
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
};
}
_ => "end_turn",
+84
Переглянути файл
@@ -455,6 +455,90 @@ fn failures_are_classified() {
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
}
#[test]
fn failed_turns_preserve_codex_error_diagnostics() {
let policy = json!({
"message": "This content was flagged for possible cybersecurity risk.",
"additionalDetails": "Contact support if this is unexpected.",
"codexErrorInfo": "cyberPolicy"
});
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
assert_eq!(failure.code, codes::INTERNAL_ERROR);
assert_eq!(failure.message, expected);
}
// A completed turn's own error wins over an older error notification.
let failure = stop_reason(
&json!({ "status": "failed", "error": policy }),
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
None,
)
.unwrap_err();
assert_eq!(failure.message, expected);
}
#[test]
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
for (value, expected) in [
(
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
"Context is full.\nCodex error: contextWindowExceeded",
),
(
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
),
(
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
"Failed\nbecause",
),
(
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
"Codex failed\nDetails\nCodex error: cyberPolicy",
),
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
(json!({}), "Codex failed"),
] {
assert_eq!(error_message(&value), expected);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
for notification_only in [false, true] {
let mut transcript = load(Scenario::UsageLimit.file());
let policy = json!({
"message": "This content was flagged for possible cybersecurity risk.",
"additionalDetails": "Contact support if this is unexpected.",
"codexErrorInfo": "cyberPolicy"
});
for (out, frame) in &mut transcript.frames {
if *out {
continue;
}
match frame["method"].as_str() {
Some("error") => frame["params"]["error"] = policy.clone(),
Some("turn/completed") => {
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
}
_ => {}
}
}
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
match result(&results, "prompt") {
Err(RpcError::Server { code, message, .. }) => {
assert_eq!(*code, codes::INTERNAL_ERROR);
assert_eq!(
message,
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
);
}
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
}
}
}
#[test]
fn approvals_offer_what_codex_offers_and_always_a_decline() {
let params = json!({"availableDecisions": ["accept",
+20 -6
Переглянути файл
@@ -740,7 +740,7 @@ pub(super) enum Failure {
UsageLimit(Option<f64>),
/// Signed out or refused.
Auth,
/// The model declined.
/// The server blocked the turn under a safety policy.
Refusal,
Other,
}
@@ -780,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
exhausted.map(|s| s * 1000.0)
}
/// The text a failed turn reports: codex's message, with its details.
/// The text a failed turn reports: Codex's message, details and diagnostic code.
pub(super) fn error_message(error: &Value) -> String {
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
_ => message.to_owned(),
let original =
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
let mut message = original.to_owned();
if let Some(details) =
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
&& !original.contains(details)
{
message.push('\n');
message.push_str(details);
}
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
message.push_str(&format!("\nCodex error: {code}"));
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
message.push_str(&format!(" (HTTP {status})"));
}
}
message
}
/// One choice of an approval: what ACP shows and what codex gets back.
+2 -2
Переглянути файл
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
Err(err)
if !prefer_stored
@@ -199,7 +199,7 @@ pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> O
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
tokio::time::timeout(Duration::from_secs(8), async move {
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
if !prefer_stored
&& has_ambient
+55 -12
Переглянути файл
@@ -154,12 +154,26 @@ impl ProviderSpec {
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
let is_copilot = is_copilot_provider(&self.id);
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
let explicit_copilot_token =
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
if let Some(account) = account {
let token = github_token_for_account(&account)?;
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
} else if is_copilot
&& !strip_ambient_tokens
&& !explicit_copilot_token
&& ide_core::project_env::github_token(cwd).is_some()
&& let Some(default_token) = default_github_token()
{
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
}
Ok(resolved)
}
@@ -169,7 +183,7 @@ impl ProviderSpec {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
@@ -275,7 +289,18 @@ fn find_gh_executable() -> Option<PathBuf> {
ide_core::tool_path::find_gh_executable()
}
fn is_valid_github_login(account: &str) -> bool {
let bytes = account.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 39
&& bytes[0].is_ascii_alphanumeric()
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
}
fn github_token_for_account(account: &str) -> Result<String, String> {
if !is_valid_github_login(account) {
return Err(format!("Invalid GitHub account login: {account}"));
}
let program = find_gh_executable()
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
@@ -386,7 +411,8 @@ fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
if entry.state.as_deref().is_some_and(|s| s != "success") {
continue;
}
if matches!(entry.token_source.as_deref(), Some("GITHUB_TOKEN" | "GH_TOKEN" | "COPILOT_GITHUB_TOKEN")) {
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
continue;
}
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
@@ -406,7 +432,8 @@ fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
let trimmed = line.trim();
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
let login = rest.split_whitespace().next().unwrap_or("").trim();
if !login.is_empty() {
current = None;
if !login.is_empty() && !rest.contains("_TOKEN") {
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
current = Some(idx);
} else {
@@ -423,6 +450,20 @@ fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
accounts
}
fn default_github_token() -> Option<String> {
let program = find_gh_executable()?;
let mut command = std::process::Command::new(program);
ide_core::process::prepare(&mut command);
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
let output = command.output().ok().filter(|out| out.status.success())?;
let token = String::from_utf8(output.stdout).ok()?;
let token = token.trim();
(!token.is_empty()).then(|| token.to_owned())
}
pub(crate) fn prefer_stored_copilot_auth() -> bool {
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
}
@@ -431,18 +472,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
}
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
})
}
fn ambient_copilot_env_value(key: &str) -> Option<String> {
ide_core::process::shell_env()
.find(|(k, _)| *k == key)
.map(|(_, v)| v.to_string_lossy().into_owned())
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
})
}
/// Builds child environment overrides for `copilot`:
@@ -453,9 +493,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
pub(crate) fn sanitized_copilot_env(
spec_env: &[(String, String)],
cwd: &Path,
strip_ambient_tokens: bool,
) -> Vec<(String, String)> {
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
}
pub(crate) fn sanitize_copilot_env_with(
@@ -1695,6 +1736,8 @@ mod tests {
let text = "\
github.com
✓ Logged in to github.com account env_user (GH_TOKEN)
- Active account: true
✓ Logged in to github.com account alice (keyring)
- Active account: false
✓ Logged in to github.com account alice-work (keyring)
+119 -3
Переглянути файл
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
}
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
let tag = format!("v{}", entry.version.trim_start_matches('v'));
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
let sha256_url = format!("{base}/SHA256SUMS.txt");
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
Some(p) => (p.args.clone(), p.env.clone()),
None => (vec!["--acp".into()], BTreeMap::new()),
};
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
let linux_arm = format!(
"copilot-{}-arm64.tar.gz",
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
);
let linux_x64 =
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
let targets = [
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
}
}
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
let (glibc_rel, musl_rel) = match arch {
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
};
let glibc = root.join(glibc_rel);
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
let points_to_musl =
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
let has_glibc = glibc.exists() && !points_to_musl;
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
}
fn safe_segment(s: &str) -> bool {
!s.is_empty()
&& !s.starts_with('.')
@@ -1304,4 +1328,96 @@ esac
assert!(npm_bin.is_file());
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
}
#[test]
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
let index = r#"{"agents":[
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
]}"#;
let archives_for = |root: &Path| -> (String, String) {
let mut entry = parse(index).unwrap().remove(0);
entry.distribution.binary.clear();
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
(
entry.distribution.binary["linux-x86_64"].archive.clone(),
entry.distribution.binary["linux-aarch64"].archive.clone(),
)
};
let touch = |path: PathBuf| {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b"").unwrap();
};
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
let empty = tempfile::tempdir().unwrap();
assert_eq!(
archives_for(empty.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
let glibc = tempfile::tempdir().unwrap();
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
let musl = tempfile::tempdir().unwrap();
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
#[cfg(unix)]
{
fs::create_dir_all(musl.path().join("lib64")).unwrap();
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
.unwrap();
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
}
#[cfg(target_os = "linux")]
{
let parsed = parse(index).unwrap().remove(0);
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
assert!(
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
"unexpected linux-x86_64 archive: {}",
parsed.distribution.binary["linux-x86_64"].archive
);
}
}
}
+1 -1
Переглянути файл
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
}
fn command_from_value(val: &Value) -> Option<String> {
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
match val {
Value::String(s) => {
let trimmed = s.trim();
+95 -11
Переглянути файл
@@ -642,15 +642,98 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
mgr.shutdown();
let restored_agent = Arc::new(FakeAgent::default());
let restored = manager(tmp.path(), restored_agent.clone());
// Listing the tasks leaves the conversation on disk until something asks for it.
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
assert!(!restored.task(&task.id).unwrap().state.lock().history.is_loaded());
assert!(!restored.entries(&task.id, None).unwrap().is_empty());
assert!(restored.task(&task.id).unwrap().state.lock().history.is_loaded());
assert!(restored_agent.calls.lock().is_empty());
assert!(restored.entries("missing-task", None).is_err());
assert!(restored.entries(&task.id, Some("missing-subagent".into())).is_err());
restored.task(&task.id).unwrap().state.lock().conversation = Conversation::default();
restored.task(&task.id).unwrap().state.lock().history.conversation = Conversation::default();
assert!(restored.entries(&task.id, None).unwrap().is_empty());
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("hello"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let names = |list: Vec<AgentCommand>| list.into_iter().map(|c| c.name).collect::<Vec<_>>();
let snapshot = |mgr: &AgentManager| mgr.task(&task.id).unwrap().state.lock().snapshot();
assert!(names(snapshot(&mgr).commands).contains(&"review".to_owned()));
mgr.archive(&task.id).unwrap();
assert!(snapshot(&mgr).commands.is_empty());
assert!(names(mgr.commands("claude", Some(&task.id)).await.unwrap()).contains(&"review".to_owned()));
mgr.shutdown();
// A list saved with an archived task (by an earlier version) isn't read back.
let other = tempfile::tempdir().unwrap();
std::fs::create_dir_all(other.path().join("store")).unwrap();
let name = format!("{}.json", task.id);
let mut file: Value =
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
assert_eq!(file["task"]["status"], json!("archived"));
file["task"]["commands"] = json!([{"name": "old", "description": "Old", "hint": null}]);
std::fs::write(other.path().join("store").join(&name), serde_json::to_vec(&file).unwrap()).unwrap();
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
assert!(snapshot(&restored).commands.is_empty());
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("Keep this"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
// In a store of its own: a late save of the first manager can't touch it.
let name = format!("{}.json", task.id);
let mut file: Value =
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
file["entries"].as_array_mut().unwrap().push(json!({"type": "no-such-entry"}));
let damaged = serde_json::to_vec(&file).unwrap();
let other = tempfile::tempdir().unwrap();
std::fs::create_dir_all(other.path().join("store")).unwrap();
let path = other.path().join("store").join(&name);
std::fs::write(&path, &damaged).unwrap();
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
// The task is listed from its own fields; its conversation shows empty.
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
assert!(restored.entries(&task.id, None).unwrap().is_empty());
restored.rename(&task.id, "Renamed").unwrap();
restored.shutdown();
assert_eq!(std::fs::read(&path).unwrap(), damaged);
}
#[tokio::test(flavor = "multi_thread")]
async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
let tmp = tempfile::tempdir().unwrap();
@@ -1479,9 +1562,9 @@ async fn saving_a_large_task_does_not_hold_up_readers() {
let path = task_file(tmp.path(), &task.id);
for i in 0..24 {
let text = format!("output {i}: \"quoted\"\n").repeat(40_000);
handle.state.lock().conversation.main.push(AgentEntry::Agent { text });
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text });
}
let entries = handle.state.lock().conversation.main.entries.clone();
let entries = handle.state.lock().history.conversation.main.entries.clone();
let started = std::time::Instant::now();
let json = serde_json::to_vec(&entries).unwrap();
let serialising = started.elapsed();
@@ -1574,7 +1657,7 @@ async fn concurrent_saves_keep_the_newest_state_of_each_task() {
let task = idle_task(&mgr, name).await;
let handle = mgr.task(&task.id).unwrap();
// Long enough that a save takes a while between the copy and the write.
handle.state.lock().conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
tasks.push((name, handle, task_file(tmp.path(), &task.id)));
}
// "<name> <n>", n growing with every change made under the state lock.
@@ -2693,7 +2776,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
mgr.shutdown();
let restored = manager(tmp.path(), agent);
let handle = restored.task(&task.id).unwrap();
assert_eq!(handle.state.lock().conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
assert_eq!(handle.state.lock().history.conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
restored.shutdown();
}
@@ -2789,13 +2872,13 @@ async fn forks_rollbacks_and_steering() {
"state": {"state": "idle", "stopReason": "end_turn"}}),
);
}
handle.state.lock().conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
handle.state.lock().history.conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
let rewinds = agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count();
let first = mgr.rollback(&task.id, 0, false).await.unwrap().unwrap();
assert_eq!(first.text, "again");
assert!(mgr.entries(&task.id, None).unwrap().is_empty());
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_none());
assert!(handle.state.lock().conversation.saved_subagents().is_empty());
assert!(handle.state.lock().history.conversation.saved_subagents().is_empty());
assert!(handle.state.lock().task.usage.is_none());
assert_eq!(agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count(), rewinds);
mgr.shutdown();
@@ -4369,6 +4452,7 @@ fn a_running_tools_output_is_sent_as_appends() {
diffs: Vec::new(),
started_ms: Some(1.0),
ended_ms: None,
command: None,
};
let running = |output| call(AgentToolStatus::Running, output);
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
@@ -4950,7 +5034,7 @@ async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
Isolation::Worktree => None,
};
assert_eq!(read("later.txt").as_deref(), later, "{case}");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().turns.len(), 1, "{case}");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().history.turns.len(), 1, "{case}");
// Without `files` they stay; the first message takes the task back to its start.
one_turn(&mgr, &task.id, Some("retry"), || write("a.txt", "again\n")).await;
@@ -4958,7 +5042,7 @@ async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
assert_eq!(read("a.txt").as_deref(), Some("again\n"), "{case}");
mgr.rollback(&task.id, 0, true).await.unwrap();
assert_eq!(read("a.txt").as_deref(), Some("base\n"), "{case}");
assert!(mgr.task(&task.id).unwrap().state.lock().turns.is_empty(), "{case}");
assert!(mgr.task(&task.id).unwrap().state.lock().history.turns.is_empty(), "{case}");
let left = std::fs::read_dir(repo.dir.join("store").join(format!("{}.turn", task.id)));
assert!(left.map_or(true, |mut d| d.next().is_none()), "{case}: no copies left");
mgr.delete(&task.id, true).await.unwrap();
@@ -4979,7 +5063,7 @@ async fn a_message_sent_before_turns_were_recorded_cannot_take_the_files_back()
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
one_turn(&mgr, &task.id, Some("last"), || repo.write("a.txt", "base\nturn 1\nturn 2\nturn 3\n")).await;
// As a task saved with its last turn's record only.
mgr.task(&task.id).unwrap().state.lock().turns[1] = None;
mgr.task(&task.id).unwrap().state.lock().history.turns[1] = None;
assert!(mgr.rollback(&task.id, 1, true).await.is_err());
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 3, "nothing changed");
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\nturn 3\n");
@@ -5007,7 +5091,7 @@ async fn rolling_back_to_first_message_without_turn_record_checks_before_changin
{
let handle = mgr.task(&task.id).unwrap();
let mut s = handle.state.lock();
s.turns[0] = None;
s.history.turns[0] = None;
s.saved = None;
}
assert!(mgr.rollback(&task.id, 0, true).await.is_err());
+35 -1
Переглянути файл
@@ -91,6 +91,7 @@ impl Timeline {
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
command: None,
};
let index = match self.tools.get(&id) {
Some(&i) => {
@@ -154,7 +155,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
&mut self.entries[index]
else {
return;
@@ -171,6 +172,11 @@ impl Timeline {
*ended_ms = Some(crate::now_ms());
}
}
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
&& let Some(cmd) = crate::security::command_from_value(raw)
{
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
}
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
@@ -471,6 +477,34 @@ mod tests {
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn an_execute_call_keeps_the_command_from_its_structured_input() {
let mut t = Timeline::default();
let command = |t: &Timeline, i: usize| match &t.entries[i] {
AgentEntry::Tool { command, .. } => command.clone(),
_ => panic!(),
};
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
"rawInput": {"command": "python hello_world.py"}}));
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
// An argv array whose shell wraps the script, sent with a later update.
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
assert_eq!(command(&t, 1), None);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
// One shell line, unwrapped as the permission card does.
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
// A later update without one keeps it; tasks saved before the field load without it.
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
old.as_object_mut().unwrap().remove("command");
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
}
#[test]
fn tool_images_survive_updates_text_truncation_and_serialization() {
use base64::Engine;
+4 -3
Переглянути файл
@@ -323,7 +323,8 @@ mod tests {
"exclude": [path(&root.join("node_modules"))],
})
);
let a = root.join("packages/a");
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
let a = root.join("packages").join("a");
assert_eq!(
copy(1),
json!({
@@ -336,14 +337,14 @@ mod tests {
"exclude": [path(&a.join("node_modules"))],
})
);
let b = root.join("packages/b");
let b = root.join("packages").join("b");
assert_eq!(
copy(2),
json!({
"extends": path(&b.join("tsconfig.json")),
"compilerOptions": {
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
},
"references": [{"path": s("1.json")}],
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
+7 -4
Переглянути файл
@@ -91,12 +91,14 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
/// redirector loaded before Maven calculates its lifecycle execution plans.
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
pub fn build(
root: &Path,
model: &BuildModel,
bundle: &Path,
generation: &Path,
cancel: &CancellationToken,
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
) -> IdeResult<Outcome> {
std::fs::create_dir_all(generation)?;
let mut plan = plan(root, model, cancel)?;
@@ -124,10 +126,10 @@ pub fn build(
for step in &plan.steps {
let mut reactor = plan.clone();
reactor.steps = vec![step.clone()];
let result = compile::run(root, &reactor, cancel, &|event| {
if let BuildEvent::Output { text, .. } = event {
tracing::debug!("kotlin bridge: {}", text.trim_end());
}
let result = compile::run(root, &reactor, cancel, &|event| match event {
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
_ => {}
})?;
messages.extend(result.messages);
}
@@ -456,6 +458,7 @@ mod tests {
Path::new("unused.jar"),
&directory.path().join("private"),
&CancellationToken::new(),
&|_, _| {},
)
.err()
.unwrap();
+52
Переглянути файл
@@ -505,6 +505,19 @@ pub struct LanguageCodeStyle {
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub spaces: BTreeMap<String, bool>,
/// JavaScript / TypeScript › Imports › Import paths:
/// `shortest` | `relative` | `non-relative` | `project-relative`.
#[serde(skip_serializing_if = "Option::is_none")]
pub import_module_specifier: Option<String>,
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
#[serde(skip_serializing_if = "Option::is_none")]
pub import_module_specifier_ending: Option<String>,
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub auto_import_file_exclude_patterns: Vec<String>,
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub auto_import_specifier_exclude_regexes: Vec<String>,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -562,6 +575,25 @@ pub struct EncodingSettings {
pub native_to_ascii: bool,
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
pub utf8_bom: String,
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
/// relative to the project with `/` separators. The status bar's choice is kept here.
#[serde(deserialize_with = "labels")]
#[specta(type = BTreeMap<String, String>)]
pub mappings: BTreeMap<String, String>,
}
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
return Ok(BTreeMap::new());
};
Ok(entries
.into_iter()
.filter_map(|(path, label)| match label {
serde_json::Value::String(label) => Some((path, label)),
_ => None,
})
.collect())
}
impl Default for EncodingSettings {
@@ -572,10 +604,30 @@ impl Default for EncodingSettings {
properties: "iso-8859-1".into(),
native_to_ascii: false,
utf8_bom: "never".into(),
mappings: BTreeMap::new(),
}
}
}
#[cfg(test)]
mod encoding_mappings_tests {
use super::EncodingSettings;
#[test]
fn encoding_mappings_keep_the_entries_that_are_labels() {
let json = serde_json::json!({
"project": "gbk",
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
});
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
assert_eq!(settings.project, "gbk");
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
assert!(not_a_table.mappings.is_empty());
assert!(EncodingSettings::default().mappings.is_empty());
}
}
#[cfg(test)]
mod auto_import_tests {
use super::{AutoImportSettings, ImportsOnPaste};
+29 -4
Переглянути файл
@@ -13,13 +13,34 @@ use std::sync::Arc;
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
/// started or failed to.
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
/// Run would, answered the same way.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum McpUiRequest {
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
Confirm {
client: String,
tool: String,
subject: String,
project: String,
detail: Option<String>,
},
OpenFile {
path: crate::IpcPath,
line: Option<u32>,
column: Option<u32>,
},
AgentRun {
name: String,
command: String,
cwd: crate::IpcPath,
env: BTreeMap<String, String>,
},
RunConfiguration {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -27,6 +48,10 @@ pub enum McpUiRequest {
pub enum IdeEvent {
/// Project data source settings changed; reload the Database tree.
DbSourcesChanged,
/// A Python run saved a matplotlib figure for the Plots tool window (a PNG file).
PlotAdded {
path: String,
},
McpRequest {
id: u32,
request: McpUiRequest,
+124 -11
Переглянути файл
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
struct Entry {
root: PathBuf,
direnv: Vec<(OsString, Option<OsString>)>,
github_token: Option<OsString>,
changes: Changes,
loading: bool,
}
impl Entry {
fn new(root: PathBuf) -> Self {
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
}
fn rebuild(&mut self) {
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
if let Some(token) = &self.github_token {
combined.push(("GH_TOKEN".into(), Some(token.clone())));
}
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
combined.extend(self.direnv.iter().cloned());
self.changes = Arc::new(combined);
}
fn is_idle_empty(&self) -> bool {
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
}
}
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
static SETTLED: Condvar = Condvar::new();
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
let mut entries = entries();
match entries.iter_mut().find(|e| e.root == root) {
Some(entry) => entry.loading = true,
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
None => {
let mut entry = Entry::new(root.to_path_buf());
entry.loading = true;
entries.push(entry);
}
}
}
/// What children started in `root` (or below it) get on top of the IDE's own environment
/// (`None`: removed). Ends a [`begin_loading`].
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
/// environment (`None`: removed). Ends a [`begin_loading`].
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
let mut entries = entries();
let changes = Arc::new(changes);
match entries.iter_mut().find(|e| e.root == root) {
Some(entry) => {
entry.changes = changes;
match entries.iter_mut().position(|e| e.root == root) {
Some(idx) => {
let entry = &mut entries[idx];
entry.direnv = changes;
entry.loading = false;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
}
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
None if !changes.is_empty() => {
let mut entry = Entry::new(root.to_path_buf());
entry.direnv = changes;
entry.rebuild();
entries.push(entry);
}
None => {}
}
SETTLED.notify_all();
}
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
pub fn settle(root: &Path) {
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
entry.loading = false;
let mut entries = entries();
if let Some(idx) = entries.iter().position(|e| e.root == root) {
entries[idx].loading = false;
if entries[idx].is_idle_empty() {
entries.remove(idx);
}
}
SETTLED.notify_all();
}
/// `root` has no environment of its own any more (closed, or not trusted).
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
pub fn remove(root: &Path) {
let mut entries = entries();
if let Some(idx) = entries.iter().position(|e| e.root == root) {
let entry = &mut entries[idx];
entry.direnv.clear();
entry.loading = false;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
}
SETTLED.notify_all();
}
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
let token = token.filter(|t| !t.is_empty());
let mut entries = entries();
match entries.iter().position(|e| e.root == root) {
Some(idx) => {
if entries[idx].github_token == token {
return false;
}
let entry = &mut entries[idx];
entry.github_token = token;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
true
}
None => {
let Some(token) = token else { return false };
let mut entry = Entry::new(root.to_path_buf());
entry.github_token = Some(token);
entry.rebuild();
entries.push(entry);
true
}
}
}
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
pub fn github_token(dir: &Path) -> Option<OsString> {
find(&entries(), dir).and_then(|e| e.github_token.clone())
}
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
pub fn remove_all(root: &Path) {
entries().retain(|e| e.root != root);
SETTLED.notify_all();
}
@@ -135,4 +226,26 @@ mod tests {
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
remove(root);
}
#[test]
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
let root = Path::new("/openidea-test-env/gh-project");
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
assert!(set_github_token(root, Some("gho_work".into())));
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
assert!(set_github_token(worktrees, Some("gho_work".into())));
remove(root); // no `.envrc` in `root`
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
remove_all(root);
remove_all(worktrees);
assert!(for_dir(root).is_empty());
assert!(for_dir(worktrees).is_empty());
}
}
+34
Переглянути файл
@@ -99,6 +99,20 @@ pub struct AgentSettings {
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
pub fit_window_width: bool,
/// Chat text follows the interface font (Appearance › Use custom font).
pub chat_use_ui_font: bool,
/// Chat text family when it does not follow the interface font.
pub chat_font_family: String,
/// Covers characters the chat font lacks.
pub chat_font_fallback: String,
pub chat_font_size: u32,
/// Code in chat follows the built-in code font.
pub code_use_default_font: bool,
/// Code family when it does not follow the built-in code font.
pub code_font_family: String,
/// Covers characters the code font lacks.
pub code_font_fallback: String,
pub code_font_size: u32,
#[serde(deserialize_with = "or_default")]
#[specta(type = ThinkingDisplay)]
pub thinking: ThinkingDisplay,
@@ -145,6 +159,14 @@ impl Default for AgentSettings {
show_cost: false,
smooth_text: true,
fit_window_width: false,
chat_use_ui_font: true,
chat_font_family: "Inter".into(),
chat_font_fallback: String::new(),
chat_font_size: 13,
code_use_default_font: true,
code_font_family: "JetBrains Mono".into(),
code_font_fallback: String::new(),
code_font_size: 13,
thinking: ThinkingDisplay::Auto,
tool_calls: ToolCallDisplay::Grouped,
expand_tool_output: false,
@@ -1426,6 +1448,15 @@ pub struct PythonSettings {
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
/// by interpreter executable; absolute or `~/`.
pub interpreter_paths: BTreeMap<String, Vec<String>>,
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
/// it, else unittest), `pytest` or `unittest`.
pub test_runner: String,
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
pub profiler: String,
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
/// unless the run sets it); off: matplotlib's own window.
pub show_plots_in_tool_window: bool,
}
impl Default for PythonSettings {
@@ -1438,6 +1469,9 @@ impl Default for PythonSettings {
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
test_runner: "auto".into(),
profiler: "auto".into(),
show_plots_in_tool_window: true,
}
}
}
+12
Переглянути файл
@@ -25,6 +25,17 @@ pub struct VcsSettings {
pub issue_navigation: Vec<IssueLink>,
/// Directory Mappings: repository roots added to or excluded from the detected ones.
pub mappings: VcsMappings,
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
pub github: GithubSettings,
}
/// Settings › Version Control › GitHub (`vcs.github`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GithubSettings {
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
pub account: String,
}
/// Directory Mappings on top of repository detection. Paths are relative to the project
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
shelf: ShelfSettings::default(),
issue_navigation: Vec::new(),
mappings: VcsMappings::default(),
github: GithubSettings::default(),
}
}
}
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-coverage"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo XML)"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
version.workspace = true
edition.workspace = true
license.workspace = true
+174
Переглянути файл
@@ -0,0 +1,174 @@
//! Cobertura XML reports (`coverage xml` of coverage.py, and many other tools):
//!
//! ```xml
//! <coverage>
//! <sources><source>/home/runner/work/app/app</source></sources>
//! <packages><package name="calc"><classes>
//! <class filename="src/calc/__init__.py">
//! <methods/>
//! <lines>
//! <line number="2" hits="1" branch="true" condition-coverage="50% (1/2)"/>
//! ```
//!
//! A relative `filename` belongs to the first `<source>` it exists under, else to the
//! first `<source>` (whose path may be another machine's; the importer relocates it).
//! Lines repeated under `<methods>` are skipped so their hits don't count twice.
use crate::Accumulator;
use quick_xml::events::{BytesStart, Event};
use quick_xml::{Reader, XmlVersion};
use std::path::{Path, PathBuf};
fn attr(e: &BytesStart, name: &str) -> Option<String> {
e.attributes()
.flatten()
.find(|a| a.key.as_ref() == name)
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok())
.map(Into::into)
}
/// `"50% (1/2)"` → `(1, 2)`.
fn conditions(text: &str) -> Option<(u32, u32)> {
let (_, rest) = text.split_once('(')?;
let (covered, total) = rest.trim_end_matches(')').split_once('/')?;
Some((covered.trim().parse().ok()?, total.trim().parse().ok()?))
}
/// `sources` pairs each `<source>` with whether it exists here (asked once: another
/// machine's `/home/…` is slow to look up on macOS).
fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf {
let p = Path::new(filename);
if p.has_root() {
return p.to_path_buf();
}
sources
.iter()
.filter(|(_, here)| *here)
.map(|(s, _)| s.join(p))
.find(|c| c.is_file())
.unwrap_or_else(|| sources.first().map_or_else(|| base.join(p), |(s, _)| s.join(p)))
}
/// Relative sources (and filenames without sources) resolve against `base`.
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
let mut reader = Reader::from_str(xml);
let mut acc = Accumulator::default();
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
let mut source: Option<String> = None;
let mut file: Option<PathBuf> = None;
let mut in_methods = false;
loop {
match reader.read_event()? {
Event::Start(e) if e.name().as_ref() == "methods" => in_methods = true,
Event::Start(e) | Event::Empty(e) => match e.name().as_ref() {
"source" => source = Some(String::new()),
"class" => {
let path = resolve(&attr(&e, "filename").unwrap_or_default(), &sources, base);
acc.file(&path);
file = Some(path);
}
"line" if !in_methods => {
let Some(path) = &file else { continue };
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
let line = number.saturating_sub(1);
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
if attr(&e, "branch").as_deref() == Some("true")
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
{
acc.has_branches = true;
for i in 0..total {
acc.branch(path, line, i.to_string(), i < covered);
}
}
}
_ => {}
},
Event::Text(t) => {
if let Some(s) = &mut source {
s.push_str(t.as_ref());
}
}
Event::GeneralRef(r) => {
if let Some(s) = &mut source {
s.push('&');
s.push_str(r.as_ref());
s.push(';');
}
}
Event::End(e) => match e.name().as_ref() {
"source" => {
let raw = source.take().unwrap_or_default();
let text = quick_xml::escape::unescape(raw.trim()).map(|t| t.into_owned()).unwrap_or(raw);
if !text.is_empty() {
let path = Path::new(&text);
// Joining a drive-less foreign root on Windows would add the checkout's drive.
let dir = if path.has_root() { path.to_path_buf() } else { base.join(path) };
let here = dir.is_dir();
sources.push((dir, here));
}
}
"methods" => in_methods = false,
"class" => file = None,
_ => {}
},
Event::Eof => break,
_ => {}
}
}
Ok(acc)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_lines_branches_and_skips_method_lines() {
let tmp = tempfile::tempdir().unwrap();
let second = tmp.path().join("b&c");
std::fs::create_dir_all(&second).unwrap();
std::fs::write(second.join("m.py"), "").unwrap();
let xml = format!(
r#"<?xml version="1.0" ?>
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
<coverage><sources><source>/elsewhere/a</source><source>{}</source></sources>
<packages><package name="p"><classes>
<class name="m" filename="m.py">
<methods><method name="f"><lines><line number="2" hits="5"/></lines></method></methods>
<lines>
<line number="1" hits="1"/>
<line number="2" hits="5" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
<line number="3" hits="0"/>
</lines>
</class>
<class name="n" filename="n.py"><lines><line number="1" hits="0"/></lines></class>
<class name="abs" filename="/abs/x.py"><lines><line number="7" hits="2"/></lines></class>
</classes></package></packages></coverage>"#,
tmp.path().join("b&amp;c").display()
);
let suite = parse(&xml, tmp.path()).unwrap().finish("Cobertura");
assert!(suite.has_branches);
assert_eq!(suite.files.len(), 3);
let file = |path: &Path| suite.files.iter().find(|f| f.path.as_ref() as &Path == path).unwrap();
// `m.py` exists under the second source; `n.py` falls back to the first.
let m = file(&second.join("m.py"));
assert_eq!(file(Path::new("/elsewhere/a/n.py")).lines[0].hits, 0);
assert_eq!(
m.lines.iter().map(|l| (l.line, l.hits, l.branches_total, l.branches_covered)).collect::<Vec<_>>(),
[(0, 1, 0, 0), (1, 5, 2, 1), (2, 0, 0, 0)]
);
assert!(m.lines[1].partial());
assert_eq!(file(Path::new("/abs/x.py")).lines[0].line, 6);
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
}
#[test]
fn filenames_without_sources_resolve_against_the_base() {
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
let suite = parse(xml, Path::new("/root")).unwrap().finish("Cobertura");
assert_eq!(suite.files[0].path.as_ref() as &Path, Path::new("/root/a/b.py"));
assert!(!suite.has_branches);
assert_eq!(conditions("100% (4/4)"), Some((4, 4)));
assert_eq!(conditions("100%"), None);
}
}
+281
Переглянути файл
@@ -0,0 +1,281 @@
//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of
//! executed lines and arcs. Which lines are statements, excluded or branches only comes from
//! analysing the source, so coverage.py in the project's interpreter combines the data into a
//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML.
use crate::{CoverageSuite, cobertura};
use ide_core::cli_process::{CliTool, Decoding};
use ide_core::{IdeError, IdeResult};
use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
const COVERAGE_PY: CliTool = CliTool::new("coverage.py", Decoding::ToolOutput);
/// Analysing a large project's sources takes a while; a `[run] plugins` that hangs must not
/// block the import for good.
const TIMEOUT: Duration = Duration::from_secs(600);
/// Files of the combined data (`relative_files` keeps them relative to the directory it ran in).
const MEASURED: &str = "import sys, json, coverage\n\
d = coverage.CoverageData(sys.argv[1]); d.read(); print(json.dumps(sorted(d.measured_files())))";
/// The files coverage.py reads its configuration from, in the directory it runs in.
const CONFIG_FILES: [&str; 4] = [".coveragerc", "setup.cfg", "tox.ini", "pyproject.toml"];
/// Whether `path` is an SQLite database (coverage.py 5+ data).
pub fn is_data_file(path: &Path) -> bool {
let mut head = [0u8; 16];
std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"
}
/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's.
fn inputs(path: &Path) -> Vec<PathBuf> {
let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage."));
let mut files: Vec<PathBuf> = match (parallel, path.parent()) {
(true, Some(dir)) => std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| {
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p)
})
.collect(),
_ => Vec::new(),
};
if files.is_empty() {
files.push(path.to_path_buf());
}
files.sort();
files
}
/// Where coverage.py ran: the nearest directory of `path` inside `root` with a coverage.py
/// configuration file (a monorepo's `backend/pyproject.toml`), else `root`.
fn run_dir(path: &Path, root: &Path) -> PathBuf {
path.ancestors()
.skip(1)
.take_while(|d| d.starts_with(root))
.find(|d| CONFIG_FILES.iter().any(|f| d.join(f).is_file()))
.unwrap_or(root)
.to_path_buf()
}
/// Runs `python -W ignore <args>` in `dir` and returns its stdout. Python warnings are
/// ignored so `PYTHONWARNINGS=error` can't turn coverage.py's warnings into failures.
fn python(python: &Path, dir: &Path, args: &[&OsStr]) -> IdeResult<String> {
let mut cmd = Command::new(python);
cmd.current_dir(dir).args(["-W", "ignore"]).args(args);
let out = COVERAGE_PY.run(cmd, TIMEOUT, None)?;
if out.success {
return Ok(out.stdout);
}
let text = if out.stderr.trim().is_empty() { out.stdout } else { out.stderr };
let text = text.trim();
if text.contains("No module named coverage") {
return Err(IdeError::unavailable(format!(
"Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.",
python.display()
)));
}
if text.contains("no such option") {
return Err(IdeError::unavailable(format!(
"Reading a .coverage data file needs coverage.py 6.3 or later in the project's interpreter ({}): {text}",
python.display()
)));
}
Err(IdeError::invalid(format!("coverage.py could not read the data: {text}")))
}
/// Reads the data file at `path` with `python`'s coverage.py, run where the project's coverage.py
/// configuration is; `out` holds the scratch files. Blocking.
pub(crate) fn import(path: &Path, root: &Path, python_path: &Path, out: &Path) -> IdeResult<CoverageSuite> {
let dir = run_dir(path, root);
let data = out.join(".coverage");
let xml = out.join("coverage.xml");
let coverage = |args: &[&OsStr]| {
let mut all: Vec<&OsStr> = vec!["-m".as_ref(), "coverage".as_ref()];
all.extend(args);
python(python_path, &dir, &all)
};
let inputs = inputs(path);
let mut args: Vec<&OsStr> = vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()];
args.extend(inputs.iter().map(|p| p.as_os_str()));
coverage(&args)?;
// `-i`: report what has source here instead of failing on the first file that has none.
// `--fail-under=0`: a `[report] fail_under` the data misses must not fail the import.
coverage(&[
"xml".as_ref(),
"-i".as_ref(),
"--fail-under=0".as_ref(),
"--data-file".as_ref(),
data.as_ref(),
"-o".as_ref(),
xml.as_ref(),
])?;
let text = std::fs::read_to_string(&xml)?;
let mut acc = cobertura::parse(&text, &dir).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
// The files the report left out (no source here): listed without lines.
let measured = python(python_path, &dir, &["-c".as_ref(), MEASURED.as_ref(), data.as_ref()])?;
let measured: Vec<PathBuf> = serde_json::from_str(measured.trim())
.map_err(|e| IdeError::invalid(format!("coverage.py listed the measured files unreadably: {e}")))?;
for file in measured {
acc.file(&dir.join(file));
}
Ok(acc.finish("coverage.py"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_the_files_of_a_parallel_run() {
let tmp = tempfile::tempdir().unwrap();
let db = |name: &str| {
let p = tmp.path().join(name);
std::fs::write(&p, b"SQLite format 3\0rest").unwrap();
p
};
let a = db(".coverage.host.1.x");
let b = db(".coverage.host.2.y");
let single = db(".coverage");
std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap();
std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap();
assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc")));
assert_eq!(inputs(&a), [a.clone(), b]);
assert_eq!(inputs(&single), [single]);
}
/// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`.
/// Needs coverage.py in `python3`; skipped without it.
#[test]
fn combines_parallel_data_with_the_projects_paths() {
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
if !has_coverage.is_ok_and(|o| o.status.success()) {
eprintln!("skipped: no coverage.py in python3");
return;
}
let tmp = tempfile::tempdir().unwrap();
// coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`).
let base = tmp.path().canonicalize().unwrap();
let ci = base.join("ci/app");
let root = base.join("project");
let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n";
for dir in [&ci, &root] {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join("calc.py"), calc).unwrap();
}
std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap();
std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap();
std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap();
for script in ["neg.py", "pos.py"] {
let ok = Command::new("python3")
.current_dir(&ci)
.args(["-m", "coverage", "run", "--branch", "--parallel-mode", script])
.status()
.unwrap();
assert!(ok.success());
}
let data = root.join("data");
std::fs::create_dir_all(&data).unwrap();
for e in std::fs::read_dir(&ci).unwrap().flatten() {
if e.file_name().to_string_lossy().starts_with(".coverage.") {
std::fs::rename(e.path(), data.join(e.file_name())).unwrap();
}
}
std::fs::remove_dir_all(&ci).unwrap();
std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap();
let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path();
let out = base.join("out");
std::fs::create_dir_all(&out).unwrap();
let suite = import(&first, &root, Path::new("python3"), &out).unwrap();
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap();
// Both runs together take both branches of line 2.
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2));
// The scripts and `gone.py` have no source in the project: listed without lines.
let empty: Vec<&str> = suite
.files
.iter()
.filter(|f| f.lines.is_empty())
.filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str())
.collect();
assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]);
// They keep the recorded path, so the import notification counts them as not in the project.
assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci)));
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept");
}
#[test]
fn runs_where_the_coverage_configuration_is() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("backend/reports")).unwrap();
std::fs::create_dir_all(root.join("data")).unwrap();
std::fs::write(root.join("backend/pyproject.toml"), "").unwrap();
assert_eq!(run_dir(&root.join("backend/reports/.coverage"), root), root.join("backend"));
assert_eq!(run_dir(&root.join("data/.coverage"), root), root);
// A data file outside the project runs in the project.
assert_eq!(run_dir(Path::new("/elsewhere/.coverage"), root), root);
}
/// A stand-in interpreter that prints `stderr` and exits with `code`.
#[cfg(unix)]
fn fake_python(dir: &Path, stderr: &str, code: i32) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let p = dir.join("python");
std::fs::write(&p, format!("#!/bin/sh\necho '{stderr}' >&2\nexit {code}\n")).unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
p
}
#[cfg(unix)]
#[test]
fn reports_why_coverage_py_failed() {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join(".coverage");
let err = |stderr: &str| {
let python = fake_python(tmp.path(), stderr, 1);
import(&data, tmp.path(), &python, tmp.path()).unwrap_err().to_string()
};
assert!(err("No module named coverage").contains("needs coverage.py in the project's interpreter"));
assert!(err("no such option: --data-file").contains("needs coverage.py 6.3 or later"));
assert!(err("No usable data files").contains("coverage.py could not read the data: No usable data files"));
}
/// A monorepo member's data recorded with `relative_files`, below its `fail_under`, with
/// coverage.py's warnings turned off. Needs coverage.py in `python3`; skipped without it.
#[test]
fn reads_a_members_relative_data_below_fail_under() {
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
if !has_coverage.is_ok_and(|o| o.status.success()) {
eprintln!("skipped: no coverage.py in python3");
return;
}
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let member = root.join("backend");
std::fs::create_dir_all(member.join("app")).unwrap();
std::fs::write(
member.join("pyproject.toml"),
"[tool.coverage.run]\nrelative_files = true\nbranch = true\ndisable_warnings = [\"couldnt-parse\"]\n\
[tool.coverage.report]\nfail_under = 90\n",
)
.unwrap();
std::fs::write(member.join("app/x.py"), "def f(n):\n if n:\n return 1\n return 2\n").unwrap();
std::fs::write(member.join("t.py"), "from app import x\nx.f(1)\n").unwrap();
let ok = Command::new("python3").current_dir(&member).args(["-m", "coverage", "run", "t.py"]).status().unwrap();
assert!(ok.success());
std::fs::remove_file(member.join("t.py")).unwrap();
let out = root.join("out");
std::fs::create_dir_all(&out).unwrap();
let suite = import(&member.join(".coverage"), &root, Path::new("python3"), &out).unwrap();
let x = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("app/x.py")).unwrap();
assert_eq!((x.lines_total, x.lines_covered, x.branches_total, x.branches_covered), (4, 3, 2, 1));
// `t.py` has no source any more and its warning is off: still listed, without lines.
let t = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("t.py")).unwrap();
assert!(t.lines.is_empty());
}
}
+127 -8
Переглянути файл
@@ -1,9 +1,10 @@
//! "Import a report collected in CI from disk": the format is sniffed from the
//! content (lcov, Go cover profile, JaCoCo XML, SimpleCov resultset) and paths recorded on another
//! content (lcov, Go cover profile, JaCoCo or Cobertura XML, SimpleCov resultset) and paths recorded on another
//! machine are mapped into the project by their longest existing suffix.
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov, simplecov};
use crate::{Accumulator, CoverageSuite, cobertura, goprofile, jacoco, lcov, simplecov};
use ide_core::{IdeError, IdeResult};
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -11,13 +12,19 @@ pub(crate) enum Format {
Lcov,
GoProfile,
Jacoco,
Cobertura,
SimpleCov,
}
pub(crate) fn detect(text: &str) -> Option<Format> {
let head = text.trim_start_matches('\u{feff}').trim_start();
if head.starts_with('<') {
return head.contains("<report").then_some(Format::Jacoco);
// The root element, after any prolog or DOCTYPE naming it.
return match (head.find("<report"), head.find("<coverage")) {
(Some(r), c) if c.is_none_or(|c| r < c) => Some(Format::Jacoco),
(_, Some(_)) => Some(Format::Cobertura),
_ => None,
};
}
if head.starts_with('{') {
return head.contains("\"coverage\"").then_some(Format::SimpleCov);
@@ -39,6 +46,9 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
let (module, module_dir) = go_module_for(root, &text);
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
}
Some(Format::Cobertura) => cobertura::parse(&text, root)
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?
.finish("Cobertura"),
Some(Format::Jacoco) => {
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
let module = jacoco::module_dir(path);
@@ -53,18 +63,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
acc.finish("JaCoCo")
}
None if text.starts_with("!coverage.py: This is a private format") => {
return Err(IdeError::invalid(format!(
"{} is coverage.py 4 data, which current coverage.py can't read. Import the output of `coverage xml` instead.",
path.display()
)));
}
None => {
return Err(IdeError::invalid(format!(
"{} is not an lcov tracefile, Go cover profile, JaCoCo XML report or SimpleCov resultset",
"{} is not an lcov tracefile, Go cover profile, JaCoCo or Cobertura XML report or SimpleCov resultset",
path.display()
)));
}
};
let mut dirs = HashMap::new();
for f in &mut suite.files {
let p: &Path = f.path.as_ref();
if !p.exists()
&& let Some(found) = relocate(p, root)
{
let present = p.parent().is_none_or(|d| dir_exists(d, &mut dirs)) && p.exists();
if !present && let Some(found) = relocate(p, root) {
f.path = found.into();
}
}
@@ -72,6 +88,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
Ok(suite)
}
/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`,
/// run in `root`; `out` is an empty scratch directory. Blocking.
pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
crate::coveragepy::import(path, root, python, out)
}
/// Whether `dir` exists, without asking again below a directory known to be missing: every
/// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports
/// (`/home/runner/work/…`) name thousands of files there.
fn dir_exists(dir: &Path, known: &mut HashMap<PathBuf, bool>) -> bool {
if let Some(&e) = known.get(dir) {
return e;
}
let e = dir.parent().is_none_or(|p| dir_exists(p, known)) && dir.is_dir();
known.insert(dir.to_path_buf(), e);
e
}
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
/// `path` that exists under `root`.
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
@@ -129,12 +163,30 @@ mod tests {
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
Some(Format::Jacoco)
);
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), Some(Format::Cobertura));
assert_eq!(
detect("<?xml version=\"1.0\"?><!DOCTYPE coverage SYSTEM \"x.dtd\"><coverage/>"),
Some(Format::Cobertura)
);
assert_eq!(detect("<?xml version=\"1.0\"?><html/>"), None);
assert_eq!(detect("{\"RSpec\": {\"coverage\": {}}}"), Some(Format::SimpleCov));
assert_eq!(detect("{\"name\": \"package.json\"}"), None);
assert_eq!(detect("hello"), None);
}
#[test]
fn missing_directories_are_looked_up_once() {
let tmp = tempfile::tempdir().unwrap();
let mut known = HashMap::new();
assert!(dir_exists(tmp.path(), &mut known));
let gone = tmp.path().join("gone");
assert!(!dir_exists(&gone.join("a/b"), &mut known));
std::fs::create_dir_all(gone.join("a/c")).unwrap();
// Known to be missing, so its subdirectories are not looked up.
assert!(!dir_exists(&gone.join("a/c"), &mut known));
assert_eq!(known.get(&gone), Some(&false));
}
#[test]
fn imports_ci_simplecov_with_foreign_paths() {
let tmp = tempfile::tempdir().unwrap();
@@ -168,8 +220,75 @@ mod tests {
assert!(import(&tmp.path().join("missing"), &root).is_err());
std::fs::write(&report, "nothing").unwrap();
assert!(import(&report, &root).is_err());
std::fs::write(&report, "!coverage.py: This is a private format, don't read it directly!{\"lines\":{}}")
.unwrap();
assert!(import(&report, &root).unwrap_err().to_string().contains("coverage.py 4 data"));
}
/// `coverage xml` (coverage.py 7.17, `--branch`) of a project checked out on a CI runner.
#[test]
fn imports_coverage_py_xml_with_foreign_sources() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("app");
std::fs::create_dir_all(root.join("src/calc")).unwrap();
std::fs::write(root.join("src/calc/__init__.py"), "").unwrap();
let report = tmp.path().join("coverage.xml");
std::fs::write(&report, COVERAGE_PY_XML).unwrap();
let suite = import(&report, &root).unwrap();
assert_eq!(suite.runner, "Cobertura");
assert!(suite.has_branches);
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("src/calc/__init__.py")).unwrap();
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (8, 5, 4, 2));
assert_eq!(calc.lines.iter().filter(|l| l.partial()).map(|l| l.line).collect::<Vec<_>>(), [1, 3]);
// The test file is not in this checkout: it keeps the runner's path.
assert!(
suite.files.iter().any(|f| f.path.as_ref() as &Path == Path::new("/home/runner/work/app/app/test_calc.py"))
);
}
const COVERAGE_PY_XML: &str = r#"<?xml version="1.0" ?>
<coverage version="7.17.5" timestamp="1795754882920" lines-valid="13" lines-covered="10" line-rate="0.7692" branches-valid="4" branches-covered="2" branch-rate="0.5" complexity="0">
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.17.5 -->
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
<sources>
<source>/home/runner/work/app/app</source>
</sources>
<packages>
<package name="." line-rate="1" branch-rate="1" complexity="0">
<classes>
<class name="test_calc.py" filename="test_calc.py" complexity="0" line-rate="1" branch-rate="1">
<methods/>
<lines>
<line number="1" hits="1"/>
<line number="2" hits="1"/>
<line number="3" hits="1"/>
<line number="6" hits="1"/>
<line number="7" hits="1"/>
</lines>
</class>
</classes>
</package>
<package name="src.calc" line-rate="0.625" branch-rate="0.5" complexity="0">
<classes>
<class name="__init__.py" filename="src/calc/__init__.py" complexity="0" line-rate="0.625" branch-rate="0.5">
<methods/>
<lines>
<line number="1" hits="1"/>
<line number="2" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
<line number="3" hits="0"/>
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="5"/>
<line number="5" hits="0"/>
<line number="6" hits="1"/>
<line number="13" hits="1"/>
<line number="14" hits="0"/>
</lines>
</class>
</classes>
</package>
</packages>
</coverage>
"#;
#[test]
fn imports_go_profiles_of_nested_modules() {
let tmp = tempfile::tempdir().unwrap();
+4 -1
Переглянути файл
@@ -16,6 +16,8 @@
//!
//! Lines in the model are 0-based, like every IPC coordinate.
mod cobertura;
mod coveragepy;
mod goprofile;
mod import;
mod jacoco;
@@ -23,7 +25,8 @@ mod lcov;
mod plan;
mod simplecov;
pub use import::import;
pub use coveragepy::is_data_file;
pub use import::{import, import_data};
pub use plan::prepare;
use ide_core::{IdeError, IdeResult, IpcPath};
+2 -1
Переглянути файл
@@ -326,7 +326,8 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
argv.extend(py.target.iter().cloned());
let report = CoverageReportSpec::Exported {
runner: s("coverage.py"),
argv: with(&["-m", "coverage", "lcov", "-o", &path(&lcov)]),
// `--fail-under=0`: a `[report] fail_under` the run misses must not lose its report.
argv: with(&["-m", "coverage", "lcov", "--fail-under=0", "-o", &path(&lcov)]),
cwd: dir.to_path_buf().into(),
env: config.env.clone(),
lcov: lcov.into(),
+15
Переглянути файл
@@ -859,6 +859,21 @@ async fn connect_with_retries(
mod tests {
use super::*;
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
/// language (a template one) declares debugpy before Python.
#[test]
fn debugpy_comes_from_the_python_language() {
let dir = tempfile::tempdir().unwrap();
let python = include_str!("../../../languages/python.toml").replace(
"args = [\"-m\", \"debugpy.adapter\"]",
"args = [\"-X\", \"frozen_modules=off\", \"-m\", \"debugpy.adapter\"]",
);
assert!(python.contains("frozen_modules"));
std::fs::write(dir.path().join("python.toml"), python).unwrap();
let languages = LanguageRegistry::load(Some(dir.path())).unwrap();
assert_eq!(find_config(&languages, "debugpy").unwrap().args[0], "-X");
}
#[test]
fn adapters_run_on_the_tool_search_path() {
let search = ide_core::tool_path::search_path();
+114
Переглянути файл
@@ -0,0 +1,114 @@
//! Python Debug Server (`attach` with `listen`): the program connects with its own debugpy,
//! which may differ from the IDE's adapter. Nothing in the protocol compares them.
use crate::session::Session;
use ide_core::IdeError;
use ide_core::event::DebugEvent;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
adapter == "debugpy" && request == "attach" && arguments.get("listen").is_some()
}
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
/// which would wait for the program forever: find out before starting it. Listening again right
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
const RELEASE: Duration = Duration::from_secs(5);
let listen = &arguments["listen"];
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
let deadline = tokio::time::Instant::now() + RELEASE;
loop {
match std::net::TcpListener::bind((host, port)) {
Ok(_) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))),
}
}
}
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
/// Evaluated in the stopped frame as a hover: without a frame, debugpy before 1.8 runs the
/// expression as a statement and prints its value into the program's output.
pub(crate) async fn check_version(s: Arc<Session>, thread: i64) {
const WAIT: Duration = Duration::from_secs(5);
let request = |command: &'static str, arguments: Value| s.conn.request_timeout(command, arguments, WAIT);
let Ok(info) = request("debugpySystemInfo", json!({})).await else { return };
let Some(ide) = info.pointer("/debugpy/version").and_then(Value::as_str) else { return };
let Ok(trace) = request("stackTrace", json!({ "threadId": thread, "levels": 1 })).await else { return };
let Some(frame) = trace.pointer("/stackFrames/0/id").and_then(Value::as_i64) else { return };
let expression = json!({ "expression": "__import__('debugpy').__version__", "frameId": frame, "context": "hover" });
let Ok(reply) = request("evaluate", expression).await else { return };
let Some(program) = reply.get("result").and_then(Value::as_str) else { return };
if let Some(warning) = version_warning(ide, program) {
s.emit(DebugEvent::Output { category: "console".into(), output: warning });
}
}
fn version_warning(ide: &str, program: &str) -> Option<String> {
let program = program.trim_matches(|c| c == '\'' || c == '"');
(program != ide).then(|| {
format!(
"The program uses debugpy {program}, the IDE's debugger debugpy {ide}. If breakpoints or stepping \
misbehave, install the same version where the program runs: pip install debugpy=={ide}\n"
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn warns_only_when_versions_differ() {
assert_eq!(version_warning("1.8.22", "'1.8.22'"), None);
assert_eq!(version_warning("1.8.22", "1.8.22"), None);
let w = version_warning("1.8.22", "'1.8.0'").unwrap();
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
}
#[tokio::test(start_paused = true)]
async fn a_taken_port_is_reported_before_the_adapter_starts() {
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = taken.local_addr().unwrap().port();
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
let e = require_free_port(&listen).await.unwrap_err();
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
drop(taken);
assert!(require_free_port(&listen).await.is_ok());
}
#[tokio::test]
async fn an_address_the_machine_lacks_is_reported_at_once() {
// 192.0.2.0/24 is reserved for documentation, never a local address.
let started = std::time::Instant::now();
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
assert!(started.elapsed() < Duration::from_secs(1));
}
#[tokio::test]
async fn waits_for_the_previous_adapter_to_release_the_port() {
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = previous.local_addr().unwrap().port();
let released = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(300)).await;
drop(previous);
});
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
released.await.unwrap();
}
#[test]
fn only_debugpy_listen_attaches_check() {
assert!(listens("debugpy", "attach", &json!({"listen": {"port": 5678}})));
assert!(!listens("debugpy", "attach", &json!({"connect": {"port": 5678}})));
assert!(!listens("debugpy", "launch", &json!({"listen": {}})));
}
}
+7
Переглянути файл
@@ -12,6 +12,7 @@ pub mod adapter;
pub mod attach;
mod cargo;
pub mod connection;
mod debugpy;
mod exception_classes;
pub mod jdwp;
mod js_cdp;
@@ -901,6 +902,9 @@ impl DebugManager {
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
) -> IdeResult<DebugSessionId> {
let mut arguments = launch_arguments(&config)?;
if debugpy::listens(&config.adapter, &config.request, &arguments) {
debugpy::require_free_port(&arguments).await?;
}
// An IDE-side marker (never sent to the adapter): the session is a Flutter
// one regardless of what the working directory holds.
let force_flutter =
@@ -1149,6 +1153,9 @@ impl DebugManager {
});
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
if debugpy::listens(&session.adapter, &session.request, &arguments) {
session.debugpy_version_unchecked.store(true, Ordering::Release);
}
let configured = tokio::select! {
biased;
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
+8
Переглянути файл
@@ -75,6 +75,8 @@ pub(crate) struct Session {
pub jdwp_port: std::sync::OnceLock<u16>,
/// The attach goes through the listen-mode relay of [`crate::jdwp::listen_for_jvm`].
pub listen_relay: AtomicBool,
/// A Python Debug Server session whose program's debugpy version is checked on its first stop.
pub(crate) debugpy_version_unchecked: AtomicBool,
pub suspended: Suspension,
/// Pids signalled for the current stop: the reported pid and everything it started (an
/// adapter may report the launcher shell, whose child is the program).
@@ -316,6 +318,7 @@ impl Session {
jvm_pid: AtomicI64::new(0),
jdwp_port: std::sync::OnceLock::new(),
listen_relay: AtomicBool::new(false),
debugpy_version_unchecked: AtomicBool::new(false),
suspended: Suspension::default(),
stop_pids: parking_lot::Mutex::new(Vec::new()),
#[cfg(windows)]
@@ -854,6 +857,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
all_threads_stopped: all,
});
});
if let Some(thread) = int("threadId")
&& s.debugpy_version_unchecked.swap(false, Ordering::AcqRel)
{
tokio::spawn(crate::debugpy::check_version(s.clone(), thread));
}
}
"continued" => {
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
+4 -1
Переглянути файл
@@ -127,7 +127,10 @@ mod tests {
fn schema(name: &str, tables: &[&str]) -> CatalogSchema {
CatalogSchema {
name: name.into(),
tables: tables.iter().map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table }).collect(),
tables: tables
.iter()
.map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table, comment: None })
.collect(),
}
}
+12 -7
Переглянути файл
@@ -655,7 +655,7 @@ impl DbManager {
}
}
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default, comment) by table.
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
for row in rows {
@@ -664,12 +664,15 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
let data_type = it.next().flatten().unwrap_or_default();
let nullable = it.next().flatten().as_deref() != Some("0");
let has_default = it.next().flatten().is_some();
// Bridges built before the comment column send five fields.
let comment = it.next().flatten().filter(|c| !c.trim().is_empty());
by_table.entry(table).or_default().push(crate::CompletionColumn {
name,
data_type,
nullable,
primary_key: false,
has_default,
comment,
});
}
by_table
@@ -684,16 +687,18 @@ mod tests {
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
};
let by_table = schema_columns(vec![
row("orders", "id", "0", None),
row("orders", "note", "1", Some("'none'")),
row("items", "sku", "1", None),
vec![None, Some("orphan".into())],
]);
let mut commented = row("orders", "note", "1", Some("'none'"));
commented.push(Some("free text".into()));
let mut blank = row("items", "sku", "1", None);
blank.push(Some(" ".into()));
let by_table =
schema_columns(vec![row("orders", "id", "0", None), commented, blank, vec![None, Some("orphan".into())]]);
let orders = &by_table["orders"];
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
assert_eq!((orders[0].comment.as_deref(), orders[1].comment.as_deref()), (None, Some("free text")));
assert_eq!(by_table["items"][0].comment, None);
assert_eq!(by_table["items"].len(), 1);
assert_eq!(by_table.len(), 2);
}
+47 -7
Переглянути файл
@@ -31,7 +31,7 @@ pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
@@ -146,6 +146,10 @@ pub struct SchemaObject {
pub struct TableInfo {
pub name: String,
pub kind: DbTableKind,
/// The table's or view's comment; `None` when it has none, or the engine keeps no comments.
#[serde(default)]
#[specta(optional)]
pub comment: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -208,6 +212,10 @@ pub struct CompletionColumn {
pub primary_key: bool,
/// Has a default (or is generated): optional in INSERT.
pub has_default: bool,
/// The column's comment; `None` when it has none, or the engine keeps no comments.
#[serde(default)]
#[specta(optional)]
pub comment: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -568,6 +576,18 @@ impl DbManager {
None => {}
}
source::save(&self.root, &project)?;
if let Ok(mut folders) = source::load_folders(&self.root) {
let known: std::collections::HashSet<&str> = sources.iter().map(|source| source.id.as_str()).collect();
let mut changed = false;
for folder in &mut folders {
let before = folder.sources.len();
folder.sources.retain(|id| known.contains(id.as_str()));
changed |= folder.sources.len() != before;
}
if changed {
source::save_folders(&self.root, &folders)?;
}
}
old
};
for o in old {
@@ -1103,7 +1123,11 @@ impl DbManager {
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
Some(TableInfo {
name,
kind: DbTableKind::from_catalog(it.next().flatten().as_deref()),
comment: it.next().flatten().filter(|comment| !comment.is_empty()),
})
})
.collect())
}
@@ -1410,10 +1434,13 @@ impl DbManager {
}
DbDriver::Postgres => {
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
let (oid, kind) = match rel.as_deref() {
Some([Some(oid), Some(kind)]) => {
(oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?, kind.clone())
}
let (oid, kind, owner, comment) = match rel.as_deref() {
Some([Some(oid), Some(kind), owner, comment]) => (
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
kind.clone(),
owner.clone(),
comment.clone(),
),
_ => return Err(missing()),
};
if kind == "v" || kind == "m" {
@@ -1434,6 +1461,7 @@ impl DbManager {
data_type: it.next().flatten().unwrap_or_default(),
not_null: flag(&it.next().flatten()),
default: it.next().flatten(),
comment: it.next().flatten(),
})
})
.collect::<Vec<_>>();
@@ -1447,7 +1475,18 @@ impl DbManager {
})
.collect::<Vec<_>>();
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes))
let grants = pool
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
})
.collect();
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
let extras = sql::DdlExtras { comment, owner, grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
}
}
}
@@ -1495,6 +1534,7 @@ impl DbManager {
nullable: flag(&Some(next())),
primary_key: flag(&Some(next())),
has_default: flag(&Some(next())),
comment: Some(next()).filter(|c| !c.trim().is_empty()),
};
if name.is_empty() || column.name.is_empty() {
continue;
+11 -2
Переглянути файл
@@ -113,7 +113,11 @@ pub(crate) async fn tables(pool: &SnowflakePool, schema: &str) -> IdeResult<Vec<
Ok(shown
.records()
.filter_map(|r| {
Some(TableInfo { name: r.get("name")?.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) })
Some(TableInfo {
name: r.get("name")?.to_owned(),
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
})
})
.collect())
}
@@ -238,7 +242,11 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
let (Some(&index), Some(name)) = (at.get(r.get("schema_name").unwrap_or_default()), r.get("name")) else {
continue;
};
out[index].tables.push(TableInfo { name: name.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) });
out[index].tables.push(TableInfo {
name: name.to_owned(),
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
});
}
for schema in &mut out {
schema.tables.sort_by(|a, b| a.name.cmp(&b.name));
@@ -447,6 +455,7 @@ pub(crate) async fn completion(pool: &SnowflakePool) -> IdeResult<Vec<Completion
primary_key: false,
has_default: r.get("default").is_some_and(|d| !d.is_empty())
|| r.get("autoincrement").is_some_and(|a| !a.is_empty()),
comment: r.get("comment").filter(|c| !c.trim().is_empty()).map(str::to_owned),
});
}
Ok(tables)
+138 -2
Переглянути файл
@@ -1,15 +1,17 @@
//! Data sources: per-project connection settings in `.openidea/data-sources.toml`, and
//! global ones (IDEA's Make Global: listed in every project) in `data-sources.toml` of the
//! app data directory. Passwords never go there: saved ones live in [`crate::secrets`],
//! app data directory. Project folder grouping is in `.openidea/data-source-folders.toml`.
//! Passwords never go there: saved ones live in [`crate::secrets`],
//! the others only in memory for the session.
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashSet};
use std::path::Path;
pub(crate) const FILE: &str = "data-sources.toml";
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -697,6 +699,108 @@ fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
Ok(())
}
/// A user folder grouping data sources in one project's Database tree.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbSourceFolder {
pub id: String,
pub name: String,
/// Reserved for nested folders; the first UI version only creates root folders.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
pub order: i32,
pub sources: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct SourceFoldersFile {
#[serde(default = "folders_version")]
version: u32,
#[serde(default, rename = "folder")]
folders: Vec<DbSourceFolder>,
}
fn folders_version() -> u32 {
1
}
/// The project's data source folders and their members.
pub fn load_folders(root: &Path) -> IdeResult<Vec<DbSourceFolder>> {
let path = project_dir::path(root, FOLDERS_FILE);
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e.into()),
};
let file: SourceFoldersFile =
toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
if file.version > 1 {
return Err(IdeError::invalid(format!(
"{}: folder format version {} is newer than this OpenIDEA",
path.display(),
file.version
)));
}
Ok(file.folders)
}
/// Replaces the project's data source folders after validating ids, parents and memberships.
pub fn save_folders(root: &Path, folders: &[DbSourceFolder]) -> IdeResult<()> {
validate_folders(folders)?;
let path = project_dir::path(root, FOLDERS_FILE);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let file = SourceFoldersFile { version: folders_version(), folders: folders.to_vec() };
let text = toml::to_string_pretty(&file).map_err(|e| IdeError::internal(e.to_string()))?;
let tmp = path.with_file_name(format!(".{FOLDERS_FILE}.{}.tmp", uuid::Uuid::new_v4()));
std::fs::write(&tmp, text)?;
if let Err(e) = std::fs::rename(&tmp, &path) {
let _ = std::fs::remove_file(&tmp);
return Err(e.into());
}
Ok(())
}
fn validate_folders(folders: &[DbSourceFolder]) -> IdeResult<()> {
let mut ids = HashSet::new();
let mut members = HashSet::new();
for folder in folders {
if folder.id.trim().is_empty() || folder.name.trim().is_empty() {
return Err(IdeError::invalid("every data source folder needs an id and a name"));
}
if !ids.insert(folder.id.as_str()) {
return Err(IdeError::invalid(format!("duplicate data source folder id '{}'", folder.id)));
}
for source in &folder.sources {
if source.is_empty() {
return Err(IdeError::invalid(format!("folder '{}' has an empty data source id", folder.name)));
}
if !members.insert(source.as_str()) {
return Err(IdeError::invalid(format!("data source '{source}' belongs to more than one folder")));
}
}
}
for folder in folders {
let mut seen = HashSet::new();
let mut parent = folder.parent.as_deref();
while let Some(id) = parent {
if id == folder.id || !seen.insert(id) {
return Err(IdeError::invalid(format!("data source folder '{}' has a parent cycle", folder.name)));
}
parent =
folders.iter().find(|candidate| candidate.id == id).and_then(|candidate| candidate.parent.as_deref());
if parent.is_none() && !folders.iter().any(|candidate| candidate.id == id) {
return Err(IdeError::invalid(format!(
"data source folder '{}' has an unknown parent '{id}'",
folder.name
)));
}
}
}
Ok(())
}
/// Credential store access. Blocking (may show an OS prompt): call off the async runtime.
/// Keys are data source ids; [`secrets::ssh_key`] names the SSH password / passphrase.
#[cfg(test)]
@@ -724,6 +828,38 @@ mod tests {
assert!(save(tmp.path(), &[DataSource::default()]).is_err());
}
#[test]
fn source_folders_round_trip_and_reject_invalid_memberships() {
let tmp = tempfile::tempdir().unwrap();
let folders = vec![
DbSourceFolder {
id: "prod".into(),
name: "Production".into(),
parent: None,
order: 0,
sources: vec!["pg".into(), "mysql".into()],
},
DbSourceFolder { id: "empty".into(), name: "Empty".into(), parent: None, order: 1, sources: vec![] },
];
save_folders(tmp.path(), &folders).unwrap();
assert_eq!(load_folders(tmp.path()).unwrap(), folders);
let duplicate = vec![
DbSourceFolder { sources: vec!["pg".into()], ..folders[0].clone() },
DbSourceFolder { id: "other".into(), sources: vec!["pg".into()], ..folders[1].clone() },
];
assert!(save_folders(tmp.path(), &duplicate).is_err());
let cycle = vec![
DbSourceFolder { parent: Some("b".into()), ..folders[0].clone() },
DbSourceFolder { id: "b".into(), parent: Some("prod".into()), ..folders[1].clone() },
];
assert!(save_folders(tmp.path(), &cycle).is_err());
let missing = vec![DbSourceFolder { parent: Some("missing".into()), ..folders[0].clone() }];
assert!(save_folders(tmp.path(), &missing).is_err());
}
#[test]
fn reads_configs_written_before_the_new_settings() {
let tmp = tempfile::tempdir().unwrap();
+158 -29
Переглянути файл
@@ -95,46 +95,52 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
}
}
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
/// Rows: `name, kind, comment` where kind is `table`, `view` or `materialized view`.
pub fn tables(driver: DbDriver, schema: &str) -> String {
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => format!(
"SELECT name, CASE engine WHEN 'View' THEN 'view' WHEN 'MaterializedView' THEN 'materialized view' \
WHEN 'WindowView' THEN 'view' ELSE 'table' END FROM system.tables \
WHEN 'WindowView' THEN 'view' ELSE 'table' END, comment FROM system.tables \
WHERE database = {} AND is_temporary = 0 ORDER BY name",
quote_literal(driver, schema)
),
DbDriver::Sqlite => format!(
"SELECT name, type FROM {}.sqlite_master WHERE type IN ('table', 'view') \
"SELECT name, type, NULL FROM {}.sqlite_master WHERE type IN ('table', 'view') \
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
quote_ident(driver, schema)
),
DbDriver::Snowflake => format!(
"SELECT table_name, CASE table_type WHEN 'VIEW' THEN 'view' WHEN 'MATERIALIZED VIEW' THEN 'materialized view' \
ELSE 'table' END FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
ELSE 'table' END, comment FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Oracle => format!(
"SELECT table_name, 'table' FROM all_tables WHERE owner = {} \
UNION ALL SELECT view_name, 'view' FROM all_views WHERE owner = {} ORDER BY 1",
quote_literal(driver, schema),
"SELECT table_name, CASE WHEN table_type = 'VIEW' THEN 'view' ELSE 'table' END, comments \
FROM all_tab_comments WHERE owner = {} ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Postgres => format!(
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END \
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, \
obj_description(c.oid, 'pg_class') \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = {} AND c.relkind IN ('r', 'v', 'm', 'p', 'f') ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Mysql => format!(
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
CASE WHEN table_type LIKE '%VIEW%' THEN NULL ELSE NULLIF(table_comment, '') END \
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::SqlServer => format!(
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
"SELECT t.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
CAST(ep.value AS nvarchar(max)) \
FROM INFORMATION_SCHEMA.TABLES t \
LEFT JOIN sys.extended_properties ep \
ON ep.major_id = OBJECT_ID(QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)) \
AND ep.minor_id = 0 AND ep.name = 'MS_Description' \
WHERE t.TABLE_SCHEMA = {} ORDER BY 1",
quote_literal(driver, schema)
),
}
@@ -301,7 +307,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1, c.comment \
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
"c.database",
@@ -312,7 +318,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END, NULL \
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
"'main'",
@@ -325,7 +331,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
AND a.attnum = ANY(i.indkey)) THEN 1 ELSE 0 END, \
CASE WHEN a.atthasdef OR EXISTS (SELECT 1 FROM pg_depend d WHERE d.refclassid = 'pg_class'::regclass \
AND d.refobjid = c.oid AND d.refobjsubid = a.attnum AND d.classid = 'pg_class'::regclass \
AND d.deptype = 'i') THEN 1 ELSE 0 END \
AND d.deptype = 'i') THEN 1 ELSE 0 END, col_description(c.oid, a.attnum) \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
@@ -336,7 +342,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
DbDriver::Mysql => (
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END, c.column_comment \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
@@ -351,7 +357,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END, NULL \
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
@@ -361,7 +367,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
DbDriver::Snowflake => (
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END, c.comment \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
@@ -372,8 +378,10 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END \
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
FROM all_tab_columns c \
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
AND cc.column_name = c.column_name \
LEFT JOIN all_views v ON v.owner = c.owner AND v.view_name = c.table_name \
LEFT JOIN (SELECT con.owner, con.table_name, kc.column_name FROM all_constraints con \
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
@@ -658,21 +666,22 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
)
}
/// Rows: `oid, relkind` of a PostgreSQL relation.
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
pub fn postgres_relation(schema: &str, name: &str) -> String {
format!(
"SELECT c.oid::text, c.relkind::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = {} AND c.relname = {}",
quote_literal(DbDriver::Postgres, schema),
quote_literal(DbDriver::Postgres, name)
)
}
/// Rows: `name, type, not null (0/1), default` of relation `oid`.
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
pub fn postgres_ddl_columns(oid: u32) -> String {
format!(
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
pg_get_expr(d.adbin, d.adrelid) FROM pg_attribute a \
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
)
@@ -695,6 +704,27 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
)
}
/// Rows: `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), grantable (0/1) of
/// the privileges relation `oid` grants beyond its owner's. A relation whose ACL was never
/// changed (`relacl` null) grants none.
pub fn postgres_ddl_grants(oid: u32) -> String {
format!(
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
string_agg(lower(a.privilege_type), ', ' ORDER BY a.privilege_type), \
CASE WHEN a.is_grantable THEN 1 ELSE 0 END \
FROM pg_class c CROSS JOIN LATERAL aclexplode(c.relacl) a \
WHERE c.oid = {oid} AND a.grantee <> c.relowner GROUP BY 1, 3 ORDER BY 1, 3"
)
}
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
pub fn postgres_ddl_triggers(oid: u32) -> String {
format!(
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
ORDER BY tgname"
)
}
/// Rows: `name, timing, events` of the triggers of a table (SQLite: `name, sql`).
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
@@ -934,6 +964,18 @@ pub struct DdlColumn {
pub data_type: String,
pub not_null: bool,
pub default: Option<String>,
pub comment: Option<String>,
}
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
#[derive(Default)]
pub struct DdlExtras {
pub comment: Option<String>,
pub owner: Option<String>,
/// `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), with grant option.
pub grants: Vec<(String, String, bool)>,
/// `CREATE TRIGGER …` statements.
pub triggers: Vec<String>,
}
/// `create table` of a PostgreSQL table from its catalog (the server has no `SHOW CREATE`).
@@ -943,6 +985,7 @@ pub fn postgres_table_ddl(
columns: &[DdlColumn],
constraints: &[(String, String)],
indexes: &[String],
extras: &DdlExtras,
) -> String {
let d = DbDriver::Postgres;
let mut items: Vec<String> = columns
@@ -959,9 +1002,31 @@ pub fn postgres_table_ddl(
})
.collect();
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
let mut out = format!("create table {}\n(\n{}\n);\n", qualified(d, schema, table), items.join(",\n"));
for i in indexes {
out.push_str(&format!("\n{i};\n"));
let target = qualified(d, schema, table);
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
if let Some(comment) = &extras.comment {
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
}
for c in columns {
if let Some(comment) = &c.comment {
let column = format!("{target}.{}", quote_ident(d, &c.name));
out.push_str(&format!("\ncomment on column {column} is {};\n", quote_literal(d, comment)));
}
}
if let Some(owner) = &extras.owner {
out.push_str(&format!("\nalter table {target}\n owner to {};\n", quote_ident(d, owner)));
}
if !extras.grants.is_empty() {
out.push('\n');
}
for (grantee, privileges, grantable) in &extras.grants {
let to = if grantee == "PUBLIC" { "public".to_owned() } else { quote_ident(d, grantee) };
let option = if *grantable { " with grant option" } else { "" };
out.push_str(&format!("grant {privileges} on {target} to {to}{option};\n"));
}
for statement in indexes.iter().chain(&extras.triggers) {
out.push_str(&format!("\n{};\n", statement.trim_end().trim_end_matches(';')));
}
out
}
@@ -988,6 +1053,24 @@ mod tests {
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
assert!(tables(DbDriver::Postgres, "public").contains("obj_description(c.oid, 'pg_class')"));
assert!(tables(DbDriver::Mysql, "db").contains("table_comment"));
assert!(tables(DbDriver::Oracle, "S").contains("all_tab_comments"));
assert!(tables(DbDriver::Clickhouse, "db").contains("END, comment FROM system.tables"));
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
// Completion (the hover card of a table or column) carries them too, as the ninth field.
let completion = |driver| completion_columns(driver, CompletionScope::All);
assert!(completion(DbDriver::Postgres).contains("col_description(c.oid, a.attnum)"));
assert!(completion(DbDriver::Mysql).contains("ELSE 0 END, c.column_comment"));
assert!(
completion(DbDriver::Oracle).contains("cc.comments")
&& completion(DbDriver::Oracle).contains("all_col_comments")
);
assert!(completion(DbDriver::Clickhouse).contains("c.is_in_primary_key, 1, c.comment"));
assert!(completion(DbDriver::Snowflake).contains("ELSE 0 END, c.comment"));
for driver in [DbDriver::Sqlite, DbDriver::SqlServer] {
assert!(completion(driver).contains("ELSE 0 END, NULL"), "{driver:?}");
}
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
@@ -1015,6 +1098,7 @@ mod tests {
assert_eq!(current_schema(driver), Some("SELECT currentDatabase()"));
let relations = tables(driver, "event's\\db");
assert!(relations.contains("WHEN 'MaterializedView' THEN 'materialized view'"));
assert!(relations.contains(r"END, comment FROM system.tables"));
assert!(relations.contains(r"WHERE database = 'event''s\\db' AND is_temporary = 0"));
let fields = columns(driver, "default", "events");
assert!(fields.starts_with("SELECT name, type, CASE WHEN startsWith(type, 'Nullable(')"));
@@ -1130,6 +1214,7 @@ mod tests {
#[test]
fn sqlserver_introspection_queries() {
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
@@ -1206,8 +1291,10 @@ mod tests {
assert_eq!(DbDriver::Oracle.default_port(), Some(1521));
assert!(schemas(DbDriver::Oracle, true).contains("all_users"));
assert!(schemas(DbDriver::Oracle, false).contains("'MDSYS'"));
assert!(tables(DbDriver::Oracle, "hr").contains("all_tables"));
assert!(tables(DbDriver::Oracle, "hr").contains("all_views"));
let relations = tables(DbDriver::Oracle, "hr");
assert!(relations.contains("all_tab_comments"));
assert!(relations.contains("table_type = 'VIEW'"));
assert!(relations.contains("comments"));
let cols = columns(DbDriver::Oracle, "hr", "employees");
assert!(cols.contains("all_tab_columns"));
assert!(cols.contains("DECODE(c.nullable, 'Y', 'YES', 'NO')"));
@@ -1296,12 +1383,13 @@ mod tests {
#[test]
fn postgres_ddl() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None },
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn {
name: "name".into(),
data_type: "character varying(40)".into(),
not_null: false,
default: Some("'x'::character varying".into()),
comment: None,
},
];
assert_eq!(
@@ -1310,12 +1398,53 @@ mod tests {
"t",
&cols,
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
&["CREATE INDEX t_name ON public.t USING btree (name)".into()]
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
&DdlExtras::default(),
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
);
}
#[test]
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn {
name: "note".into(),
data_type: "text".into(),
not_null: false,
default: None,
comment: Some("what's this".into()),
},
];
let extras = DdlExtras {
comment: Some("Orders".into()),
owner: Some("app owner".into()),
grants: vec![("PUBLIC".into(), "select".into(), false), ("reader".into(), "insert, select".into(), true)],
triggers: vec![
"CREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit()".into(),
],
};
assert_eq!(
postgres_table_ddl(
"public",
"t",
&cols,
&[],
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
&extras
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
\ncomment on table \"public\".\"t\" is 'Orders';\n\
\ncomment on column \"public\".\"t\".\"note\" is 'what''s this';\n\
\nalter table \"public\".\"t\"\n owner to \"app owner\";\n\
\ngrant select on \"public\".\"t\" to public;\n\
grant insert, select on \"public\".\"t\" to \"reader\" with grant option;\n\
\nCREATE INDEX t_note ON public.t USING btree (note);\n\
\nCREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit();\n"
);
}
#[test]
fn snowflake_quotes_names_and_reads_its_information_schema() {
let driver = DbDriver::Snowflake;
+10 -6
Переглянути файл
@@ -1,9 +1,9 @@
//! Data source files edited outside the Database tool window (by hand, by a coding
//! agent, by `git checkout`) are picked up while the project is open, as IDEA does
//! Data source and data source folder files edited outside the Database tool window
//! (by hand, by a coding agent, by `git checkout`) are picked up while the project is open, as IDEA does
//! for `dataSources.xml`. The project file tree's watcher is no help here: it never
//! reports a modification inside a gitignored `.openidea/`.
use crate::source::FILE;
use crate::source::{FILE, FOLDERS_FILE};
use ide_core::{IdeError, IdeResult, project_dir};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use parking_lot::Mutex;
@@ -15,8 +15,8 @@ use std::time::Duration;
/// the files are read.
const SETTLE: Duration = Duration::from_millis(200);
/// Watches `<root>/.openidea/data-sources.toml` and `<global>/data-sources.toml`;
/// stops when dropped.
/// Watches `<root>/.openidea/data-sources.toml`, `data-source-folders.toml` and
/// `<global>/data-sources.toml`; stops when dropped.
pub struct SourcesWatch {
_watcher: Arc<Mutex<RecommendedWatcher>>,
}
@@ -29,7 +29,7 @@ impl SourcesWatch {
let (tx, rx) = mpsc::channel::<()>();
let relevant = {
let config = config.clone();
move |p: &Path| p.file_name().is_some_and(|n| n == FILE) || p == config
move |p: &Path| p.file_name().is_some_and(|n| n == FILE || n == FOLDERS_FILE) || p == config
};
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
if let Ok(e) = res
@@ -131,6 +131,10 @@ mod tests {
std::fs::write(project.join(".openidea/data-sources.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "project file");
let seen = count.load(Ordering::SeqCst);
std::fs::write(project.join(".openidea/data-source-folders.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "project folders file");
let seen = count.load(Ordering::SeqCst);
std::fs::write(global.join("data-sources.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "global file");
+1
Переглянути файл
@@ -57,6 +57,7 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
assert!(schemas.iter().any(|n| n == s), "{s} missing from {schemas:?}");
let tables = db.tables("m", s).await?;
assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["用户"], "tables of {s}");
assert_eq!(tables[0].comment.as_deref(), Some("用户表"));
let d = db.table_details("m", s, "用户").await?;
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
assert_eq!(cols, ["id", "name", "raw"]);
+26 -1
Переглянути файл
@@ -353,6 +353,9 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
let orders = db.table_details("p", "oi_meta", "orders").await?;
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
let listed = db.tables("p", "oi_meta").await?;
let listed_orders = listed.iter().find(|table| table.name == "orders").expect("orders in the table list");
assert_eq!(listed_orders.comment.as_deref(), Some("Customer's orders"));
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
assert_eq!(comments, [None, None, Some("Free text")]);
assert_eq!(details.comment, None);
@@ -420,7 +423,29 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
db.execute("p", "CREATE SEQUENCE oi_keys.seq", 10, &c).await?;
let objects = db.schema_objects("p", "oi_keys").await?;
assert_eq!(objects.sequences.len(), 1);
assert!(db.ddl("p", "oi_keys", "refs").await?.contains("FOREIGN KEY"));
let plain = db.ddl("p", "oi_keys", "refs").await?;
assert!(plain.contains("FOREIGN KEY"), "{plain}");
assert!(plain.contains("\n owner to "), "{plain}");
assert!(!plain.contains("comment on") && !plain.contains("grant ") && !plain.contains("TRIGGER"), "{plain}");
// Comments, privileges and triggers come back too, so the script rebuilds the table.
for statement in [
"COMMENT ON TABLE oi_keys.refs IS 'Refs'",
"COMMENT ON COLUMN oi_keys.refs.x IS 'it''s x'",
"GRANT SELECT, INSERT ON oi_keys.refs TO PUBLIC",
"CREATE FUNCTION oi_keys.touch() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END'",
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch()",
] {
db.execute("p", statement, 10, &c).await?;
}
let full = db.ddl("p", "oi_keys", "refs").await?;
for part in [
"comment on table \"oi_keys\".\"refs\" is 'Refs';",
"comment on column \"oi_keys\".\"refs\".\"x\" is 'it''s x';",
"grant insert, select on \"oi_keys\".\"refs\" to public;",
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch();",
] {
assert!(full.contains(part), "{part}\n{full}");
}
db.execute("p", "DROP SCHEMA oi_keys CASCADE", 10, &c).await?;
Ok(())
}
+22 -13
Переглянути файл
@@ -27,18 +27,24 @@ const QUICK: Duration = Duration::from_secs(20);
/// Stop / restart wait for the container's grace period (10 s by default).
const LIFECYCLE: Duration = Duration::from_secs(90);
/// Locates the docker executable once per process. GUI apps on macOS start with a
/// minimal `PATH`, so the usual install locations are probed after the lookup.
/// Locates the docker executable. GUI apps on macOS start with a minimal `PATH`, so
/// the login/reloaded `PATH` and usual install locations are probed after the lookup.
/// Only a found path is cached, so installing Docker while the backend runs is picked up.
pub fn docker_executable() -> Option<PathBuf> {
static DOCKER: OnceLock<Option<PathBuf>> = OnceLock::new();
DOCKER
.get_or_init(|| {
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
if let Ok(found) = which::which("docker") {
return Some(found);
}
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
static DOCKER: OnceLock<PathBuf> = OnceLock::new();
if let Some(cached) = DOCKER.get().filter(|p| p.is_file()) {
return Some(cached.clone());
}
let found = which::which("docker")
.ok()
.or_else(|| {
let path = ide_core::process::host_var_os("PATH")?;
which::which_in("docker", Some(path), ".").ok()
})
.or_else(|| {
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
let mut candidates: Vec<PathBuf> = if cfg!(windows) {
vec![PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin\docker.exe")]
@@ -60,8 +66,11 @@ pub fn docker_executable() -> Option<PathBuf> {
candidates.push(home.join(".docker/bin/docker"));
}
candidates.into_iter().find(|p| p.is_file())
})
.clone()
});
if let Some(ref path) = found {
let _ = DOCKER.set(path.clone());
}
found
}
/// Environment for docker command lines a run configuration launches: the endpoint's
+1
Переглянути файл
@@ -76,6 +76,7 @@ tracing.workspace = true
url = "2"
tracing-subscriber.workspace = true
parking_lot.workspace = true
notify.workspace = true
dunce.workspace = true
dirs.workspace = true
uuid.workspace = true
+5
Переглянути файл
@@ -82,6 +82,11 @@ impl Environment {
}
}
/// True on `openidea-server`, where the backend runs on a remote/headless host rather than the desktop shell.
pub fn is_remote(&self) -> bool {
self.project_env
}
/// A trusted project at `root` opened or became trusted: loads its direnv environment in
/// the background, unless another window of it already did. Its language servers wait.
pub(crate) fn direnv_opened(&self, root: &Path, sink: &SharedSink) {
+26 -1
Переглянути файл
@@ -261,6 +261,12 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
}
}
/// The entry of the formatters' language lists that covers `language`. MDX was part of Markdown
/// and follows its entry, so lists saved before it had its own language keep formatting it.
fn formatter_language(language: &str) -> &str {
if language == "mdx" { "markdown" } else { language }
}
/// The external formatter of a file, for a language with an external formatter.
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
@@ -295,7 +301,8 @@ fn external_tool(
)))
};
}
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
let id = formatter_language(language.id.as_str());
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
Some(Black)
@@ -897,6 +904,24 @@ mod tests {
external_tool(forced, language.as_ref(), file, settings)
}
#[test]
fn mdx_follows_the_markdown_entry_of_saved_language_lists() {
// Saved before MDX had its own language: the whole list, with no `mdx` in it.
let old: ide_core::settings::Settings = serde_json::from_str(
r#"{"languages":{"prettier":{"languages":["markdown","css"]},"oxfmt":{"languages":["css"]}}}"#,
)
.unwrap();
let file = Path::new("/project/docs/intro.mdx");
assert_eq!(tool(None, "mdx", file, &old.languages).unwrap(), Some(Prettier));
let mut no_markdown = old.languages.clone();
no_markdown.prettier.languages.retain(|l| l != "markdown");
assert_eq!(tool(None, "mdx", file, &no_markdown).unwrap(), None);
let mut oxfmt = old.languages.clone();
oxfmt.oxfmt.languages.push("markdown".into());
oxfmt.oxfmt.prefer = true;
assert_eq!(tool(None, "mdx", file, &oxfmt).unwrap(), Some(Oxfmt));
}
#[test]
fn default_settings_use_ruff_for_python_and_prettier_for_the_web() {
let settings = LanguagesSettings::default();
+340
Переглянути файл
@@ -0,0 +1,340 @@
//! Project-scoped GitHub CLI (`gh`) account selection and opt-in `GH_TOKEN` injection.
//!
//! Each project may pin a GitHub login in `vcs.github.account` (`.openidea/settings.toml`) or
//! leave it empty (`Automatic`). `Automatic` leaves `gh`'s own behaviour untouched—no `GH_TOKEN`
//! is injected into [`ide_core::project_env`] and opening a project makes no GitHub API calls.
//! When the user inspects GitHub settings or Pull Requests with multiple `gh` keyring accounts,
//! OpenIDEA probes the repository remote (`owner/repo`) to suggest a matching non-active account
//! ("Use <login> for this project"). Only when an account is explicitly chosen does OpenIDEA
//! resolve its token into [`ide_core::project_env`] (for both `project.root` and `.worktrees`).
use crate::Project;
use ide_agent::GhAuthAccount;
use ide_core::cli_process::{CliTool, Decoding};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::LazyLock;
use std::time::{Duration, Instant};
const AMBIENT_GH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
const GH_TOOL: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
const LOCAL_TIMEOUT: Duration = Duration::from_secs(5);
const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
const CACHE_TTL: Duration = Duration::from_secs(10 * 60);
/// GitHub CLI accounts available on this machine and which one applies to the project.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GhProjectAccountStatus {
pub gh_installed: bool,
pub accounts: Vec<GhAuthAccount>,
/// Value of `vcs.github.account` (`""` = Automatic).
pub configured_account: String,
/// Account login currently used (`configured_account` if signed in, else `gh`'s active account).
pub effective_account: Option<String>,
/// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty.
pub suggested_account: Option<String>,
}
#[derive(Clone)]
struct CachedAutoAccount {
login: Option<String>,
at: Instant,
}
type AutoCacheMap = HashMap<(String, Vec<String>), CachedAutoAccount>;
static AUTO_CACHE: LazyLock<Mutex<AutoCacheMap>> = LazyLock::new(|| Mutex::new(HashMap::new()));
pub(crate) fn is_valid_github_login(login: &str) -> bool {
let bytes = login.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 39
&& bytes[0].is_ascii_alphanumeric()
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
}
fn find_gh_executable() -> Option<PathBuf> {
ide_core::tool_path::find_gh_executable()
}
fn clean_gh_command(program: &Path, args: &[&str]) -> Command {
let mut cmd = Command::new(program);
cmd.current_dir(std::env::temp_dir())
.args(args)
.env("GH_PROMPT_DISABLED", "1")
.env("GH_NO_UPDATE_NOTIFIER", "1")
.env("NO_COLOR", "1")
.env("CLICOLOR", "0");
// Strip ambient tokens by setting empty then removing after `prepare`: `CliTool::run` calls
// `ide_core::process::prepare`, which skips keys already present in `cmd.get_envs()`.
for key in AMBIENT_GH_VARS {
cmd.env_remove(key);
}
cmd
}
fn gh_token_for_account(program: &Path, login: &str) -> Option<String> {
if !is_valid_github_login(login) {
return None;
}
let cmd = clean_gh_command(program, &["auth", "token", "--hostname", "github.com", "--user", login]);
let out = GH_TOOL.run(cmd, LOCAL_TIMEOUT, None).ok().filter(|o| o.success)?;
let token = out.stdout.trim();
(!token.is_empty()).then(|| token.to_owned())
}
/// Access level of an account for a specific `owner/repo` on `github.com`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum RepoAccess {
None = 0,
Read = 1,
Push = 2,
}
fn probe_repo_access(program: &Path, token: &str, owner: &str, name: &str) -> RepoAccess {
let endpoint = format!("repos/{owner}/{name}");
let mut cmd =
clean_gh_command(program, &["api", "--hostname", "github.com", &endpoint, "--jq", ".permissions.push"]);
cmd.env("GH_TOKEN", token);
let Ok(out) = GH_TOOL.run(cmd, PROBE_TIMEOUT, None) else {
return RepoAccess::None;
};
if !out.success {
return RepoAccess::None;
}
if out.stdout.trim() == "true" { RepoAccess::Push } else { RepoAccess::Read }
}
fn pick_best_account(candidates: &[(GhAuthAccount, RepoAccess)]) -> Option<(&GhAuthAccount, bool)> {
let active_access =
candidates.iter().find(|(a, _)| a.active).map(|(_, access)| *access).unwrap_or(RepoAccess::None);
// Prefer higher RepoAccess; break ties in favor of the globally active account.
let (best, best_access) = candidates.iter().max_by_key(|(acc, access)| (*access, acc.active))?;
if *best_access == RepoAccess::None {
// Nobody could reach the repo (offline or SSO required): keep the active account.
return candidates.iter().find(|(a, _)| a.active).or_else(|| candidates.first()).map(|(a, _)| (a, false));
}
let auto_detected = !best.active && *best_access > active_access;
Some((best, auto_detected))
}
/// Parses `github.com` `(owner, repo)` from HTTPS, SSH, or SCP-style remote URLs.
pub(crate) fn parse_github_owner_repo(url: &str) -> Option<(String, String)> {
let url = url.trim();
let path = if let Some(rest) =
url.strip_prefix("https://github.com/").or_else(|| url.strip_prefix("http://github.com/"))
{
rest
} else if let Some(rest) = url.strip_prefix("ssh://") {
rest.strip_prefix("[email protected]/").or_else(|| rest.strip_prefix("github.com/"))?
} else {
url.strip_prefix("[email protected]:")?
};
let path = path.trim_matches('/');
let (owner, rest) = path.split_once('/')?;
let repo = rest.split('/').next()?;
let repo = repo.strip_suffix(".git").unwrap_or(repo);
if owner.is_empty() || repo.is_empty() {
return None;
}
Some((owner.to_owned(), repo.to_owned()))
}
fn primary_github_repo(project: &Project) -> Option<(String, String)> {
let repos = project.repos();
let mut ordered = Vec::new();
if let Some(primary) = repos.primary() {
ordered.push(primary);
}
for repo in repos.all() {
if ordered.first().is_none_or(|p| p.root() != repo.root()) {
ordered.push(repo);
}
}
for repo in ordered {
let Ok(mut remotes) = repo.remotes() else { continue };
remotes.sort_by_key(|r| r.name != "origin");
for remote in remotes {
let url = remote.resolved_url.as_deref().unwrap_or(&remote.url);
if let Some(coords) = parse_github_owner_repo(url) {
return Some(coords);
}
}
}
None
}
fn auto_detect_account(program: &Path, accounts: &[GhAuthAccount], owner: &str, repo: &str) -> Option<(String, bool)> {
// Fast path: the repository owner matches one of the signed-in accounts directly.
if let Some(matched) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(owner)) {
return Some((matched.login.clone(), !matched.active));
}
let key_repo = format!("{}/{}", owner.to_ascii_lowercase(), repo.to_ascii_lowercase());
let key_logins: Vec<String> = accounts.iter().map(|a| format!("{}:{}", a.login, a.active)).collect();
let cache_key = (key_repo, key_logins);
if let Some(cached) = AUTO_CACHE.lock().get(&cache_key).cloned()
&& cached.at.elapsed() < CACHE_TTL
{
if let Some(login) = cached.login {
let is_active = accounts.iter().any(|a| a.login == login && a.active);
return Some((login, !is_active));
}
return None;
}
let tokens: Vec<(GhAuthAccount, Option<String>)> =
accounts.iter().map(|acc| (acc.clone(), gh_token_for_account(program, &acc.login))).collect();
let results: Vec<(GhAuthAccount, RepoAccess)> = std::thread::scope(|s| {
let handles: Vec<_> = tokens
.into_iter()
.map(|(acc, token)| {
s.spawn(move || {
let access = match token {
Some(tok) => probe_repo_access(program, &tok, owner, repo),
None => RepoAccess::None,
};
(acc, access)
})
})
.collect();
handles.into_iter().filter_map(|h| h.join().ok()).collect()
});
let picked = pick_best_account(&results).map(|(acc, auto)| (acc.login.clone(), auto));
AUTO_CACHE
.lock()
.insert(cache_key, CachedAutoAccount { login: picked.as_ref().map(|(l, _)| l.clone()), at: Instant::now() });
picked
}
/// Resolves global status when no project is open.
pub fn global_status(configured_account: String) -> GhProjectAccountStatus {
let configured_account = configured_account.trim().to_owned();
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
let effective_account = if !configured_account.is_empty() {
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
} else {
accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone())
};
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account: None }
}
/// Applies the project's explicit `vcs.github.account` setting to [`ide_core::project_env`]
/// without making any network requests. `Automatic` (`""`) clears any injected `GH_TOKEN` so
/// processes use `gh`'s own behaviour.
pub fn apply_to_project(project: &Project) {
if project.light || !project.is_trusted() {
clear_project_env(project);
return;
}
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
if configured_account.is_empty() {
set_project_token(project, None);
return;
}
let token = find_gh_executable().and_then(|program| gh_token_for_account(&program, &configured_account));
set_project_token(project, token);
}
/// Applies the project's explicit account setting and returns the full account status,
/// probing the project's GitHub remote to suggest a matching non-active `gh` account when
/// `vcs.github.account` is `Automatic` (`""`) and multiple `gh` accounts are signed in.
pub fn project_status(project: &Project) -> GhProjectAccountStatus {
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
if project.light || !project.is_trusted() {
clear_project_env(project);
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
}
apply_to_project(project);
let Some(program) = find_gh_executable() else {
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
};
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
let active_login = accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone());
let effective_account = if !configured_account.is_empty() {
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
} else {
active_login
};
let suggested_account = if configured_account.is_empty() && accounts.len() >= 2 {
primary_github_repo(project)
.and_then(|(owner, repo)| auto_detect_account(&program, &accounts, &owner, &repo))
.and_then(|(login, non_active_match)| non_active_match.then_some(login))
} else {
None
};
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account }
}
fn set_project_token(project: &Project, token: Option<String>) {
let os_tok = token.map(std::ffi::OsString::from);
let changed_root = ide_core::project_env::set_github_token(&project.root, os_tok.clone());
let changed_wt = ide_core::project_env::set_github_token(project.agents.worktrees_dir(), os_tok);
if changed_root || changed_wt {
project.agents.notify_mcp_servers_changed();
}
}
pub fn clear_project_env(project: &Project) {
ide_core::project_env::remove_all(&project.root);
ide_core::project_env::remove_all(project.agents.worktrees_dir());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_github_owner_repo_across_https_ssh_and_scp_remotes() {
assert_eq!(
parse_github_owner_repo("https://github.com/l0ng-ai/openidea.git"),
Some(("l0ng-ai".into(), "openidea".into()))
);
assert_eq!(
parse_github_owner_repo("[email protected]:acme-corp/payments.git"),
Some(("acme-corp".into(), "payments".into()))
);
assert_eq!(parse_github_owner_repo("ssh://[email protected]/alice/demo/"), Some(("alice".into(), "demo".into())));
assert_eq!(parse_github_owner_repo("https://gitlab.com/foo/bar.git"), None);
}
#[test]
fn validates_github_logins_against_flag_injection() {
assert!(is_valid_github_login("alice"));
assert!(is_valid_github_login("alice-work"));
assert!(is_valid_github_login("l0ng-ai"));
assert!(!is_valid_github_login(""));
assert!(!is_valid_github_login("--hostname"));
assert!(!is_valid_github_login("bad space"));
}
#[test]
fn picks_account_with_push_or_private_access_and_preserves_active_on_ties() {
let personal = GhAuthAccount { login: "alice".into(), active: true };
let work = GhAuthAccount { login: "alice-work".into(), active: false };
// Private org repo: personal gets 404 (None), work gets Push -> auto-detects work.
let private_org = vec![(personal.clone(), RepoAccess::None), (work.clone(), RepoAccess::Push)];
let (picked, auto) = pick_best_account(&private_org).unwrap();
assert_eq!(picked.login, "alice-work");
assert!(auto);
// Public org repo: personal gets Read, work gets Push -> auto-detects work.
let public_org = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Push)];
let (picked, auto) = pick_best_account(&public_org).unwrap();
assert_eq!(picked.login, "alice-work");
assert!(auto);
// Third-party public repo: both get Read -> keeps active personal account without auto flag.
let oss = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Read)];
let (picked, auto) = pick_best_account(&oss).unwrap();
assert_eq!(picked.login, "alice");
assert!(!auto);
}
}
+97 -4
Переглянути файл
@@ -2,7 +2,7 @@
use ide_build::kotlin_bridge::{self, Outcome, ProjectLibraries};
use ide_core::event::NotifyLevel;
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink, TaskId};
use ide_lsp::LspManager;
use ide_workspace::SettingsStore;
use ide_workspace::documents::DocumentObserver;
@@ -223,9 +223,15 @@ impl KotlinBridge {
let staging = directory.clone();
let root = self.root.clone();
let token = cancel.clone();
let result =
tokio::task::spawn_blocking(move || kotlin_bridge::build(&root, &model, &bundle, &staging, &token))
.await;
// The build runs Maven over the Kotlin modules, which can take a minute: it shows in
// the status bar and can be stopped there (the next saved change builds again).
let task = BuildTask::start(self.sink.clone(), &cancel);
let progress = task.reporter();
let result = tokio::task::spawn_blocking(move || {
kotlin_bridge::build(&root, &model, &bundle, &staging, &token, &progress)
})
.await;
drop(task);
if !self.revision.lock().current(generation) || self.lifetime.is_cancelled() {
remove_directory(directory).await;
continue;
@@ -306,6 +312,58 @@ impl KotlinBridge {
}
}
/// The status bar's background task for one bridge build; ends when dropped.
struct BuildTask {
id: TaskId,
sink: SharedSink,
_cancel: ide_core::task::CancelHandle,
}
impl BuildTask {
const TITLE: &str = "Compiling Kotlin for Java";
fn start(sink: SharedSink, cancel: &CancellationToken) -> Self {
let id = TaskId::next();
let cancel = cancel.clone();
let handle = ide_core::task::on_cancel(id, move || cancel.cancel());
let task = Self { id, sink, _cancel: handle };
task.emit(None, None, false);
task
}
fn emit(&self, message: Option<String>, fraction: Option<f32>, done: bool) {
self.sink.emit(IdeEvent::Task {
id: self.id,
title: Self::TITLE.into(),
message,
fraction,
done,
cancellable: !done,
});
}
/// Forwards Maven's progress to the task.
fn reporter(&self) -> impl Fn(&str, Option<f32>) + Send + Sync + 'static {
let (id, sink) = (self.id, self.sink.clone());
move |message: &str, fraction| {
sink.emit(IdeEvent::Task {
id,
title: Self::TITLE.into(),
message: Some(message.to_owned()),
fraction,
done: false,
cancellable: true,
})
}
}
}
impl Drop for BuildTask {
fn drop(&mut self) {
self.emit(None, None, true);
}
}
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
@@ -369,6 +427,41 @@ impl DocumentObserver for KotlinBridge {
mod tests {
use super::*;
#[test]
fn a_build_shows_as_a_cancellable_background_task() {
let events = Arc::new(Mutex::new(Vec::new()));
let sink: SharedSink = Arc::new({
let events = events.clone();
move |e: IdeEvent| events.lock().push(e)
});
let cancel = CancellationToken::new();
let task = BuildTask::start(sink, &cancel);
let progress = task.reporter();
progress("Building app 1.0 [2/3]", Some(0.5));
assert!(ide_core::task::cancel(task.id), "the status bar can stop it");
assert!(cancel.is_cancelled());
drop(task);
let seen: Vec<_> = events
.lock()
.iter()
.map(|e| match e {
IdeEvent::Task { title, message, fraction, done, cancellable, .. } => {
assert_eq!(title, "Compiling Kotlin for Java");
(message.clone(), *fraction, *done, *cancellable)
}
other => panic!("{other:?}"),
})
.collect();
assert_eq!(
seen,
[
(None, None, false, true),
(Some("Building app 1.0 [2/3]".into()), Some(0.5), false, true),
(None, None, true, false),
]
);
}
#[test]
fn target_package_directory_does_not_trigger() {
let dir = tempfile::tempdir().unwrap();
+4
Переглянути файл
@@ -12,6 +12,7 @@ pub mod diagnostics_store;
mod direnv;
pub mod environment;
mod formatter;
pub mod github_auth;
mod java_runtime;
mod kotlin_bridge;
pub mod mcp;
@@ -124,6 +125,7 @@ pub struct Host {
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
/// The IDE's Java build: resident javac processes shared by every window's launches.
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
pub(crate) metrics_sampler: Mutex<ops::host_metrics::HostMetricsSampler>,
/// SSH connections of Settings › SSH Configurations.
pub ssh: Arc<ide_ssh::SshManager>,
/// SFTP deployment, remote file editing and runs on run targets.
@@ -254,6 +256,7 @@ impl Host {
heap_requests: Default::default(),
rebase_editors: Default::default(),
java_build: Default::default(),
metrics_sampler: Default::default(),
languages,
syntax,
config_dir,
@@ -419,6 +422,7 @@ impl Host {
self.environment.project_closed();
if self.windows_for_root(&project.root).is_empty() {
self.environment.direnv_closed(&project.root);
crate::github_auth::clear_project_env(&project);
}
}
if let Some(bridge) = &project.kotlin_bridge {
+5
Переглянути файл
@@ -38,6 +38,11 @@ impl Requests {
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
Ok(())
}
/// Whether `window` answers requests (a project loaded for MCP alone has no window).
pub(super) fn window_ready(&self, window: &str) -> bool {
self.0.lock().ready.contains(window)
}
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
let id = super::tool::request_id().0;
let (tx, rx) = oneshot::channel();
+87 -7
Переглянути файл
@@ -15,8 +15,9 @@ use ide_core::{IdeError, IdeResult, RunId, Severity};
use ide_run::{OutputChunk, RunConfig};
use parking_lot::Mutex;
use serde_json::{Map, Value, json};
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};
@@ -286,6 +287,79 @@ workingDirectory, envs).",
/// not the user's own runs.
static STARTED: LazyLock<Mutex<HashSet<RunId>>> = LazyLock::new(Default::default);
/// Run configuration parameter naming the `execute_run_configuration` call a start belongs to.
pub const CONFIG_RUN_PARAM: &str = "mcp.configRun";
/// The `execute_run_configuration` calls waiting for the Run tool window to start their run.
struct ConfigLaunch {
output: Arc<Mutex<OutputCollector>>,
started: Option<Result<ide_run::RunInfo, String>>,
}
static LAUNCHES: LazyLock<Mutex<HashMap<u64, ConfigLaunch>>> = LazyLock::new(Default::default);
static NEXT_LAUNCH: AtomicU64 = AtomicU64::new(1);
/// The Run tool window's start of an `execute_run_configuration` run: its output also goes to
/// the call's output file, and the call learns the run it started.
pub(crate) struct ConfigRunLaunch {
token: u64,
output: Arc<Mutex<OutputCollector>>,
}
/// The call `config` was started for (its first start only; a rerun from the tab is the user's).
pub(crate) fn config_run_launch(config: &RunConfig) -> Option<ConfigRunLaunch> {
let token = config.extras.params.get(CONFIG_RUN_PARAM)?.parse().ok()?;
let launches = LAUNCHES.lock();
let launch = launches.get(&token).filter(|l| l.started.is_none())?;
Some(ConfigRunLaunch { token, output: launch.output.clone() })
}
impl ConfigRunLaunch {
pub(crate) fn wrap_output(&self, on_output: crate::ops::Emit<OutputChunk>) -> crate::ops::Emit<OutputChunk> {
let output = self.output.clone();
Arc::new(move |chunk: OutputChunk| {
// As JetBrains skips `ProcessOutputType.SYSTEM` (`Process finished…`).
if let OutputChunk::Stdout { text } | OutputChunk::Stderr { text } = &chunk {
output.lock().append(text);
}
on_output(chunk);
})
}
pub(crate) fn started(&self, result: &IdeResult<ide_run::RunInfo>) {
if let Some(launch) = LAUNCHES.lock().get_mut(&self.token) {
launch.started = Some(result.clone().map_err(|e| e.message));
}
}
}
/// Starts `config` in the Run tool window, as the user's Run would: a tab with its console and
/// Stop. Its before launch tasks already ran.
async fn start_in_run_window(
call: &Call,
mut config: RunConfig,
output: Arc<Mutex<OutputCollector>>,
) -> IdeResult<ide_run::RunInfo> {
struct Forget(u64);
impl Drop for Forget {
fn drop(&mut self) {
LAUNCHES.lock().remove(&self.0);
}
}
let token = NEXT_LAUNCH.fetch_add(1, Ordering::Relaxed);
LAUNCHES.lock().insert(token, ConfigLaunch { output, started: None });
let _forget = Forget(token);
config.extras.params.insert(CONFIG_RUN_PARAM.into(), token.to_string());
let config = serde_json::to_value(&config).map_err(|e| IdeError::invalid(e.to_string()))?;
let asked = call.ask(ide_core::event::McpUiRequest::RunConfiguration { config }).await;
let started = LAUNCHES.lock().get_mut(&token).and_then(|l| l.started.take());
match (asked, started) {
(_, Some(Ok(info))) => Ok(info),
(_, Some(Err(message))) => Err(IdeError::invalid(message)),
(Err(e), None) => Err(e),
(Ok(()), None) => Err(IdeError::invalid("the run did not start")),
}
}
pub(super) fn started_by_mcp(id: RunId) -> bool {
STARTED.lock().contains(&id)
}
@@ -753,9 +827,9 @@ Behavior:
Returns the execution result including current output snapshot, optional exit code, and optional `fullOutputPath`.
In OpenIDEA the user is asked first for every call; `programArguments` replace the configuration's \
arguments (appended to a command that is one shell line, such as `npm run dev`); the run does not appear in the Run \
tool window: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \
and deleted after a day.",
arguments (appended to a command that is one shell line, such as `npm run dev`); the run appears in the Run tool \
window like a run the user started, with its console and Stop; while it is still running, the result carries `runId`, \
which `stop_run` stops; output files are private and deleted after a day.",
|call| async move {
let target = execution_target(
call.opt_str("configurationName")?,
@@ -811,9 +885,15 @@ one by one",
};
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
let output_path = collector.lock().path.clone();
let sink = collector.clone();
let emit = process_output(move |text| sink.lock().append(text));
let info = match crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await {
let started = if call.has_window() {
start_in_run_window(&call, config, collector.clone()).await
} else {
// A project loaded for MCP alone has no Run tool window to show it in.
let sink = collector.clone();
let emit = process_output(move |text| sink.lock().append(text));
crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await
};
let info = match started {
Ok(info) => info,
Err(e) => {
let _ = std::fs::remove_file(&output_path);
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@
pub(crate) mod agent;
mod agent_tools;
mod build;
mod configs;
pub(crate) mod configs;
mod output;
mod process;
mod targets;
+35 -1
Переглянути файл
@@ -493,7 +493,7 @@ fn test_kinds(rel: &str) -> &'static [&'static str] {
if JS_FILE.is_match(rel) {
&["npm", "deno", "bun"]
} else if rel.ends_with(".py") {
&["pytest", "python"]
&["pytest", "unittest", "python"]
} else if rel.ends_with(".go") {
&["go"]
} else if rel.ends_with(".rs") {
@@ -644,6 +644,11 @@ fn test_config_for(root: &Path, rel: &str, configs: &[RunConfig]) -> Option<RunC
"npm" | "bun" if base.args.iter().any(|a| a == "--") => derived(&base, rel, with(&[file])),
"npm" | "bun" => derived(&base, rel, with(&["--".into(), file])),
"deno" | "pytest" | "python" => derived(&base, rel, with(&[file])),
// `python -m unittest <file>`; a `discover` selection gives way to the file.
"unittest" => {
let end = base.args.iter().position(|a| a == "discover").unwrap_or(base.args.len());
derived(&base, rel, [base.args[..end].to_vec(), vec![file]].concat())
}
"go" => {
let dir = dir_of(&file);
let target = if dir.is_empty() { ".".to_owned() } else { format!("./{dir}") };
@@ -790,6 +795,11 @@ pub fn target_config(
"pytest" | "python" => {
Some(named(replace_last(file.args.clone(), |f| format!("{f}::{}", target.path.join("::")))))
}
// unittest names tests by dotted module path: `tests.test_calc.TestCalc.test_add`.
"unittest" => Some(named(replace_last(file.args.clone(), |f| {
let module = f.strip_suffix(".py").unwrap_or(f).replace(['/', '\\'], ".");
format!("{module}.{}", target.path.join("."))
}))),
"go" => {
let pattern = format!("^{}$", target.path.iter().map(|p| escape_regexp(p)).collect::<Vec<_>>().join("$/^"));
let benchmark = target.path.first().is_some_and(|p| p.starts_with("Benchmark"));
@@ -921,6 +931,30 @@ mod tests {
);
}
#[test]
fn narrows_unittest_configs_to_files_and_dotted_tests() {
let root = Path::new("/p");
let mut unittest =
blank("unittest".into(), "unittest", "unittest", "python3".into(), vec!["-m".into(), "unittest".into()]);
unittest.is_test = true;
let mut discover = unittest.clone();
discover.args.extend(["discover".into(), "-s".into(), "tests".into()]);
let src = "import unittest\n\nclass TestCalc(unittest.TestCase):\n def test_add(self):\n pass\n";
let rel = "tests/test_calc.py";
for configs in [vec![unittest], vec![discover]] {
let c = context_config(root, rel, &configs, src).unwrap();
assert_eq!(
(c.kind.as_str(), c.args.as_slice()),
("unittest", ["-m", "unittest", rel].map(String::from).as_slice())
);
let ts = detect(src, rel);
let c = target_config(root, &ts[1], rel, &configs, src).unwrap();
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc.test_add"]);
let c = target_config(root, &ts[0], rel, &configs, src).unwrap();
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc"]);
}
}
#[test]
fn narrows_cargo_test_configs() {
let root = Path::new("/p");
+4
Переглянути файл
@@ -70,6 +70,10 @@ impl Call {
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
self.host.mcp_requests.ask(self, request).await
}
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
pub fn has_window(&self) -> bool {
self.host.mcp_requests.window_ready(&self.window)
}
/// Asks the user before a tool changes the project or starts a process, unless brave mode
/// is on — read from the IDE's own settings only, which a project's settings can't set.
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
+2
Переглянути файл
@@ -754,6 +754,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
));
let mut tools = vec![
act("code.saveAsLiveTemplate", "Save as Live Template…"),
SEP,
act("http.newRequest", "New HTTP Request"),
act("http.showToolWindow", "HTTP Client"),
SEP,
+55 -1
Переглянути файл
@@ -1,11 +1,12 @@
//! Project-incarnation notebook ownership and whole-batch execution admission.
use crate::ops::Channel;
use base64::Engine;
use ide_core::error::ErrorKind;
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, IpcPath, SharedSink};
use ide_notebook::kernel::{KernelManager, KernelOutput};
use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot};
use parking_lot::Mutex;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
@@ -28,6 +29,31 @@ pub struct NotebookOutputEvent {
pub changed_cells: Vec<String>,
}
/// One row of the Jupyter Variables tool window.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
pub struct NotebookVariable {
pub name: String,
#[serde(rename = "type")]
pub type_name: String,
pub value: String,
}
const VARIABLES: &str = include_str!("notebook_variables.py");
/// The rows from the `user_expressions` of the variables request.
fn parse_variables(reply: &serde_json::Value) -> IdeResult<Vec<NotebookVariable>> {
let rows = &reply["rows"];
if rows["status"] != "ok" {
let reason = rows["evalue"].as_str().unwrap_or("no result");
return Err(IdeError::unavailable(format!("could not read the kernel's variables: {reason}")));
}
// The value is a base64 str, so its text/plain is that text in quotes.
let text = rows["data"]["text/plain"].as_str().unwrap_or_default().trim_matches(['\'', '"']);
let bad = |error: String| IdeError::unavailable(format!("could not read the kernel's variables: {error}"));
let json = base64::engine::general_purpose::STANDARD.decode(text).map_err(|e| bad(e.to_string()))?;
serde_json::from_slice(&json).map_err(|e| bad(e.to_string()))
}
#[derive(Default)]
struct Registry {
stopped: bool,
@@ -323,6 +349,19 @@ impl NotebookService {
Ok(())
}
/// The variables of the notebook's running kernel; `None` when no kernel runs.
pub async fn variables(&self, id: &str) -> IdeResult<Option<Vec<NotebookVariable>>> {
let document = self.resolve(id)?;
if document.state.lock().active.is_some() {
return Err(IdeError::unavailable("notebook is running"));
}
let expressions = HashMap::from([("rows".to_owned(), "_openidea_variables()".to_owned())]);
match self.kernels.inspect(&document.path, VARIABLES, expressions).await? {
Some(reply) => parse_variables(&reply).map(Some),
None => Ok(None),
}
}
pub(crate) fn admit(
&self,
id: &str,
@@ -588,6 +627,21 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn variables_are_decoded_from_the_user_expression() {
let rows = r#"[{"name": "x", "type": "int", "value": "1"}]"#;
let text = format!("'{}'", base64::engine::general_purpose::STANDARD.encode(rows));
let reply = json!({"rows": {"status": "ok", "data": {"text/plain": text}, "metadata": {}}});
assert_eq!(
parse_variables(&reply).unwrap(),
vec![NotebookVariable { name: "x".into(), type_name: "int".into(), value: "1".into() }]
);
let failed =
json!({"rows": {"status": "error", "ename": "NameError", "evalue": "name 'get_ipython' is not defined"}});
assert!(parse_variables(&failed).unwrap_err().message.contains("get_ipython"));
assert!(parse_variables(&json!({})).is_err());
}
fn fixture() -> (tempfile::TempDir, Arc<NotebookService>, NotebookSnapshot) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("session.ipynb");
+23
Переглянути файл
@@ -0,0 +1,23 @@
# Run silently on a notebook's kernel by the Jupyter Variables tool window; the IDE then
# evaluates `_openidea_variables()` as a user expression. Same rows as the Python Console's.
def _openidea_variables():
import base64
import json
import reprlib
import types
shell = get_ipython() # noqa: F821 -- defined in every IPython namespace
short = reprlib.Repr()
short.maxstring = short.maxother = 200
rows = []
for name, value in list(shell.user_ns.items()):
if name.startswith("_") or name in shell.user_ns_hidden or isinstance(value, types.ModuleType):
continue
try:
text = short.repr(value)
except Exception as error: # a broken __repr__ must not hide the other variables
text = "<repr failed: %s>" % type(error).__name__
rows.append({"name": name, "type": type(value).__name__, "value": text})
rows.sort(key=lambda row: row["name"])
# Base64 so the expression's text/plain (a str repr) needs no unescaping.
return base64.b64encode(json.dumps(rows).encode()).decode()
+79 -5
Переглянути файл
@@ -80,6 +80,19 @@ pub fn agent_refresh_models(
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
}
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
#[command(trust = trusted)]
pub async fn agent_preview_copilot_models(
host: &Host,
window: &str,
account: String,
model: Option<String>,
) -> IdeResult<AgentModelCatalog> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
agents.preview_copilot_models(&account, model.as_deref()).await
}
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
#[command(trust = trusted)]
@@ -122,6 +135,39 @@ pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult<C
}
}
const REMOTE_SESSION_ENV_VARS: [&str; 5] =
["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "CODESPACES", "REMOTE_CONTAINERS"];
fn prepare_login_launch_env(
is_remote: bool,
target_is_gh: bool,
env: &mut std::collections::BTreeMap<String, String>,
host_has: impl Fn(&str) -> bool,
) {
if !is_remote {
return;
}
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
};
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
if !REMOTE_SESSION_ENV_VARS.iter().any(|key| has_non_empty(env, key)) {
env.insert("REMOTE_CONTAINERS".into(), "1".into());
}
if target_is_gh && !has_non_empty(env, "GH_BROWSER") && !has_non_empty(env, "BROWSER") {
env.insert("GH_BROWSER".into(), "true".into());
}
}
fn apply_remote_login_env(host: &Host, cwd: &std::path::Path, target_is_gh: bool, launch: &mut LoginLaunch) {
let cwd = if cwd.is_dir() { cwd.to_path_buf() } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
prepare_login_launch_env(host.environment.is_remote(), target_is_gh, &mut launch.env, |key| {
ide_core::process::host_var_os_in(&cwd, key).is_some_and(|v| !v.is_empty())
});
}
fn spawn_login_pty(
host: &Host,
window: &str,
@@ -167,7 +213,7 @@ pub async fn agent_login_spawn(
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
host.require_trust_if_project(window)?;
let (cwd, launch) = match host.project(window) {
let (cwd, mut launch) = match host.project(window) {
Ok(project) => {
let root = project.root.clone();
let agents = project.agents.clone();
@@ -186,6 +232,7 @@ pub async fn agent_login_spawn(
(cwd, launch)
}
};
apply_remote_login_env(host, &cwd, false, &mut launch);
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
}
@@ -204,7 +251,8 @@ pub async fn agent_gh_login_spawn(
.project(window)
.map(|p| p.root.clone())
.unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir));
let launch = host.blocking(ide_agent::gh_login_launch).await?;
let mut launch = host.blocking(ide_agent::gh_login_launch).await?;
apply_remote_login_env(host, &cwd, true, &mut launch);
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
}
@@ -356,8 +404,9 @@ pub async fn agent_commands(
host.project(window)?.agents.commands(&provider, task.as_deref()).await
}
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. Async so a long
/// conversation is cloned and serialised off the main thread.
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. On the blocking pool:
/// the first read of a saved conversation parses its task file, and a long one is cloned
/// and serialised.
#[command(trust = always)]
pub async fn agent_entries(
host: &Host,
@@ -365,7 +414,8 @@ pub async fn agent_entries(
task: String,
subagent: Option<String>,
) -> IdeResult<Vec<AgentEntry>> {
host.project(window)?.agents.entries(&task, subagent)
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.entries(&task, subagent)).await
}
/// Sessions of the project on this machine that no task holds yet, newest first.
@@ -1549,6 +1599,29 @@ mod tests {
assert!(reloaded.approved(&root, "extra", &extra));
assert!(!reloaded.approved(&tmp.path().join("other"), "extra", &extra));
}
#[test]
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
let mut desktop_env = std::collections::BTreeMap::new();
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
assert!(desktop_env.is_empty());
let mut remote_agent_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
let mut remote_gh_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
// Preserves existing SSH/remote indicators and explicit browser settings.
let mut ssh_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
assert!(!ssh_env.contains_key("GH_BROWSER"));
}
}
ide_command::domain!(
@@ -1584,6 +1657,7 @@ ide_command::domain!(
agent_mcp_save_json,
agent_mcp_set_enabled,
agent_mcp_test,
agent_preview_copilot_models,
agent_probe,
agent_prompt,
agent_providers,
+25 -4
Переглянути файл
@@ -3,7 +3,7 @@ use crate::Host;
use ide_command::command;
use super::blocking;
use ide_core::{IdeResult, IpcPath};
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
use ide_run::RunConfig;
@@ -35,9 +35,30 @@ pub async fn coverage_collect(host: &Host, window: &str, report: CoverageReportS
/// with paths mapped into this project.
#[command(trust = always)]
pub async fn coverage_import(host: &Host, window: &str, path: IpcPath) -> IdeResult<CoverageSuite> {
// Also reads a SimpleCov resultset.
let root = host.project(window)?.root.clone();
blocking(move || ide_coverage::import(&path, &root)).await
// Also reads Cobertura XML, a SimpleCov resultset and coverage.py data files.
let project = host.project(window)?;
let (root, cache, config_dir) =
(project.root.clone(), project.cache_dir.join("coverage-import"), host.config_dir.clone());
let trusted = project.require_trust();
blocking(move || {
if !ide_coverage::is_data_file(&path) {
return ide_coverage::import(&path, &root);
}
// coverage.py analyses the sources with the project's interpreter: that runs project code.
trusted.map_err(|_| {
IdeError::unavailable(
"Reading a .coverage data file runs the project's Python. Trust the project, or import the output of `coverage xml`.",
)
})?;
let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| {
IdeError::unavailable(
"Reading a .coverage data file needs the project's Python interpreter. Choose one, or import the output of `coverage xml`.",
)
})?;
let out = ide_run::wrap::new_output_dir(&cache, KEEP_RUNS)?;
ide_coverage::import_data(&path, &root, &python, &out)
})
.await
}
ide_command::domain!(coverage: coverage_collect, coverage_import, coverage_prepare);
+29 -3
Переглянути файл
@@ -8,8 +8,8 @@ use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
use ide_db::split::SqlStatement;
use ide_db::{
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode,
QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange, HistoryEntry,
PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -75,6 +75,20 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
sources_changed(host, window)
}
#[command(trust = trusted)]
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
// The project's user-created folders and their data source members.
ide_db::source::load_folders(&host.project(window)?.root)
}
#[command(trust = trusted)]
pub fn db_save_source_folders(host: &Host, window: &str, folders: Vec<DbSourceFolder>) -> IdeResult<()> {
// Replaces the project's data source folders; only grouping changes, never a source.
let root = host.project(window)?.root.clone();
ide_db::source::save_folders(&root, &folders)?;
sources_changed(host, window)
}
#[command(trust = trusted)]
pub async fn db_save_source_visibility(
host: &Host,
@@ -612,7 +626,16 @@ pub fn db_consoles(host: &Host, id: String, create: bool) -> IdeResult<Vec<IpcPa
Ok(out)
}
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
/// The project view root for every data source's query consoles (`<dataDir>/consoles/db`).
#[command(trust = always)]
pub fn db_consoles_dir(host: &Host) -> IdeResult<IpcPath> {
let dir = host.data_dir.join("consoles").join("db");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database,
/// `<id>.<database>` for the others.
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
let (source, database) = ide_db::split_target(id);
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
@@ -670,6 +693,7 @@ ide_command::domain!(
db_connect,
db_connected,
db_console_path,
db_consoles_dir,
db_consoles,
db_create_database,
db_database_catalog,
@@ -692,6 +716,7 @@ ide_command::domain!(
db_result_row,
db_remove_history,
db_retain_catalog,
db_save_source_folders,
db_save_source_visibility,
db_save_sources,
db_saved_catalog,
@@ -701,6 +726,7 @@ ide_command::domain!(
db_set_manual_commit,
db_set_password,
db_set_ssh_secret,
db_source_folders,
db_sources,
db_statements,
db_table_details,
+2 -1
Переглянути файл
@@ -60,7 +60,8 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
python.as_deref(),
config.cwd.as_deref(),
);
super::python::prepare_debug(&mut config, &paths)?;
let plots = super::plots::prepare(host, &project);
super::python::prepare_debug(&mut config, &paths, plots.as_ref())?;
}
let label = window;
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
+19 -3
Переглянути файл
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
#[command(trust = always)]
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
host.blocking(move || project.documents.save(doc)).await?;
host.blocking(move || {
project.documents.save(doc)?;
remember_saved_encodings(&project);
Ok(())
})
.await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
#[command(trust = always)]
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
let project = host.project(window)?;
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
let saved = host
.blocking(move || {
let saved = project.documents.autosave(doc)?;
remember_saved_encodings(&project);
Ok(saved)
})
.await?;
if saved {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
}
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
#[command(trust = always)]
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
let project = host.project(window)?;
host.blocking(move || project.documents.save_all()).await?;
host.blocking(move || {
let saved = project.documents.save_all();
remember_saved_encodings(&project);
saved
})
.await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
+50 -4
Переглянути файл
@@ -1,11 +1,13 @@
use crate::Host;
use crate::ops::blocking;
use crate::project::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
use std::path::PathBuf;
use ide_workspace::settings::SettingsScope;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
use std::path::{Path, PathBuf};
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
/// editor buffer, so syntax features and language-server requests work in it.
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
}
/// Keeps the encoding the user chose for a project file in the project's File Encodings
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
/// until then its file is still in the old encoding. Nothing is kept for a document without
/// a file in the project.
#[command(trust = always)]
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
let info = project.documents.snapshot(doc)?;
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
return Ok(());
}
remember_encoding(&project, &info.path, &info.encoding)
})
.await
}
/// Keeps the encodings of the converted documents a save has just written.
pub(super) fn remember_saved_encodings(project: &Project) {
for (path, encoding) in project.documents.take_saved_encodings() {
if let Err(e) = remember_encoding(project, &path, &encoding) {
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
}
}
}
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
const MAPPINGS: &str = "editor.encodings.mappings";
if project.light {
return Ok(());
}
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
return Ok(());
};
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
return Ok(());
}
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
Ok(())
}
#[command(trust = always)]
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
@@ -118,7 +163,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
}
items
}
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
None => syntax(),
})
})
@@ -263,6 +308,7 @@ ide_command::domain!(
doc_outline,
doc_python_facts,
doc_rearrange,
doc_remember_encoding,
doc_selection_ranges,
doc_set_bom,
doc_set_encoding,
+95
Переглянути файл
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
}
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
impl Fixture {
fn project_settings(&self) -> PathBuf {
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
}
fn mappings_changed(&self) -> usize {
let events = self.events.lock();
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::write(&f.path, "ação\n").unwrap();
let doc = f.open(&f.path).await;
assert_eq!(doc.encoding, "utf-8");
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
assert!(!settings.exists());
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
let written = std::fs::read_to_string(&settings).unwrap();
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
assert_eq!(f.mappings_changed(), 1);
// The same choice again leaves the file alone.
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
assert_eq!(f.mappings_changed(), 1);
doc_close(&f.host, "main", doc.id).await.unwrap();
let reopened = f.open(&f.path).await;
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
// A file outside the project has no place in the project's settings.
let outside = f.open(&f.outside).await;
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::write(&f.path, "ação\n").unwrap();
let doc = f.open(&f.path).await;
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
assert!(!settings.exists());
doc_close(&f.host, "main", doc.id).await.unwrap();
let reopened = f.open(&f.path).await;
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
doc_save(&f.host, "main", reopened.id).await.unwrap();
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
assert_eq!(
std::fs::read_to_string(&settings).unwrap(),
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
);
assert_eq!(f.mappings_changed(), 1);
// Later saves keep nothing more.
doc_save(&f.host, "main", reopened.id).await.unwrap();
assert_eq!(f.mappings_changed(), 1);
doc_close(&f.host, "main", reopened.id).await.unwrap();
let again = f.open(&f.path).await;
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
std::fs::write(&settings, "[editor\n").unwrap();
let doc = f.open(&f.path).await;
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
assert_eq!(f.mappings_changed(), 0);
}
+267 -5
Переглянути файл
@@ -1,9 +1,14 @@
//! Docker run configurations: the environment their `docker` command line runs with; and Docker
//! connections through an SSH configuration, tunnelled with the IDE's own SSH client.
//! Services tool window › Docker (`ide-docker`) and Docker run configurations: run on the
//! project host (`Host` locally, `openidea-server` in a remote window), with SSH connections
//! tunnelled through the host's own SSH client.
use super::Channel;
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
use ide_docker::DockerEndpoint;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
use ide_docker::{
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
};
use ide_ssh::Tunnel;
use std::collections::{BTreeMap, HashMap};
@@ -54,6 +59,242 @@ pub async fn disconnect(host: &Host, endpoint: &DockerEndpoint) {
host.ssh.release(id);
}
/// Runs a cancellable docker command (`request` → `cancel_request`) off the async workers.
async fn cancellable<T: Send + 'static>(
host: &Host,
request: RequestId,
f: impl FnOnce(&CancellationToken) -> IdeResult<T> + Send + 'static,
) -> IdeResult<T> {
let cancel = host.begin_request(request);
let result = host.blocking(move || f(&cancel)).await;
host.end_request(request);
result
}
/// Closes the connection's SSH tunnel and, when nothing else uses it, its SSH connection
/// (Services › Disconnect); other endpoints keep nothing open.
#[command(trust = always)]
pub async fn docker_disconnect(host: &Host, endpoint: DockerEndpoint) -> IdeResult<()> {
disconnect(host, &endpoint).await;
Ok(())
}
/// Availability plus containers, images, volumes and networks.
#[command(trust = trusted)]
pub async fn docker_snapshot(host: &Host, endpoint: DockerEndpoint) -> IdeResult<DockerSnapshot> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || Ok(ide_docker::snapshot(&endpoint))).await
}
#[command(trust = trusted)]
pub async fn docker_container_op(
host: &Host,
endpoint: DockerEndpoint,
ids: Vec<String>,
op: ContainerOp,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
}
#[command(trust = trusted)]
pub async fn docker_remove(
host: &Host,
endpoint: DockerEndpoint,
object: DockerObject,
ids: Vec<String>,
force: bool,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::remove(&endpoint, object, &ids, force)).await
}
/// Pretty-printed `docker inspect` JSON.
#[command(trust = trusted)]
pub async fn docker_inspect(
host: &Host,
endpoint: DockerEndpoint,
object: DockerObject,
id: String,
) -> IdeResult<String> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::inspect(&endpoint, object, &id)).await
}
/// Layers of an image (`docker image history`).
#[command(trust = trusted)]
pub async fn docker_image_history(
host: &Host,
endpoint: DockerEndpoint,
id: String,
) -> IdeResult<Vec<DockerImageLayer>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::image_history(&endpoint, &id)).await
}
/// Processes running inside a container (`docker top`).
#[command(trust = trusted)]
pub async fn docker_container_top(host: &Host, endpoint: DockerEndpoint, id: String) -> IdeResult<DockerProcessList> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_top(&endpoint, &id)).await
}
/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`).
#[command(trust = trusted)]
pub async fn docker_container_stats(
host: &Host,
endpoint: DockerEndpoint,
id: String,
) -> IdeResult<DockerContainerStats> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await
}
/// Disk usage per volume name (`docker system df -v`).
#[command(trust = trusted)]
pub async fn docker_volume_sizes(host: &Host, endpoint: DockerEndpoint) -> IdeResult<BTreeMap<String, String>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::volume_sizes(&endpoint)).await
}
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
#[command(trust = trusted)]
#[allow(clippy::too_many_arguments)]
pub async fn docker_logs(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
id: String,
tail: u32,
follow: bool,
timestamps: bool,
on_lines: Channel<Vec<DockerLogLine>>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| {
let _ = on_lines.send(lines);
})
})
.await
}
/// Follows `docker events` until the daemon goes away or the request is cancelled.
#[command(trust = trusted)]
pub async fn docker_events(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
on_event: Channel<DockerEvent>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::watch_events(&endpoint, cancel, &|e| {
let _ = on_event.send(e);
})
})
.await
}
/// `docker pull`, logging in first when a saved registry with a password serves the image.
#[command(trust = trusted)]
pub async fn docker_pull(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
reference: String,
on_output: Channel<String>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
let data_dir = host.data_dir.clone();
cancellable(host, request, move |cancel| {
let auth = ide_docker::auth_for(&data_dir, &reference);
ide_docker::pull(&endpoint, &reference, auth.as_ref(), cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
}
#[command(trust = trusted)]
pub async fn docker_prune(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
target: PruneTarget,
on_output: Channel<String>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::prune(&endpoint, target, cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
}
/// `docker compose` start / stop / restart / down of a project found through labels.
#[command(trust = trusted)]
#[allow(clippy::too_many_arguments)]
pub async fn docker_compose_op(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
project: String,
files: Vec<String>,
working_dir: Option<String>,
op: ComposeOp,
on_output: Channel<String>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::compose_op(&endpoint, &project, &files, working_dir.as_deref(), op, cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
}
/// Docker connections and registries of the project host.
#[command(trust = always)]
pub async fn docker_settings(host: &Host) -> IdeResult<DockerSettings> {
let data_dir = host.data_dir.clone();
host.blocking(move || Ok(ide_docker::load_settings(&data_dir))).await
}
#[command(trust = always)]
pub async fn docker_save_settings(host: &Host, settings: DockerSettings) -> IdeResult<()> {
let data_dir = host.data_dir.clone();
host.blocking(move || ide_docker::save_settings(&data_dir, &settings)).await
}
/// Saves (`None`: forgets) a registry's password.
#[command(trust = always)]
pub async fn docker_set_registry_password(host: &Host, id: String, password: Option<String>) -> IdeResult<()> {
let data_dir = host.data_dir.clone();
host.blocking(move || ide_docker::set_registry_password(&data_dir, &id, password.as_deref())).await
}
/// Test login to `registry` (`password`, else the saved one) through `endpoint`'s daemon.
#[command(trust = trusted)]
pub async fn docker_registry_login(
host: &Host,
endpoint: DockerEndpoint,
registry: DockerRegistry,
password: Option<String>,
) -> IdeResult<String> {
let endpoint = resolve(host, endpoint).await?;
let data_dir = host.data_dir.clone();
host.blocking(move || {
let password = password
.or_else(|| ide_docker::registry_password(&data_dir, &registry.id))
.ok_or_else(|| IdeError::invalid("enter the registry password"))?;
let auth = RegistryAuth { address: registry.address, username: registry.username, password };
ide_docker::login(&endpoint, &auth)
})
.await
}
/// Environment for a Docker run configuration's command line: selects `endpoint`'s
/// daemon and puts the docker executable on `PATH`.
#[command(trust = always)]
@@ -64,4 +305,25 @@ pub async fn docker_run_env(host: &Host, endpoint: DockerEndpoint) -> IdeResult<
host.blocking(move || Ok(ide_docker::run_env(&endpoint))).await
}
ide_command::domain!(docker: docker_run_env);
ide_command::domain!(
docker:
docker_compose_op,
docker_container_op,
docker_container_stats,
docker_container_top,
docker_disconnect,
docker_events,
docker_image_history,
docker_inspect,
docker_logs,
docker_prune,
docker_pull,
docker_registry_login,
docker_remove,
docker_run_env,
docker_save_settings,
docker_set_registry_password,
docker_settings,
docker_snapshot,
docker_volume_sizes,
);
+264
Переглянути файл
@@ -0,0 +1,264 @@
//! Host resource metrics (`host_metrics`, `host_end_process`) for the Remote Host
//! Resources status bar widget and popover dashboard.
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
use ide_workspace::system::SystemSampler;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
#[derive(Default)]
pub(crate) struct HostMetricsSampler {
system: SystemSampler,
cpu: CpuSampler,
}
/// One process outside OpenIDEA's own process tree on the host (read-only in the UI).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostProcess {
pub pid: u32,
pub name: String,
pub cpu_percent: Option<f32>,
pub memory_bytes: Option<u64>,
}
/// Snapshot of host-wide CPU, memory, network, disk and process usage.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostMetrics {
/// Overall CPU utilization across all logical cores (`0..=100`); `null` on the first sample.
pub cpu_percent: Option<f32>,
/// Logical CPU cores available to this host or container.
pub cpu_cores: u32,
/// Unix 1m, 5m, 15m load averages; `null` on Windows.
pub load_average: Option<[f32; 3]>,
/// Host or container memory in use, in bytes.
pub memory_used_bytes: Option<u64>,
/// Total physical (or container limit) memory, in bytes.
pub memory_total_bytes: Option<u64>,
/// Bytes/s received across non-loopback network interfaces; `null` on the first sample or unsupported OS.
pub net_rx_bytes_per_sec: Option<f64>,
/// Bytes/s sent across non-loopback network interfaces; `null` on the first sample or unsupported OS.
pub net_tx_bytes_per_sec: Option<f64>,
/// Bytes/s read from block storage; `null` on the first sample or unsupported OS.
pub disk_read_bytes_per_sec: Option<f64>,
/// Bytes/s written to block storage; `null` on the first sample or unsupported OS.
pub disk_write_bytes_per_sec: Option<f64>,
/// Free bytes available to the user on the project volume (or `$HOME` fallback).
pub disk_available_bytes: Option<u64>,
/// Total capacity in bytes of the project volume (or `$HOME` fallback).
pub disk_total_bytes: Option<u64>,
/// Uptime of the backend process in milliseconds.
pub uptime_ms: f64,
/// OpenIDEA backend, language servers, runs, terminals, debug adapters and agents (`includeProcesses = true`).
pub processes: Vec<ProcessMemory>,
/// Highest-usage processes on the host outside OpenIDEA's own process tree (`includeProcesses = true`).
pub external_processes: Vec<HostProcess>,
}
const MAX_EXTERNAL_PROCESSES: usize = 5;
const MIN_EXTERNAL_CPU_PERCENT: f32 = 0.5;
const MIN_EXTERNAL_MEMORY_BYTES: u64 = 32 << 20;
fn project_name(root: &Path) -> String {
root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string())
}
fn process_root(pid: u32, label: String, kind: &str) -> MemoryRoot {
MemoryRoot { pid, category: MemoryCategory::Process, label, detail: Some(kind.into()), with_children: true }
}
fn volume_path(host: &Host, window: &str) -> PathBuf {
if let Ok(p) = host.project(window) {
return p.root.clone();
}
if let Some(p) = host.projects().into_iter().next() {
return p.root.clone();
}
dirs::home_dir().unwrap_or_else(|| host.data_dir.clone())
}
fn disk_space(path: &Path) -> Option<(u64, u64)> {
#[cfg(unix)]
#[allow(clippy::unnecessary_cast)]
{
let stat = rustix::fs::statvfs(path).ok()?;
let frsize = stat.f_frsize as u64;
let total = (stat.f_blocks as u64).saturating_mul(frsize);
let avail = (stat.f_bavail as u64).saturating_mul(frsize);
(total > 0).then_some((avail.min(total), total))
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64);
// SAFETY: `wide` is NUL-terminated and all three u64 out-pointers are writable.
let ok = unsafe {
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
wide.as_ptr(),
&mut avail,
&mut total,
&mut free,
)
};
(ok != 0 && total > 0).then_some((avail.min(total), total))
}
#[cfg(not(any(unix, windows)))]
{
let _ = path;
None
}
}
fn collect_roots(host: &Host) -> Vec<MemoryRoot> {
let mut roots = Vec::new();
for p in host.projects() {
for s in p.lsp.servers() {
if let Some(pid) = s.pid {
roots.push(MemoryRoot {
pid,
category: MemoryCategory::LanguageServer,
label: s.name,
detail: Some(project_name(s.root.as_ref())),
with_children: true,
});
}
}
}
for r in host.processes.list().into_iter().filter(|r| r.running) {
if let Some(pid) = r.pid {
roots.push(process_root(pid, r.name, "Run"));
}
}
for t in host.terminals.list() {
if let Some(pid) = t.pid {
roots.push(process_root(pid, t.title, "Terminal"));
}
}
roots
}
fn resource_share(p: &HostProcess, cores: u32, total_memory: Option<u64>) -> f64 {
let cpu_share = p.cpu_percent.map(|c| c as f64 / (cores.max(1) as f64 * 100.0)).unwrap_or(0.0);
let mem_share = match (p.memory_bytes, total_memory.filter(|&t| t > 0)) {
(Some(b), Some(t)) => b as f64 / t as f64,
_ => 0.0,
};
cpu_share.max(mem_share)
}
/// Snapshot of host-wide resource counters (CPU, memory, network, disk) and, when
/// `include_processes` is true, the process breakdown of OpenIDEA and top host processes.
#[command(trust = always)]
pub async fn host_metrics(host: &Arc<Host>, window: &str, include_processes: bool) -> IdeResult<HostMetrics> {
let disk_target = volume_path(host, window);
let roots = if include_processes { collect_roots(host) } else { Vec::new() };
let h = host.clone();
host.blocking(move || {
let table = include_processes.then(ProcessTable::snapshot);
let (disk_available_bytes, disk_total_bytes) = match disk_space(&disk_target) {
Some((a, t)) => (Some(a), Some(t)),
None => (None, None),
};
let uptime_ms =
ide_workspace::process::process_age().unwrap_or_else(ide_workspace::process::uptime).as_secs_f64() * 1000.0;
let mut sampler = h.metrics_sampler.lock();
let rates = sampler.system.sample();
let (processes, external_processes) = if let Some(table) = table {
sampler.cpu.retain(&table);
let me = std::process::id();
let processes =
memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| sampler.cpu.percent(pid));
let claimed: HashSet<u32> = table.tree(me).into_iter().collect();
let mut external: Vec<HostProcess> = table
.entries()
.filter(|e| e.pid != 0 && !claimed.contains(&e.pid))
.filter_map(|e| {
let cpu_percent = sampler.cpu.percent(e.pid);
let memory_bytes = memory::fast_resident_bytes(e.pid);
let active = cpu_percent.unwrap_or(0.0) >= MIN_EXTERNAL_CPU_PERCENT
|| memory_bytes.unwrap_or(0) >= MIN_EXTERNAL_MEMORY_BYTES;
active.then(|| HostProcess { pid: e.pid, name: e.name.clone(), cpu_percent, memory_bytes })
})
.collect();
external.sort_by(|a, b| {
resource_share(b, rates.cpu_cores, rates.memory_total_bytes)
.total_cmp(&resource_share(a, rates.cpu_cores, rates.memory_total_bytes))
.then_with(|| b.memory_bytes.unwrap_or(0).cmp(&a.memory_bytes.unwrap_or(0)))
.then_with(|| a.pid.cmp(&b.pid))
});
external.truncate(MAX_EXTERNAL_PROCESSES);
(processes, external)
} else {
(Vec::new(), Vec::new())
};
Ok(HostMetrics {
cpu_percent: rates.cpu_percent,
cpu_cores: rates.cpu_cores,
load_average: rates.load_average,
memory_used_bytes: rates.memory_used_bytes,
memory_total_bytes: rates.memory_total_bytes,
net_rx_bytes_per_sec: rates.net_rx_bytes_per_sec,
net_tx_bytes_per_sec: rates.net_tx_bytes_per_sec,
disk_read_bytes_per_sec: rates.disk_read_bytes_per_sec,
disk_write_bytes_per_sec: rates.disk_write_bytes_per_sec,
disk_available_bytes,
disk_total_bytes,
uptime_ms,
processes,
external_processes,
})
})
.await
}
/// Ends a child process started by this OpenIDEA host (language server, run, terminal,
/// debug adapter or agent) and its descendants; refuses processes outside this host's tree.
#[command(trust = trusted)]
pub async fn host_end_process(host: &Arc<Host>, pid: u32) -> IdeResult<bool> {
host.blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, Duration::from_secs(3)))).await
}
ide_command::domain!(host_metrics: host_metrics, host_end_process);
#[cfg(test)]
mod tests {
use super::*;
use crate::HostConfig;
#[tokio::test]
async fn collects_light_and_detailed_host_metrics() {
let dir = tempfile::tempdir().unwrap();
let host = Arc::new(Host::new(HostConfig::for_test(dir.path())));
let light = host_metrics(&host, "main", false).await.unwrap();
assert!(light.cpu_cores >= 1);
assert!(light.processes.is_empty());
assert!(light.external_processes.is_empty());
if cfg!(any(unix, windows)) {
let avail = light.disk_available_bytes.expect("disk_available_bytes");
let total = light.disk_total_bytes.expect("disk_total_bytes");
assert!(total > 0 && avail <= total, "{avail} / {total}");
}
let detailed = host_metrics(&host, "main", true).await.unwrap();
assert!(!detailed.processes.is_empty());
assert_eq!(detailed.processes[0].label, "Backend");
assert!(detailed.external_processes.len() <= MAX_EXTERNAL_PROCESSES);
// Refuses to terminate the backend itself or PID 1.
assert!(!host_end_process(&host, std::process::id()).await.unwrap());
assert!(!host_end_process(&host, 1).await.unwrap());
}
}
+24
Переглянути файл
@@ -1881,6 +1881,29 @@ pub async fn lsp_snapshot_diagnostics(
result
}
#[command(trust = trusted)]
pub async fn lsp_snapshot_completion(
host: &Host,
window: &str,
path: std::path::PathBuf,
text: String,
pos: Pos,
request: RequestId,
) -> IdeResult<Vec<CompletionItem>> {
let project = host.project(window)?;
if !path.is_absolute() || path.file_name().is_none() {
return Err(IdeError::invalid("a text snapshot requires a file path"));
}
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
return Ok(Vec::new());
}
let language = project.documents.language_of(&path, text.lines().next()).language;
let cancel = host.begin_project_read_request(window, request);
let result = project.lsp.snapshot_completion(&path, &language, &text, pos, &cancel).await;
host.end_request(request);
result
}
#[command(trust = trusted)]
pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
let lsp = host.project(window)?.lsp.clone();
@@ -3236,6 +3259,7 @@ ide_command::domain!(
lsp_extract_interface_info,
lsp_format,
lsp_format_text,
lsp_snapshot_completion,
lsp_snapshot_diagnostics,
lsp_source_action_text,
lsp_goto,
+4
Переглянути файл
@@ -19,6 +19,7 @@ pub mod flutter;
pub mod fs;
pub mod heap;
pub mod history;
pub mod host_metrics;
pub mod http;
pub mod java;
pub mod jvm_icons;
@@ -26,7 +27,9 @@ pub mod lsp;
pub mod maven_placeholder;
pub mod nav;
pub mod notebook;
mod plots;
pub mod project;
pub mod pytest_fixtures;
mod python;
pub mod python_stubs;
pub mod refactor;
@@ -93,6 +96,7 @@ ide_command::domains!(
fs: crate::ops::fs,
heap: crate::ops::heap,
history: crate::ops::history,
host_metrics: crate::ops::host_metrics,
http: crate::ops::http,
java: crate::ops::java,
jvm_icons: crate::ops::jvm_icons,
+77 -1
Переглянути файл
@@ -1,11 +1,12 @@
use super::blocking;
use super::pytest_fixtures::{PytestFixtureAt, PytestFixtureUsages, fixture_at, fixture_usages, rename_fixture};
use super::python_stubs::{
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
};
use crate::Host;
use crate::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId, WorkspaceEdit};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
@@ -478,6 +479,78 @@ pub async fn nav_python_stubs(host: &Host, window: &str, doc: DocId) -> IdeResul
.await
}
/// pytest fixtures at `pos` of a Python document: the definition pytest uses for the fixture
/// named there (a test's parameter, a `usefixtures` / `getfixturevalue` string), and the
/// fixtures visible where a fixture name goes, for completion.
#[command(trust = always)]
pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<PytestFixtureAt> {
let project = host.project(window)?;
let syntax = host.syntax();
blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.large || snap.language.as_str() != "python" {
return Ok(Default::default());
}
Ok(fixture_at(&project, &syntax, &snap.path, &snap.text, pos))
})
.await
}
/// Find Usages of the pytest fixture at `pos` (its definition, or a place asking for it): every
/// test and fixture parameter, `usefixtures` and `getfixturevalue` string that gets it.
/// None when `pos` names no fixture. Cancellable.
#[command(trust = always)]
pub async fn nav_pytest_fixture_usages(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
request: RequestId,
) -> IdeResult<Option<PytestFixtureUsages>> {
let project = host.project(window)?;
let syntax = host.syntax();
let token = host.begin_request(request);
let result = blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.large || snap.language.as_str() != "python" {
return Ok(None);
}
fixture_usages(&project, &syntax, &snap.path, &snap.text, pos, &|| token.is_cancelled())
})
.await;
host.end_request(request);
result
}
/// Rename of the pytest fixture at `pos`: its definition, every place that gets it and the
/// uses of those parameters in their functions. Cancellable.
#[command(trust = always)]
pub async fn nav_pytest_fixture_rename(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
new_name: String,
request: RequestId,
) -> IdeResult<WorkspaceEdit> {
let project = host.project(window)?;
let syntax = host.syntax();
let token = host.begin_request(request);
let result = blocking(move || {
let snap = project.documents.snapshot(doc)?;
let mut edit =
rename_fixture(&project, &syntax, &snap.path, &snap.text, pos, &new_name, &|| token.is_cancelled())?;
if token.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
project.documents.prepare_workspace_edit(&mut edit)?;
Ok(edit)
})
.await;
host.end_request(request);
result
}
ide_command::domain!(
nav:
find_dirs,
@@ -491,6 +564,9 @@ ide_command::domain!(
mark_recent,
nav_index_definitions,
nav_inheritance,
nav_pytest_fixture_rename,
nav_pytest_fixture_usages,
nav_pytest_fixtures,
nav_python_stubs,
nav_resolve_module,
path_completions,
+13
Переглянути файл
@@ -93,6 +93,18 @@ pub async fn notebook_interrupt(host: &Host, window: &str, id: String) -> IdeRes
.map_err(|error| IdeError::internal(error.to_string()))?
}
#[command(trust = trusted)]
pub async fn notebook_variables(
host: &Host,
window: &str,
id: String,
) -> IdeResult<Option<Vec<crate::notebook::NotebookVariable>>> {
let notebooks = host.project(window)?.notebooks.clone();
tokio::spawn(async move { notebooks.variables(&id).await })
.await
.map_err(|error| IdeError::internal(error.to_string()))?
}
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn notebook_execute(
@@ -162,4 +174,5 @@ ide_command::domain!(
notebook_restart,
notebook_save,
notebook_undo,
notebook_variables,
);
+66
Переглянути файл
@@ -0,0 +1,66 @@
//! The Plots tool window: matplotlib figures that Python runs and debug sessions save (see
//! [`ide_run::plots`]) reach the window as [`IdeEvent::PlotAdded`].
use crate::Host;
use crate::project::Project;
use ide_core::IdeEvent;
use ide_run::plots::Plots;
use notify::{RecursiveMode, Watcher};
use std::io;
use std::path::Path;
/// The backend and plots folder for a Python run of `project`, installed and watched on first use;
/// `None` when Settings › Python turns the tool window off.
pub(crate) fn prepare(host: &Host, project: &Project) -> Option<Plots> {
if !project.settings.effective().languages.python.show_plots_in_tool_window {
return None;
}
let plots = Plots { backend: host.local_data_dir.join("matplotlib-backend"), dir: project.cache_dir.join("plots") };
match ide_run::plots::install(&plots.backend).and_then(|()| watch(project, &plots.dir)) {
Ok(()) => Some(plots),
Err(e) => {
tracing::warn!("cannot set up the Plots tool window in {}: {e}", plots.dir.display());
None
}
}
}
fn watch(project: &Project, dir: &Path) -> io::Result<()> {
let mut slot = project.plots_watch.lock();
if slot.is_some() {
return Ok(());
}
// Figures of an earlier session are not shown again.
let _ = std::fs::remove_dir_all(dir);
std::fs::create_dir_all(dir)?;
let sink = project.sink.clone();
// Every event of a finished PNG is sent (create, rename, modify); the window keeps each path once.
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
for path in res.map(|e| e.paths).unwrap_or_default() {
if is_plot(&path) && path.is_file() {
sink.emit(IdeEvent::PlotAdded { path: path.to_string_lossy().into_owned() });
}
}
})
.map_err(io::Error::other)?;
watcher.watch(dir, RecursiveMode::NonRecursive).map_err(io::Error::other)?;
*slot = Some(watcher);
Ok(())
}
/// A finished figure: the backend writes `.<name>.png` first, then renames it.
fn is_plot(path: &Path) -> bool {
path.extension().is_some_and(|e| e == "png")
&& path.file_name().is_some_and(|n| !n.to_string_lossy().starts_with('.'))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_finished_pngs_are_plots() {
assert!(is_plot(Path::new("/c/plots/1-2-0.png")));
assert!(!is_plot(Path::new("/c/plots/.1-2-0.png")));
assert!(!is_plot(Path::new("/c/plots/notes.txt")));
}
}
+70 -11
Переглянути файл
@@ -110,6 +110,22 @@ pub fn settings_removed_theme(host: &Host, window: &str) -> Option<String> {
}
}
/// What a changed setting `key` starts or stops right away. Both `settings_set` commands (this
/// crate's and the desktop's) call it after writing the value.
pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
if key == "terminal" || key.starts_with("terminal.") {
super::term::apply_output_rate(host, window);
}
if "languages.typescript.watchProblems".starts_with(key)
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
{
watch.apply(&host.runtime);
}
}
/// `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.
@@ -122,17 +138,7 @@ pub fn settings_set(
value: String,
) -> IdeResult<Settings> {
let applied = set_settings(host, window, scope, &key, &value)?;
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
if key == "terminal" || key.starts_with("terminal.") {
super::term::apply_output_rate(host, window);
}
if "languages.typescript.watchProblems".starts_with(&key)
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
{
watch.apply(&host.runtime);
}
apply_setting(host, window, &key);
let sink = host.window_sink(window);
sink.emit(IdeEvent::SettingsChanged { key });
if let Some(root) = applied.roots_changed {
@@ -448,6 +454,14 @@ pub fn set_settings(
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
host.apply_git_executable();
}
if key == "vcs" || key == "vcs.github" || key.starts_with("vcs.github.") {
let affected = affected();
host.runtime.spawn_blocking(move || {
for project in affected {
crate::github_auth::apply_to_project(&project);
}
});
}
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
for project in affected() {
@@ -524,11 +538,56 @@ pub fn set_settings(
Ok(SettingsApplied { settings: host.with_proxy_password(settings), project_scope, roots_changed })
}
/// Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project.
#[command(trust = outside_restricted)]
pub async fn gh_project_account_status(
host: &Arc<Host>,
window: &str,
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
host.require_trust_if_project(window)?;
let current = host.project(window).ok().filter(|p| !p.light);
let global_account = host.global_settings.effective().vcs.github.account;
host.blocking(move || match current {
Some(project) => Ok(crate::github_auth::project_status(&project)),
None => Ok(crate::github_auth::global_status(global_account)),
})
.await
}
/// Sets `vcs.github.account` for `window`'s project (or globally when no project is open),
/// updates the project's `GH_TOKEN` environment immediately, and returns the updated status.
#[command(trust = outside_restricted)]
pub async fn gh_set_project_account(
host: &Arc<Host>,
window: &str,
account: String,
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
host.require_trust_if_project(window)?;
let trimmed = account.trim().to_owned();
if !trimmed.is_empty() && !crate::github_auth::is_valid_github_login(&trimmed) {
return Err(ide_core::IdeError::invalid(format!("invalid GitHub account login: {trimmed}")));
}
let current = host.project(window).ok().filter(|p| !p.light);
let scope = if current.is_some() { SettingsScope::Project } else { SettingsScope::Global };
let json = serde_json::to_string(&trimmed).map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
set_settings(host, window, scope, "vcs.github.account", &json)?;
let sink = host.window_sink(window);
sink.emit(IdeEvent::SettingsChanged { key: "vcs.github.account".into() });
let global_account = host.global_settings.effective().vcs.github.account;
host.blocking(move || match current {
Some(project) => Ok(crate::github_auth::project_status(&project)),
None => Ok(crate::github_auth::global_status(global_account)),
})
.await
}
ide_command::domain!(
project:
cancel_request,
cancel_task,
close_project,
gh_project_account_status,
gh_set_project_account,
open_project,
project_current,
project_roots,
+464
Переглянути файл
@@ -0,0 +1,464 @@
//! pytest fixtures across files: the modules a test file sees, nearest first (the file, its
//! `conftest.py` files up to the project root, the modules `pytest_plugins` names, installed
//! plugins' `pytest11` entry points, pytest's own `_pytest` package), for Go to Declaration
//! and completion of fixture names.
use super::python_stubs::site_packages;
use crate::Project;
use ide_core::{FileEdit, IdeError, IdeResult, IpcPath, LanguageId, Location, Pos, Range, TextEdit, WorkspaceEdit};
use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::SystemTime;
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PytestFixtureAt {
/// The fixture name at the position, and the definition pytest uses for it.
pub reference: Option<PytestFixtureReference>,
/// At a place a fixture name goes (a test's parameters, a `usefixtures` string): the
/// fixtures visible there, nearest first.
pub completions: Option<Vec<PytestFixtureItem>>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PytestFixtureReference {
pub name: String,
pub range: Range,
/// None when no visible module defines it (`request`, a fixture from a hook).
pub definition: Option<Location>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PytestFixtureItem {
pub name: String,
/// The file defining it.
pub path: IpcPath,
}
/// Fixtures at `pos` of the Python document `path` / `text`.
pub(crate) fn fixture_at(project: &Project, syntax: &Syntax, path: &Path, text: &str, pos: Pos) -> PytestFixtureAt {
let own = syntax.pytest_module(&python(), text);
let usage = own.use_at(pos).cloned();
let slot = own.slot_at(pos).cloned();
if usage.is_none() && slot.is_none() {
return PytestFixtureAt::default();
}
let layers = Scope::new(project).layers(project, syntax, path, Arc::new(own));
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
let reference = usage.map(|u| {
let found = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name));
PytestFixtureReference {
definition: found.map(|(l, f)| Location {
path: IpcPath::from(layers[l].0.clone()),
range: modules[l].fixtures[f].selection,
uri: None,
}),
name: u.name,
range: u.range,
}
});
let completions = slot.map(|s| {
visible_fixtures(&modules, s.class.as_deref())
.into_iter()
// `_name` fixtures are internal, as `pytest --fixtures` hides them.
.filter(|&(l, f)| !modules[l].fixtures[f].name.starts_with('_'))
.map(|(l, f)| PytestFixtureItem {
name: modules[l].fixtures[f].name.clone(),
path: IpcPath::from(layers[l].0.clone()),
})
.collect()
});
PytestFixtureAt { reference, completions }
}
fn python() -> LanguageId {
LanguageId::new("python")
}
type Layer = (PathBuf, Arc<PytestModule>);
/// What every file of the project sees after its own `conftest.py` files: the folders
/// `pytest_plugins` modules are found in, installed plugins and pytest's own modules.
struct Scope {
search: Vec<PathBuf>,
tail: Vec<PathBuf>,
}
impl Scope {
fn new(project: &Project) -> Self {
let packages = interpreter_site_packages(project);
let mut search = super::python::paths(project);
search.extend(packages.iter().cloned());
// `pytest_plugins = ["pytester"]` names pytest's own optional plugins by their short name.
search.extend(packages.iter().map(|p| p.join("_pytest")));
let mut tail = Vec::new();
for packages in &packages {
tail.extend(
entry_point_modules(packages).iter().filter_map(|m| module_file(m, std::slice::from_ref(packages))),
);
}
for packages in &packages {
tail.extend(builtin_modules(&packages.join("_pytest")));
}
Self { search, tail }
}
/// The modules `path` sees, nearest first, `own` being its own: its `conftest.py` files up to
/// the project root, the modules their `pytest_plugins` name, then installed plugins and pytest.
fn layers(&self, project: &Project, syntax: &Syntax, path: &Path, own: Arc<PytestModule>) -> Vec<Layer> {
let mut out: Vec<Layer> = vec![(path.to_path_buf(), own)];
let mut dir = path.parent();
while let Some(d) = dir.filter(|d| d.starts_with(&project.root)) {
let conftest = d.join("conftest.py");
if conftest != path
&& let Some(m) = module_of(project, syntax, &conftest)
{
out.push((conftest, m));
}
dir = d.parent();
}
let named: Vec<String> = out.iter().flat_map(|(_, m)| m.plugins.clone()).collect();
let extra =
named.iter().filter_map(|module| module_file(module, &self.search)).chain(self.tail.iter().cloned());
for file in extra.collect::<Vec<_>>() {
if !out.iter().any(|(p, _)| *p == file)
&& let Some(m) = module_of(project, syntax, &file)
{
out.push((file, m));
}
}
out
}
}
/// A fixture definition: its file and the range of its name there.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Definition {
name: String,
path: PathBuf,
selection: Range,
}
/// Where pytest finds the fixture `u` asks for, seen from `layers`.
fn definition_of(layers: &[Layer], u: &ide_language::PytestFixtureUse) -> Option<Definition> {
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
let (l, f) = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name))?;
Some(Definition { name: u.name.clone(), path: layers[l].0.clone(), selection: modules[l].fixtures[f].selection })
}
/// The fixture at `pos` of `path`: the one defined there, or the one a test asks for there.
fn target_at(
project: &Project,
syntax: &Syntax,
scope: &Scope,
path: &Path,
own: &Arc<PytestModule>,
pos: Pos,
) -> Option<Definition> {
if let Some(f) = own.definition_at(pos) {
let fixture = &own.fixtures[f];
return Some(Definition { name: fixture.name.clone(), path: path.to_path_buf(), selection: fixture.selection });
}
let usage = own.use_at(pos)?;
definition_of(&scope.layers(project, syntax, path, own.clone()), usage)
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PytestFixtureUsages {
pub name: String,
pub definition: Location,
/// Defined in the project (not by a plugin or pytest): it may be renamed.
pub in_project: bool,
/// Every place that gets this fixture: parameters, `usefixtures` and `getfixturevalue` strings.
pub usages: Vec<Location>,
}
struct Usage {
path: PathBuf,
use_: ide_language::PytestFixtureUse,
}
/// The fixture at `pos` of the Python document `path` / `text` and every place that gets it.
pub(crate) fn fixture_usages(
project: &Project,
syntax: &Syntax,
path: &Path,
text: &str,
pos: Pos,
cancelled: &dyn Fn() -> bool,
) -> IdeResult<Option<PytestFixtureUsages>> {
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else { return Ok(None) };
Ok(Some(PytestFixtureUsages {
name: target.name.clone(),
in_project: is_project_file(project, &target.path),
definition: Location { path: IpcPath::from(target.path), range: target.selection, uri: None },
usages: usages
.into_iter()
.map(|u| Location { path: IpcPath::from(u.path), range: u.use_.range, uri: None })
.collect(),
}))
}
/// Rename of the fixture at `pos`: its definition (the `name=` string, else the function name),
/// every place that gets it, and the uses of a renamed parameter in its function's body.
pub(crate) fn rename_fixture(
project: &Project,
syntax: &Syntax,
path: &Path,
text: &str,
pos: Pos,
new_name: &str,
cancelled: &dyn Fn() -> bool,
) -> IdeResult<WorkspaceEdit> {
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else {
return Err(IdeError::invalid("No pytest fixture here"));
};
if !is_project_file(project, &target.path) {
return Err(IdeError::invalid("The fixture is defined outside the project"));
}
let mut by_file: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
let mut edit = |file: &Path, range: Range| {
let edits = match by_file.iter_mut().find(|(p, _)| p == file) {
Some((_, edits)) => edits,
None => {
by_file.push((file.to_path_buf(), Vec::new()));
&mut by_file.last_mut().expect("just pushed").1
}
};
if !edits.iter().any(|e| e.range == range) {
edits.push(TextEdit { range, new_text: new_name.to_owned() });
}
};
edit(&target.path, target.selection);
for u in &usages {
edit(&u.path, u.use_.range);
for &r in &u.use_.body {
edit(&u.path, r);
}
}
let files = by_file
.into_iter()
.map(|(p, mut edits)| {
edits.sort_by_key(|e| e.range);
FileEdit::Edit { path: IpcPath::from(p), edits, version: None }
})
.collect();
Ok(WorkspaceEdit { files, preconditions: Vec::new() })
}
fn usages_of(
project: &Project,
syntax: &Syntax,
path: &Path,
text: &str,
pos: Pos,
cancelled: &dyn Fn() -> bool,
) -> IdeResult<Option<(Definition, Vec<Usage>)>> {
let own = Arc::new(syntax.pytest_module(&python(), text));
if own.definition_at(pos).is_none() && own.use_at(pos).is_none() {
return Ok(None);
}
let scope = Scope::new(project);
let Some(target) = target_at(project, syntax, &scope, path, &own, pos) else { return Ok(None) };
let mut files = candidate_files(project, &target.path);
if !files.iter().any(|f| f == path) && path.starts_with(&project.root) {
files.push(path.to_path_buf());
}
let mut usages = Vec::new();
for file in files {
if cancelled() {
return Err(IdeError::cancelled());
}
let module = if file == path { Some(own.clone()) } else { module_of(project, syntax, &file) };
let Some(module) = module else { continue };
if !module.uses.iter().any(|u| u.name == target.name) {
continue;
}
let layers = scope.layers(project, syntax, &file, module.clone());
for u in module.uses.iter().filter(|u| u.name == target.name) {
if definition_of(&layers, u).as_ref() == Some(&target) {
usages.push(Usage { path: file.clone(), use_: u.clone() });
}
}
}
Ok(Some((target, usages)))
}
/// The files that may get a fixture defined in `definition`: that test module alone, the test
/// modules and `conftest.py` files below a `conftest.py`, all of the project's for a plugin's.
fn candidate_files(project: &Project, definition: &Path) -> Vec<PathBuf> {
let in_project = is_project_file(project, definition);
let is_conftest = definition.file_name().is_some_and(|n| n == "conftest.py");
if in_project && !is_conftest {
return vec![definition.to_path_buf()];
}
let dir = if in_project { definition.parent().unwrap_or(&project.root) } else { &project.root };
let mut files = project.index.files_matching(dir, is_test_file, MAX_FILES).unwrap_or_default();
files.sort();
files
}
const MAX_FILES: usize = 20_000;
/// A file of the project's own code: below its root, not in an installed package (a
/// virtualenv inside the project holds pytest and its plugins).
fn is_project_file(project: &Project, path: &Path) -> bool {
path.starts_with(&project.root) && !path.components().any(|c| c.as_os_str() == "site-packages")
}
/// `test_*.py`, `*_test.py` and `conftest.py`: the files pytest collects or loads.
fn is_test_file(rel: &Path) -> bool {
let Some(name) = rel.file_name().and_then(|n| n.to_str()) else { return false };
let Some(stem) = name.strip_suffix(".py") else { return false };
stem == "conftest" || stem.starts_with("test_") || stem.ends_with("_test")
}
/// The `site-packages` of the project's interpreter: its virtualenv's, else its install prefix's.
fn interpreter_site_packages(project: &Project) -> Vec<PathBuf> {
let settings = project.settings.effective();
let Some(python) = ide_sdk::apply::python_interpreter(&project.root, &settings) else { return Vec::new() };
let prefix = ide_sdk::venv_of(&python).or_else(|| python.parent()?.parent().map(Path::to_path_buf));
prefix.map(|p| site_packages(&p)).unwrap_or_default()
}
/// `pkg.mod` → `pkg/mod.py` or `pkg/mod/__init__.py` in the first folder that has it.
fn module_file(module: &str, search: &[PathBuf]) -> Option<PathBuf> {
let rel: PathBuf = module.split('.').collect();
search.iter().find_map(|base| {
let file = base.join(&rel).with_extension("py");
let package = base.join(&rel).join("__init__.py");
[file, package].into_iter().find(|p| p.is_file())
})
}
/// The modules of the `[pytest11]` entry points of the distributions in `site_packages`.
fn entry_point_modules(site_packages: &Path) -> Vec<String> {
let Ok(entries) = std::fs::read_dir(site_packages) else { return Vec::new() };
let mut out = Vec::new();
for entry in entries.flatten() {
if !entry.file_name().to_string_lossy().ends_with(".dist-info") {
continue;
}
let Ok(text) = std::fs::read_to_string(entry.path().join("entry_points.txt")) else { continue };
out.extend(pytest11_modules(&text));
}
out.sort();
out
}
/// The modules of the `[pytest11]` section of an `entry_points.txt` (`name = module:attr`).
fn pytest11_modules(text: &str) -> Vec<String> {
let mut section = "";
let mut out = Vec::new();
for line in text.lines().map(str::trim) {
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
section = name;
} else if section == "pytest11"
&& let Some((_, value)) = line.split_once('=')
{
let module = value.trim().split(':').next().unwrap_or_default().trim();
if !module.is_empty() {
out.push(module.to_owned());
}
}
}
out
}
/// pytest's own plugins that are off unless `pytest_plugins` names them.
const OPTIONAL_BUILTINS: [&str; 2] = ["pytester.py", "pytester_assertions.py"];
/// pytest's own modules that may define fixtures: `_pytest/*.py`, one level of subpackages.
fn builtin_modules(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let Ok(entries) = std::fs::read_dir(dir) else { return out };
for entry in entries.flatten() {
let path = entry.path();
if OPTIONAL_BUILTINS.iter().any(|name| entry.file_name() == *name) {
continue;
}
if path.extension().is_some_and(|e| e == "py") {
out.push(path);
} else if path.is_dir() {
out.extend(
std::fs::read_dir(&path)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "py")),
);
}
}
out.sort();
out
}
/// A parsed file and the modification time and length it was read at.
type Cached = (SystemTime, u64, Arc<PytestModule>);
/// The fixtures of a file: from its open editor, else from disk, parsed once per modification.
fn module_of(project: &Project, syntax: &Syntax, path: &Path) -> Option<Arc<PytestModule>> {
if let Some(text) = project.documents.text_of(path) {
return Some(Arc::new(syntax.pytest_module(&python(), &text)));
}
static CACHE: LazyLock<Mutex<HashMap<PathBuf, Cached>>> = LazyLock::new(Default::default);
let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?;
if meta.len() > ide_vfs::LARGE_FILE_THRESHOLD {
return None;
}
let stamp = (meta.modified().ok()?, meta.len());
if let Some((time, len, m)) = CACHE.lock().ok()?.get(path)
&& (*time, *len) == stamp
{
return Some(m.clone());
}
let text = std::fs::read_to_string(path).ok()?;
let module = Arc::new(syntax.pytest_module(&python(), &ide_text::normalize_line_endings(&text)));
CACHE.lock().ok()?.insert(path.to_path_buf(), (stamp.0, stamp.1, module.clone()));
Some(module)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_files_are_the_ones_pytest_loads() {
for (rel, expected) in [
("tests/test_a.py", true),
("a_test.py", true),
("pkg/conftest.py", true),
("pkg/helpers.py", false),
("test_data.json", false),
] {
assert_eq!(is_test_file(Path::new(rel)), expected, "{rel}");
}
}
#[test]
fn reads_pytest11_entry_points() {
let text =
"[console_scripts]\nx = a:b\n\n[pytest11]\nmock = pytest_mock\nasyncio = pytest_asyncio.plugin:main\n";
assert_eq!(pytest11_modules(text), ["pytest_mock", "pytest_asyncio.plugin"]);
}
#[test]
fn finds_module_files_and_packages() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("pkg/sub")).unwrap();
std::fs::write(dir.path().join("pkg/fixtures.py"), "").unwrap();
std::fs::write(dir.path().join("pkg/sub/__init__.py"), "").unwrap();
let search = [dir.path().to_path_buf()];
assert_eq!(module_file("pkg.fixtures", &search), Some(dir.path().join("pkg/fixtures.py")));
assert_eq!(module_file("pkg.sub", &search), Some(dir.path().join("pkg/sub/__init__.py")));
assert_eq!(module_file("pkg.none", &search), None);
}
}
+24 -10
Переглянути файл
@@ -52,29 +52,43 @@ pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
extra.get("python")?.as_str().map(str::to_owned)
}
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> IdeResult<()> {
/// Adds the project's import paths, and the Plots tool window's backend (`plots`), to a debugpy
/// launch's environment.
pub(super) fn prepare_debug(
config: &mut LaunchConfig,
paths: &[PathBuf],
plots: Option<&ide_run::plots::Plots>,
) -> IdeResult<()> {
// Adapter-specific env takes precedence over the common launch fields in DAP.
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
// A custom adapter may run on another host; local paths are not portable.
if extra.as_ref().is_some_and(|e| e.get("debugServer").is_some()) {
return Ok(());
}
let plots = plots.filter(|_| !config.env.contains_key("MPLBACKEND"));
if let Some(env) = extra.as_mut().and_then(|e| e.get_mut("env")) {
if env.is_null() {
*env = serde_json::json!({});
}
if !env.is_object() {
let Some(object) = env.as_object_mut() else {
return Ok(());
};
let mut vars: BTreeMap<String, String> =
object.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned()))).collect();
let inherit = !vars.contains_key("PYTHONPATH");
ide_run::python_path::extend(&mut vars, paths, inherit)?;
if let Some(plots) = plots {
ide_run::plots::add(&mut vars, plots, true)?;
}
let mut vars = BTreeMap::new();
if let Some(value) = env.get("PYTHONPATH").and_then(|v| v.as_str()) {
vars.insert("PYTHONPATH".into(), value.to_owned());
for (key, value) in vars {
object.insert(key, serde_json::json!(value));
}
ide_run::python_path::extend(&mut vars, paths, env.get("PYTHONPATH").is_none())?;
env["PYTHONPATH"] = serde_json::json!(vars["PYTHONPATH"]);
config.extra_json = extra.map(|e| e.to_string());
} else {
ide_run::python_path::extend(&mut config.env, paths, true)?;
if let Some(plots) = plots {
ide_run::plots::add(&mut config.env, plots, true)?;
}
}
Ok(())
}
@@ -97,11 +111,11 @@ mod tests {
extra_json: Some(serde_json::json!({"env": null, "debugServer": "remote:5678"}).to_string()),
};
let before = config.extra_json.clone();
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
assert_eq!(config.extra_json, before);
assert!(config.env.is_empty());
config.extra_json = Some(serde_json::json!({"env": null}).to_string());
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
let paths = std::env::split_paths(value["env"]["PYTHONPATH"].as_str().unwrap()).collect::<Vec<_>>();
assert_eq!(paths[0], root);
@@ -123,7 +137,7 @@ mod tests {
env: vars.clone(),
extra_json: extra.then(|| serde_json::json!({"env": vars}).to_string()),
};
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
let vars: BTreeMap<String, String> = if extra {
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
serde_json::from_value(value["env"].clone()).unwrap()
+173 -57
Переглянути файл
@@ -6,8 +6,9 @@ use ide_command::command;
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
use ide_language::Syntax;
use ide_lsp::types::FileRenameEdits;
use ide_workspace::file_moves::moved_path;
use ide_workspace::roots::{ProjectRoots, RootKind};
use ide_workspace::Documents;
use ide_workspace::file_moves::{moved_path, read_text};
use ide_workspace::roots::{PYTHON_FILES, ProjectRoots, RootKind, SourceFolder};
use ide_workspace::{FileMove, UndoOutcome};
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
@@ -18,7 +19,8 @@ fn pairs(moves: &[FileMove]) -> Vec<(PathBuf, PathBuf)> {
moves.iter().map(|m| (m.from.to_path_buf(), m.to.to_path_buf())).collect()
}
/// `workspace/willRenameFiles` on every interested server (before the move). Cancellable.
/// `workspace/willRenameFiles` on every interested server (before the move), plus the
/// Python import updates the IDE makes itself. Cancellable.
#[command(trust = always)]
pub async fn refactor_file_move_edits(
host: &Host,
@@ -28,46 +30,72 @@ pub async fn refactor_file_move_edits(
) -> IdeResult<FileRenameEdits> {
let project = host.project(window)?;
let token = host.begin_request(request);
let result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await;
host.end_request(request);
let mut result = result?;
let syntax = host.syntax();
blocking(move || {
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
let python = python_import_edits(&project, &syntax, &moves, &|| token.is_cancelled());
result.edit.files.extend(python.files);
}
project.documents.prepare_workspace_edit(&mut result.edit)?;
Ok(result)
})
.await
let result = async {
let mut result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await?;
blocking(move || {
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
let python = python_import_edits(
&project.root,
&project.roots(),
&project.exclude_globs(),
&project.documents,
&syntax,
&moves,
&|| token.is_cancelled(),
);
result.edit.files.extend(python.files);
}
if token.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
project.documents.prepare_workspace_edit(&mut result.edit)?;
Ok(result)
})
.await
}
.await;
host.end_request(request);
result
}
fn is_python(path: &Path) -> bool {
path.extension().is_some_and(|e| e == "py" || e == "pyi")
}
/// The dotted name of a Python module file or package folder, from its project's Python roots
/// (`src/a/b.py` → `a.b` in a `src` layout).
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<String> {
let rel = path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/");
let base = roots
.root_for(&rel)
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
.map_or("", |r| r.path.as_str());
/// The folders Python imports modules from: source and test roots of Python projects (or marked
/// by the user), else the project root. Other languages' roots (`frontend/src`) don't count.
fn python_root<'a>(roots: &'a ProjectRoots, rel: &str) -> &'a str {
let python = |r: &&SourceFolder| {
matches!(r.kind, RootKind::Source | RootKind::Test)
&& r.detected_from.as_deref().is_none_or(|f| PYTHON_FILES.iter().any(|p| f.rsplit('/').next() == Some(*p)))
};
let inside = |r: &&SourceFolder| r.path.is_empty() || rel == r.path || rel.starts_with(&format!("{}/", r.path));
roots.roots.iter().filter(python).filter(inside).max_by_key(|r| r.path.len()).map_or("", |r| r.path.as_str())
}
fn rel_path(root: &Path, path: &Path) -> Option<String> {
Some(path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/"))
}
/// The dotted name of a Python module file or package folder and the root it is imported from
/// (`src/a/b.py` → `a.b` from `src` in a `src` layout).
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<(String, String)> {
let rel = rel_path(root, path)?;
let base = python_root(roots, &rel);
let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') };
let inner = if is_dir { inner } else { inner.strip_suffix(".py").or_else(|| inner.strip_suffix(".pyi"))? };
let inner = inner.strip_suffix("/__init__").unwrap_or(inner);
let valid = |s: &str| {
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
};
(!inner.is_empty() && inner.split('/').all(valid)).then(|| inner.replace('/', "."))
(!inner.is_empty() && inner.split('/').all(valid)).then(|| (inner.replace('/', "."), base.to_owned()))
}
/// The package relative imports in `file` start from.
fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
let Some(module) = python_module(root, roots, file, false) else { return String::new() };
let Some((module, _)) = python_module(root, roots, file, false) else { return String::new() };
if file.file_stem().is_some_and(|s| s == "__init__") {
module
} else {
@@ -75,52 +103,91 @@ fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
}
}
/// Whether `dir` holds Python modules (a package or namespace package), at any depth.
fn has_python(dir: &Path) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else { return false };
entries.flatten().any(|e| {
let path = e.path();
let name = e.file_name();
let name = name.to_string_lossy();
if e.file_type().is_ok_and(|t| t.is_dir()) {
!name.starts_with('.') && !matches!(name.as_ref(), "node_modules" | "__pycache__") && has_python(&path)
} else {
is_python(&path)
}
})
}
/// Import updates in the project's Python files for `moves` (paths before the move).
fn python_import_edits(
project: &crate::project::Project,
root: &Path,
roots: &ProjectRoots,
excludes: &[String],
documents: &Documents,
syntax: &Syntax,
moves: &[FileMove],
cancelled: &(dyn Fn() -> bool + Sync),
) -> WorkspaceEdit {
let root = &project.root;
let roots = project.roots();
let renames: Vec<(String, String)> = moves
.iter()
.filter_map(|m| {
let is_dir = m.from.is_dir();
if !is_dir && (!is_python(&m.from) || m.from.file_stem().is_some_and(|s| s == "__init__")) {
return None;
}
let old = python_module(root, &roots, &m.from, is_dir)?;
let new = python_module(root, &roots, &m.to, is_dir)?;
(old != new).then_some((old, new))
})
.collect();
// (old, new, root the old module is imported from)
let mut renames: Vec<(String, String, String)> = Vec::new();
for m in moves {
let is_dir = m.from.is_dir();
let module = if is_dir {
has_python(&m.from)
} else {
let stub_only = m.from.extension().is_some_and(|e| e == "pyi")
&& !moves.iter().any(|o| *o.from == m.from.with_extension("py"));
// A stub may describe a compiled module that stays where it is.
is_python(&m.from) && !stub_only && m.from.file_stem().is_some_and(|s| s != "__init__")
};
if !module {
continue;
}
let (Some((old, base)), Some((new, _))) =
(python_module(root, roots, &m.from, is_dir), python_module(root, roots, &m.to, is_dir))
else {
continue;
};
if old != new && !renames.iter().any(|r| r.0 == old) {
renames.push((old, new, base));
}
}
if renames.is_empty() {
return WorkspaceEdit::default();
}
let names: Vec<&str> = renames.iter().map(|(old, _)| old.rsplit('.').next().unwrap_or(old)).collect();
// `import utils` in `backend/app.py` means `backend/utils.py`, not `backend/tests/utils.py`.
let shadowed = |base: &str, module: &str| {
let p = root.join(base).join(module.replace('.', "/"));
p.with_extension("py").is_file() || p.with_extension("pyi").is_file() || p.is_dir()
};
let names: Vec<&str> = renames.iter().map(|(old, ..)| old.rsplit('.').next().unwrap_or(old)).collect();
let found: Mutex<Vec<(PathBuf, Vec<ide_core::TextEdit>)>> = Mutex::new(Vec::new());
ide_vfs::walk_files(root, &project.exclude_globs(), |path| {
ide_vfs::walk_files(root, excludes, |path| {
if cancelled() || !is_python(path) {
return;
}
let moved = moved_path(path, moves);
let text = match project.documents.text_of(path) {
Some(t) => t,
None => match std::fs::read_to_string(path) {
Ok(t) => t,
Err(_) => return,
},
};
if moved == path && !names.iter().any(|n| text.contains(n)) {
return;
if moved == path {
let Ok(bytes) = std::fs::read(path) else { return };
let raw = String::from_utf8_lossy(&bytes);
if !names.iter().any(|n| raw.contains(n)) {
return;
}
}
// Through the documents layer: unsaved edits, BOM and encodings as the edits will see them.
let Ok(text) = read_text(documents, path) else { return };
let Some(rel) = rel_path(root, path) else { return };
let base = python_root(roots, &rel);
let visible: Vec<(String, String)> = renames
.iter()
.filter(|(old, _, from)| from == base || !shadowed(base, old))
.map(|(old, new, _)| (old.clone(), new.clone()))
.collect();
let edits = syntax.python_import_edits(
&text,
&python_package(root, &roots, path),
&python_package(root, &roots, &moved),
&renames,
&python_package(root, roots, path),
&python_package(root, roots, &moved),
&visible,
);
if !edits.is_empty() {
found.lock().push((path.to_path_buf(), edits));
@@ -213,7 +280,6 @@ ide_command::domain!(
#[cfg(test)]
mod tests {
use super::*;
use ide_workspace::roots::SourceFolder;
#[test]
fn python_module_names_follow_the_roots() {
@@ -223,7 +289,7 @@ mod tests {
vec![folder("src", RootKind::Source), folder("tests", RootKind::Test)],
&Default::default(),
);
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir);
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir).map(|(m, _)| m);
assert_eq!(name("src/tasks/models.py", false).as_deref(), Some("tasks.models"));
assert_eq!(name("src/tasks/__init__.py", false).as_deref(), Some("tasks"));
assert_eq!(name("src/tasks", true).as_deref(), Some("tasks"));
@@ -234,4 +300,54 @@ mod tests {
assert_eq!(python_package(root, &roots, &root.join("src/tasks/cli.py")), "tasks");
assert_eq!(python_package(root, &roots, &root.join("src/tasks/__init__.py")), "tasks");
}
#[test]
fn python_imports_in_a_mixed_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let write = |p: &str, text: &str| {
let path = root.join(p);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
write("backend/pyproject.toml", "[project]\nname = \"b\"\n");
write("backend/utils.py", "");
write("backend/app.py", "import utils\nfrom api import routes\n");
write("backend/api/__init__.py", "");
write("backend/api/routes.py", "");
write("backend/bom.py", "\u{feff}from api import routes\n");
write("backend/tests/utils.py", "");
write("backend/tests/test_a.py", "import utils\n");
write("backend/native/_ext.pyi", "");
write("backend/uses_ext.py", "from native import _ext\n");
write("frontend/package.json", "{}");
write("frontend/src/api/index.js", "");
let roots = ProjectRoots::compute(ide_workspace::roots::detect(root), &Default::default());
let documents = Documents::new(
std::sync::Arc::new(|_| {}),
Box::new(|_: &Path, _: Option<&str>| ide_core::LanguageId::new("python")),
);
let edits = |from: &str, to: &str| {
let moves = vec![FileMove { from: root.join(from).into(), to: root.join(to).into() }];
let edit = python_import_edits(root, &roots, &[], &documents, &Syntax::new(), &moves, &|| false);
edit.files
.into_iter()
.filter_map(|f| match f {
FileEdit::Edit { path, edits, .. } => Some((rel_path(root, &path).unwrap(), edits)),
_ => None,
})
.collect::<Vec<_>>()
};
// Not Python: a JavaScript folder of the same name.
assert!(edits("frontend/src/api", "frontend/src/client").is_empty());
// Same-named modules of different roots.
let files = edits("backend/tests/utils.py", "backend/tests/helpers.py");
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/tests/test_a.py"]);
// A BOM doesn't shift the edit.
let files = edits("backend/api", "backend/web");
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/app.py", "backend/bom.py"]);
assert_eq!(files[1].1[0].range.start, ide_core::Pos { line: 0, col: 5 });
// A stub without its module.
assert!(edits("backend/native/_ext.pyi", "backend/native/_ext2.pyi").is_empty());
}
}
+13 -1
Переглянути файл
@@ -334,10 +334,19 @@ pub async fn run_start(
Some(agent) => agent.wrap_output(on_output),
None => on_output,
};
// `execute_run_configuration` asked the Run tool window to start it.
let mcp = crate::mcp::run::configs::config_run_launch(&config);
let on_output = match &mcp {
Some(mcp) => mcp.wrap_output(on_output),
None => on_output,
};
let result = start_inner(host, window, config, on_output, agent.as_ref(), &cancel).await;
if let Some(agent) = &agent {
agent.started(&result);
}
if let Some(mcp) = &mcp {
mcp.started(&result);
}
if let Some(id) = request {
host.end_request(id);
}
@@ -429,6 +438,7 @@ async fn start_inner(
encoding: Some(settings.console.encoding).filter(|e| !e.trim().is_empty()),
python_paths: Vec::new(),
ruby_reporter: None,
plots: None,
},
sink,
Box::new(move |c| on_output(c)),
@@ -445,6 +455,7 @@ async fn start_inner(
python_paths: Vec::new(),
// A folder on this machine: not in the container.
ruby_reporter: None,
plots: None,
};
project.require_trust()?;
return host.processes.start(
@@ -493,7 +504,7 @@ async fn start_inner(
}
// A Python configuration pointing at a missing interpreter fails in the depth of
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test");
if is_python && Path::new(&config.command).components().count() > 1 {
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
@@ -542,6 +553,7 @@ async fn start_inner(
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths,
ruby_reporter: ruby_reporter_dir(host, &config),
plots: if is_python { super::plots::prepare(host, &project) } else { None },
};
project.require_trust()?;
if config.kind == "go" && matches!(config.args.first().map(String::as_str), Some("mod" | "work")) {
+2 -2
Переглянути файл
@@ -110,8 +110,8 @@ pub(crate) fn search_project(
_ => true,
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
// Search's UTF-8 fast path does not need to resolve the configured encoding.
let fallback = |path: &Path| project.documents.configured_encoding_for(path);
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
+1 -1
Переглянути файл
@@ -11,7 +11,7 @@ use ide_spell::{Region, RegionKind, SpellScope, Speller, Typo};
use std::path::{Path, PathBuf};
/// Languages checked as prose (all text but code spans).
const PROSE: &[&str] = &["plaintext", "markdown", "restructuredtext", "asciidoc", "latex"];
const PROSE: &[&str] = &["plaintext", "markdown", "mdx", "restructuredtext", "asciidoc", "latex"];
/// Custom dictionary paths: `~/…` from home, relative ones from the project root.
fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
+52 -9
Переглянути файл
@@ -85,6 +85,8 @@ pub struct Project {
pub(crate) git_metadata: Option<Arc<ide_vcs::MetadataWatch>>,
/// Picks up data sources edited on disk outside the Database tool window.
_db_sources_watch: Option<ide_db::SourcesWatch>,
/// The Plots tool window's folder watch, started by the first Python run ([`crate::ops::plots`]).
pub(crate) plots_watch: Mutex<Option<notify::RecommendedWatcher>>,
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
/// nothing indexed, no language servers, repositories or project services.
pub light: bool,
@@ -211,6 +213,10 @@ impl Host {
crate::ts_code_style::configure(cfg, server_root, &effective);
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
// After the global plugins: they keep the IDE's copies.
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
let container_python = effective.languages.python.run_target().is_some();
crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective);
// Attached dependency projects are source, so basedpyright/Pyright should
@@ -360,8 +366,13 @@ impl Host {
}
{
let settings = settings.clone();
let data_dir = self.local_data_dir.clone();
lsp.set_servers_hook(Box::new(move |language, defined| {
ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective())
let mut servers = ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective());
if language.as_str() == "css" && ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit").is_none() {
ide_sdk::apply::drop_css_modules_route(&mut servers);
}
servers
}));
}
{
@@ -452,7 +463,9 @@ impl Host {
phpstan.files_removed(batch.removed.iter());
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
if composer_changed(&root, changed.iter().chain(&batch.removed))
|| ts_config_changed(changed.iter().chain(&batch.removed))
{
lsp.reconfigure_soon();
}
// Not while loading: a first `use flake` may write `flake.lock` itself.
@@ -702,6 +715,7 @@ impl Host {
_scratch_watcher: scratch_watcher,
git_metadata,
_db_sources_watch: db_sources_watch,
plots_watch: Mutex::default(),
files_events_active,
light: false,
});
@@ -762,6 +776,12 @@ impl Host {
if let Some(cmd) = post_start {
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
}
if project.is_trusted() {
let p = project.clone();
self.runtime.spawn_blocking(move || {
crate::github_auth::apply_to_project(&p);
});
}
crate::ops::sdk::container_python::ensure(self, &project);
Ok(project)
}
@@ -966,6 +986,7 @@ impl Host {
_scratch_watcher: None,
git_metadata: None,
_db_sources_watch: None,
plots_watch: Mutex::default(),
files_events_active: Arc::new(AtomicBool::new(false)),
light: true,
root: dir,
@@ -1034,9 +1055,8 @@ fn db_sources_watch(
let Some(db) = weak.upgrade() else { return };
let sink = sink.clone();
runtime.spawn(async move {
if db.reconcile_sources().await {
sink.emit(IdeEvent::DbSourcesChanged);
}
db.reconcile_sources().await;
sink.emit(IdeEvent::DbSourcesChanged);
});
}))
.inspect_err(|e| tracing::warn!("{}", e.message))
@@ -1524,8 +1544,7 @@ impl Project {
}
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
let defaults = self.documents.file_defaults();
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
let charset = self.documents.detect_encoding(path, bytes);
self.vcs_text_encoding(path, charset)
}
@@ -1884,7 +1903,9 @@ fn content_root_watcher(
index.ignore_rules_changed(&batch.ignore_rules);
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
// A workspace member's PHP language level follows its own composer.json.
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
if composer_changed(&root, changed.iter().chain(&batch.removed))
|| ts_config_changed(changed.iter().chain(&batch.removed))
{
lsp.reconfigure_soon();
}
if let Some(bridge) = &kotlin_bridge {
@@ -1906,6 +1927,17 @@ fn content_root_watcher(
.ok()
}
/// A tsconfig.json / jsconfig.json (or a `tsconfig.*.json` one extends) changed: the tsserver
/// plugins it declares are part of vtsls' configuration.
fn ts_config_changed<'a>(mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
paths.any(|p| {
let name = p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
!p.components().any(|c| c.as_os_str() == "node_modules")
&& (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
&& name.ends_with(".json")
})
}
/// Whether the `composer.json` of `root` is among `paths`: the PHP language level follows it
/// (`ide_sdk::php`).
fn composer_changed<'a>(root: &Path, mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
@@ -2731,9 +2763,20 @@ mod agent_worktree_tests {
#[cfg(test)]
mod composer_tests {
use super::composer_changed;
use super::{composer_changed, ts_config_changed};
use std::path::{Path, PathBuf};
#[test]
fn tsconfig_and_jsconfig_files_count_outside_node_modules() {
let changed = |p: &str| ts_config_changed([PathBuf::from(p)].iter());
for yes in ["/p/tsconfig.json", "/p/apps/web/jsconfig.json", "/p/tsconfig.base.json"] {
assert!(changed(yes), "{yes}");
}
for no in ["/p/package.json", "/p/tsconfig.ts", "/p/node_modules/x/tsconfig.json"] {
assert!(!changed(no), "{no}");
}
}
#[test]
fn only_the_roots_own_composer_json_counts() {
let root = Path::new("/work/app");
+1
Переглянути файл
@@ -364,6 +364,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
| IdeEvent::UpdateAvailable { .. } => false,
IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. } => trusted,
IdeEvent::DbSourcesChanged
| IdeEvent::PlotAdded { .. }
| IdeEvent::ProjectTrustChanged { .. }
| IdeEvent::Direnv { .. }
| IdeEvent::FlutterDevices { .. }
+7
Переглянути файл
@@ -282,11 +282,18 @@ impl crate::Host {
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
}
self.environment.direnv_opened(&project.root, &project.sink);
{
let p = project.clone();
self.runtime.spawn_blocking(move || {
crate::github_auth::apply_to_project(&p);
});
}
project.lsp.set_execution_allowed(true);
project.lsp.prewarm_java_configuration();
} else {
self.environment.project_closed();
self.environment.direnv_closed(&project.root);
crate::github_auth::clear_project_env(&project);
project.agents.shutdown();
project.flutter.stop();
project.devtools.stop();
+81 -13
Переглянути файл
@@ -1,4 +1,4 @@
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation, Imports) as the TypeScript
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
//! quick fixes, auto-imports, refactorings and organize imports.
@@ -48,12 +48,7 @@ pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &
.and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}"))))
.unwrap_or_default();
let section = section(language, code_style.languages.get(language), &pairs);
if !section.is_empty() {
layer.insert(language.into(), Value::Object(section));
}
}
if layer.is_empty() {
return;
layer.insert(language.into(), Value::Object(section));
}
let mut merged = Value::Object(layer);
if let Some(own) = cfg.settings.take() {
@@ -96,10 +91,30 @@ fn section(
if !format.is_empty() {
section.insert("format".into(), Value::Object(format));
}
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
// vtsls reads VS Code's names (`quoteStyle`, `importModuleSpecifier`), typescript-language-server
// tsserver's (`quotePreference`, `importModuleSpecifierPreference`).
let mut preferences = Map::new();
if let Some(quotes) = quotes {
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": quotes }));
preferences.insert("quoteStyle".into(), json!(quotes));
preferences.insert("quotePreference".into(), json!(quotes));
}
let paths = ["shortest", "relative", "non-relative", "project-relative"];
if let Some(paths) = pick(style.and_then(|s| s.import_module_specifier.as_ref()), &paths) {
preferences.insert("importModuleSpecifier".into(), json!(paths));
preferences.insert("importModuleSpecifierPreference".into(), json!(paths));
}
let endings = ["auto", "minimal", "index", "js"];
if let Some(ending) = pick(style.and_then(|s| s.import_module_specifier_ending.as_ref()), &endings) {
preferences.insert("importModuleSpecifierEnding".into(), json!(ending));
}
// Sent even when empty: vtsls has no default for these, so a list left out keeps tsserver's
// previous one, and clearing it would only apply after a restart. `[]` excludes nothing.
let none = Vec::new();
let patterns = style.map_or(&none, |s| &s.auto_import_file_exclude_patterns);
let regexes = style.map_or(&none, |s| &s.auto_import_specifier_exclude_regexes);
preferences.insert("autoImportFileExcludePatterns".into(), json!(patterns));
preferences.insert("autoImportSpecifierExcludeRegexes".into(), json!(regexes));
section.insert("preferences".into(), Value::Object(preferences));
section
}
@@ -133,9 +148,17 @@ mod tests {
"typescript": {
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
// The server's own settings win.
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
"preferences": {
"quoteStyle": "double",
"quotePreference": "single",
"autoImportFileExcludePatterns": [],
"autoImportSpecifierExcludeRegexes": [],
},
},
"javascript": {
"format": { "semicolons": "insert" },
"preferences": { "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] },
},
"javascript": { "format": { "semicolons": "insert" } },
})
);
@@ -144,7 +167,52 @@ mod tests {
assert_eq!(eslint.settings, None);
let mut untouched = server("vtsls");
configure(&mut untouched, dir.path(), &Settings::default());
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
// Nothing set: the server's defaults, and empty exclusion lists so that clearing one reaches
// a running server.
let empty = json!({ "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] });
let empty = json!({ "typescript": { "preferences": empty }, "javascript": { "preferences": empty } });
assert_eq!(untouched.settings, Some(empty));
}
#[test]
fn import_style_reaches_the_preferences_of_each_language() {
let mut settings = Settings::default();
let ts = LanguageCodeStyle {
import_module_specifier: Some("relative".into()),
import_module_specifier_ending: Some("index".into()),
auto_import_file_exclude_patterns: vec!["**/index.ts".into()],
auto_import_specifier_exclude_regexes: vec!["^node:".into()],
..Default::default()
};
settings.editor.code_style.languages.insert("typescript".into(), ts);
let js = LanguageCodeStyle {
import_module_specifier: Some("non-relative".into()),
// Not a tsserver value: left out.
import_module_specifier_ending: Some("ts".into()),
..Default::default()
};
settings.editor.code_style.languages.insert("javascript".into(), js);
let dir = tempfile::tempdir().unwrap();
let mut cfg = server("vtsls");
configure(&mut cfg, dir.path(), &settings);
assert_eq!(
cfg.settings.unwrap(),
json!({
"typescript": { "preferences": {
"importModuleSpecifier": "relative",
"importModuleSpecifierPreference": "relative",
"importModuleSpecifierEnding": "index",
"autoImportFileExcludePatterns": ["**/index.ts"],
"autoImportSpecifierExcludeRegexes": ["^node:"],
} },
"javascript": { "preferences": {
"importModuleSpecifier": "non-relative",
"importModuleSpecifierPreference": "non-relative",
"autoImportFileExcludePatterns": [],
"autoImportSpecifierExcludeRegexes": [],
} },
})
);
}
#[test]
@@ -178,6 +246,6 @@ mod tests {
configure(&mut cfg, dir.path(), &settings);
let s = cfg.settings.unwrap();
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
assert_eq!(s.get("javascript"), None);
assert_eq!(s["javascript"].get("format"), None);
}
}
+14 -1
Переглянути файл
@@ -9,12 +9,15 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(common::host_config(base)));
let root = base.join("data/consoles/db/pg");
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
};
assert!(db::db_consoles(&host, "pg".into(), false).unwrap().is_empty());
// The first new console is the default one, then console_1, console_2…
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql"]);
let first = db::db_consoles(&host, "pg".into(), true).unwrap();
assert_eq!(names(first.clone()), ["console.sql"]);
assert_eq!(first[0].0, root.join("console.sql"));
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql", "console_1.sql"]);
let all = db::db_consoles(&host, "pg".into(), true).unwrap();
assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]);
@@ -26,3 +29,13 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
assert!(db::db_consoles(&host, "pg:other".into(), false).unwrap().is_empty());
assert!(db::db_consoles(&host, "../x".into(), true).is_err());
}
#[tokio::test]
async fn consoles_root_is_the_directory_listed_in_the_project_view() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(common::host_config(base)));
let root = db::db_consoles_dir(&host).unwrap();
assert_eq!(root.0, base.join("data/consoles/db"));
assert!(root.0.is_dir());
}
+82
Переглянути файл
@@ -542,6 +542,23 @@ impl Smoke {
self.restore(doc, &before).await;
}
/// Completion at the end of the typed line, once it offers the auto-import `control`, has
/// none labelled `label`.
async fn not_offered(&self, typed: Typed, label: &str, control: &str) {
let (doc, pos, before) = self.type_line(typed).await;
self.retry("completion without the item", self.warm_up, || async {
let list = ops::lsp::lsp_completion(&self.host, WINDOW, RequestId(7), doc, pos, None).await;
let labels: Vec<String> = match list {
Ok(l) => l.items.into_iter().map(|i| i.label).collect(),
Err(e) => vec![e.to_string()],
};
let has = |name: &str| labels.iter().any(|l| l == name);
if has(control) && !has(label) { Ok(()) } else { Err(labels) }
})
.await;
self.restore(doc, &before).await;
}
async fn organize_imports(&self, import: Typed, expect: Imports) {
let (doc, _, before) = self.type_line(import).await;
let typed = import.text.trim();
@@ -696,6 +713,71 @@ async fn typescript() {
smoke("typescript", TYPESCRIPT).await;
}
/// Code Style › TypeScript › Imports (#6072): each change reaches the running vtsls, and its
/// auto-imports follow it: relative or path alias, `/index` or not, and excluded files and
/// specifiers left out.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "language smoke: needs vtsls"]
async fn typescript_import_style() {
let checks = Checks {
files: &[
(
"tsconfig.json",
r#"{"compilerOptions": {"module": "ESNext", "moduleResolution": "Bundler", "strict": true,
"noEmit": true, "allowImportingTsExtensions": true, "paths": {"@/*": ["./src/*"]}},
"include": ["src"]}"#,
),
("src/lib/alpha.ts", "export function alphaHelper(): number {\n return 1;\n}\n"),
// Never excluded, and matching what is typed (tsserver offers only those): the
// auto-import candidates are in the completion list.
("src/lib/betaWord.ts", "export function betaWord(): number {\n return 3;\n}\n"),
("src/lib/hints.ts", "export function alphaHint(): number {\n return 4;\n}\n"),
("src/app/components/index.ts", "export function betaWidget(): number {\n return 2;\n}\n"),
("src/app/main.ts", "export const ready = true;\n"),
("src/app/other.ts", "export const other = true;\n"),
("src/app/third.ts", "export const third = true;\n"),
("src/app/fourth.ts", "export const fourth = true;\n"),
("src/app/fifth.ts", "export const fifth = true;\n"),
],
..TYPESCRIPT
};
let smoke = Smoke::start("typescript", &checks).await;
let set = |key: &str, value: &str| {
let scope = ide_workspace::settings::SettingsScope::Project;
let key = format!("editor.codeStyle.languages.typescript.{key}");
ops::project::settings_set(&smoke.host, WINDOW, scope, key, value.into()).unwrap();
};
let alpha = typed("src/app/main.ts", "export const ready", "alphaH");
let beta = typed("src/app/main.ts", "export const ready", "betaW");
let import = |typed, label, result| AutoImport { typed, label, result };
set("importModuleSpecifier", r#""relative""#);
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
set("importModuleSpecifier", r#""non-relative""#);
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
set("importModuleSpecifier", r#""relative""#);
set("importModuleSpecifierEnding", r#""index""#);
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
set("importModuleSpecifierEnding", r#""minimal""#);
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
// tsserver keeps the auto-import candidates of the file it last completed in until the
// program changes; other files see an exclusion at once.
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#);
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
smoke.not_offered(typed("src/app/third.ts", "export const third", "alphaH"), "alphaHelper", "alphaHint").await;
// Emptied lists reach the server too: the symbols are offered again.
set("autoImportFileExcludePatterns", "[]");
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
set("autoImportSpecifierExcludeRegexes", "[]");
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
}
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
#[cfg(unix)]
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
+67
Переглянути файл
@@ -731,6 +731,38 @@ async fn reformat_uses_the_formatter_chain_and_preserves_a_dirty_buffer() {
assert!(p.documents.is_dirty(doc.id).unwrap());
}
/// Answers `execute_run_configuration`'s window requests the way the Run tool window does:
/// starts the configuration in a tab and says whether it started. Returns what it started.
fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>> {
let started = Arc::new(std::sync::Mutex::new(Vec::new()));
let (host, events, out) = (h.host.clone(), h.events.clone(), started.clone());
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|e| match e {
IdeEvent::McpRequest { id, request: ide_core::event::McpUiRequest::RunConfiguration { config } }
if !handled.contains(id) =>
{
Some((*id, config.clone()))
}
_ => None,
});
let Some((id, config)) = request else {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
continue;
};
handled.insert(id);
let config: ide_run::RunConfig = serde_json::from_value(config).unwrap();
out.lock().unwrap().push(config.clone());
let result =
ide_host::ops::run::run_start(&host, "main", config, ide_host::ops::Channel::new(|_| {}), None).await;
let error = result.err().map(|e| e.message);
let _ = host.mcp_requests.answer("main", id, error.is_none(), error);
}
});
started
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_reports_output_exit_code_and_requires_confirmation() {
let h = Harness::new();
@@ -765,6 +797,7 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
assert!(error.contains("denied by the user"));
assert!(h.host.processes.list().is_empty());
h.events.lock().unwrap().clear();
let tabs = config_run_window(&h);
let run = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
let allow = async {
let id = h.request().await;
@@ -773,6 +806,39 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
let (result, ()) = tokio::join!(run, allow);
assert_eq!(result["exitCode"], 7);
assert!(result["output"].as_str().unwrap().contains("captured-output"));
// It ran in a Run tool window tab, as the user's Run would.
let tabs = tabs.lock().unwrap();
assert_eq!(tabs.len(), 1);
assert_eq!(tabs[0].name, "MCP test");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
let h = Harness::new();
h.trust().await;
let config = ide_run::RunConfig {
id: "test".into(),
name: "MCP test".into(),
kind: "shell".into(),
command: if cfg!(windows) { "echo windowless& exit 3" } else { "echo windowless; exit 3" }.into(),
args: vec![],
cwd: None,
env: Default::default(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
ide_run::save_user_configs(&h.root, &[config]).unwrap();
h.host
.global_settings
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
.unwrap();
let result = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})).await;
assert_eq!(result["exitCode"], 3, "{result}");
assert!(result["output"].as_str().unwrap().contains("windowless"));
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
#[tokio::test(flavor = "multi_thread")]
@@ -795,6 +861,7 @@ async fn a_configuration_left_running_is_stopped_by_its_run_id() {
};
ide_run::save_user_configs(&h.root, &[config]).unwrap();
h.host.mcp_requests.set_ready("main", true);
let _tabs = config_run_window(&h);
let run = h.json("execute_run_configuration", json!({"configurationName":"Server","waitForExit":false}));
let allow = async {
let id = h.request().await;
+4 -3
Переглянути файл
@@ -429,9 +429,10 @@ fn gutter_actions_see_the_editors_window_project() {
assert_eq!(actions.len(), 1);
actions[0].1.argument.clone().unwrap()
};
// The outer project's window: the file is its, though the inner project holds it too.
assert_eq!(argument(Some(&outer)), outer.to_string_lossy());
assert_eq!(argument(Some(&inner)), inner.to_string_lossy());
// The outer project's window: the file is its, though the inner project holds it too. Compared
// as paths: the plugin sees Windows paths `/`-separated.
assert_eq!(Path::new(&argument(Some(&outer))), outer);
assert_eq!(Path::new(&argument(Some(&inner))), inner);
// No window, or a root that is no open project: no invoking project.
assert_eq!(argument(None), "gutter");
assert_eq!(argument(Some(&tmp.path().join("elsewhere"))), "gutter");
+2 -1
Переглянути файл
@@ -52,7 +52,8 @@ fn the_plugins_configuration_completes_only_the_argument_under_the_caret() {
let config = "plugin:test.run-anything:tasks";
// Not provided until its program is approved.
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 1).is_err());
p.choose_program(ID, "process:task", Some(&root), Some(Path::new("/bin/echo"))).unwrap();
// Any approved executable will do; the test binary exists on every host.
p.choose_program(ID, "process:task", Some(&root), Some(&std::env::current_exe().unwrap())).unwrap();
assert!(p.run_detection().detect(&root).iter().any(|c| c.id == config));
let complete = |text: &str, caret: u32| -> Vec<(String, String, u32, u32)> {
p.run_configuration_complete("main", &root, config, "arguments", text, caret)
+2 -1
Переглянути файл
@@ -6794,6 +6794,8 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
let mut req = vec![0; len];
let _ = reader.read_exact(&mut req);
let body = "plain ok";
// Recorded before the reply: the client may assert as soon as it reads it.
seen.lock().push("served".into());
let _ = writer.write_all(
format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
@@ -6801,7 +6803,6 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
)
.as_bytes(),
);
seen.lock().push("served".into());
}
});
}
+14 -8
Переглянути файл
@@ -5,7 +5,7 @@ mod common;
use ide_core::{Pos, RequestId};
use ide_host::{Host, ops};
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery};
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery, SearchScope};
use std::sync::{Arc, Mutex};
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
@@ -145,9 +145,10 @@ async fn replace_all_covers_matches_past_the_limit() {
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
let scope = base.join("scope");
let root = scope.join("project");
std::fs::create_dir_all(&root).unwrap();
for name in ["previewed.txt", "edited.txt", "closed.txt", "stale.txt"] {
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
std::fs::write(root.join(name), "TOKEN\n").unwrap();
}
let host = Host::new(common::host_config(&base));
@@ -157,14 +158,18 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
project.documents.open(&root.join("previewed.txt")).unwrap();
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
// Open and clean, but changed on disk before the watcher reported it.
let stale = project.documents.open(&root.join("stale.txt")).unwrap().id;
std::fs::write(root.join("stale.txt"), "TOKEN\nexternal\n").unwrap();
// Search the parent folder so Replace All also covers a clean buffer outside the project watch.
let stale_path = scope.join("stale.txt");
std::fs::write(&stale_path, "TOKEN\n").unwrap();
let stale = project.documents.open(&stale_path).unwrap().id;
std::fs::write(&stale_path, "TOKEN\nexternal\n").unwrap();
let mut search = query("TOKEN", false);
search.scope = SearchScope::Directory { path: scope.into() };
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
query("TOKEN", false),
search,
"DONE".into(),
false,
vec![],
@@ -178,7 +183,8 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
assert_eq!(disk("closed.txt"), "DONE\n");
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
assert_eq!(disk("stale.txt"), "TOKEN\nexternal\n", "the external change is kept");
assert_eq!(std::fs::read_to_string(&stale_path).unwrap(), "TOKEN\nexternal\n", "the external change is kept");
assert_eq!(project.documents.text_snapshot(stale).unwrap().text, "DONE\n");
assert!(project.documents.is_dirty(stale).unwrap(), "the replacement stays unsaved");
host.close_project("main");
}
+19 -4
Переглянути файл
@@ -80,14 +80,23 @@ async fn serves_projects_files_documents_search_and_runs() {
assert_eq!(opened["name"], "demo");
assert_eq!(opened["trusted"], false);
invoke(&peer, "index_status", json!({})).await.unwrap();
let metrics = invoke(&peer, "host_metrics", json!({ "includeProcesses": true })).await.unwrap();
assert!(metrics["cpuCores"].as_u64().unwrap() >= 1);
assert_eq!(metrics["processes"][0]["label"], "Backend");
assert_eq!(invoke(&peer, "lsp_servers", json!({})).await.unwrap(), json!([]));
invoke(&peer, "lsp_resend_diagnostics", json!({})).await.unwrap();
let files = invoke(&peer, "find_files", json!({"query": "main", "limit": 10})).await.unwrap();
assert!(files.is_array());
for command in
["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start", "agent_refresh_models"]
{
let error = invoke(&peer, command, json!({})).await.unwrap_err();
for (command, args) in [
("build_sync", json!({})),
("run_start", json!({})),
("sdk_locate_tools", json!({})),
("notebook_execute", json!({})),
("debug_start", json!({})),
("agent_refresh_models", json!({})),
("host_end_process", json!({ "pid": 1 })),
] {
let error = invoke(&peer, command, args).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
}
let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) };
@@ -271,6 +280,9 @@ async fn serves_projects_files_documents_search_and_runs() {
.await
.unwrap();
assert_eq!(env["DOCKER_HOST"], "unix:///run/user/1/docker.sock");
// Services › Docker commands are served by the project host too.
assert!(Dispatcher::standard().commands().contains(&"docker_snapshot"));
assert_eq!(invoke(&peer, "docker_settings", json!({})).await.unwrap()["connections"], json!([]));
// Real project-host ignore writes travel through the remote command dispatcher.
assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
@@ -391,6 +403,8 @@ async fn local_deployment_runs_on_the_project_host() {
"http_curl",
"http_environment_file",
"http_variable_definitions",
"db_source_folders",
"db_save_source_folders",
"db_sources",
"db_save_sources",
"db_set_password",
@@ -420,6 +434,7 @@ async fn local_deployment_runs_on_the_project_host() {
"db_table_page",
"db_apply_edits",
"db_console_path",
"db_consoles_dir",
"db_consoles",
"ssh_test",
"ssh_set_secret",
+22
Переглянути файл
@@ -50,3 +50,25 @@ async fn find_in_files_decodes_closed_files_with_the_project_encoding() {
project.documents.set_file_defaults(defaults);
assert!(find(&host, "中文搜索验证").await.is_empty());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn find_in_files_decodes_closed_files_with_the_editorconfig_charset() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
std::fs::write(root.join("A.java"), b"// a\xe7\xe3o \xa4 needle\n").unwrap();
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
let mut defaults = project.documents.file_defaults();
defaults.project_fallback = "gbk".into();
project.documents.set_file_defaults(defaults);
let files = find(&host, "ação €").await;
assert_eq!(files.len(), 1);
assert_eq!(files[0].matches[0].text, "// ação € needle", "the text the editor shows");
assert_eq!(find(&host, "needle").await[0].matches[0].text, "// ação € needle");
}
+3 -1
Переглянути файл
@@ -29,7 +29,9 @@ pub use syntax::{
set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{
MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases,
MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule,
PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases, resolve_fixture,
visible_fixtures,
};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
+57 -5
Переглянути файл
@@ -89,12 +89,42 @@ fn has_toml_table(file: &Path, table: &str) -> bool {
table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table)
}
/// `file` parses as JSON and has the dotted `key` with a value other than `null`:
/// an object (`eslintConfig`) or a dependency's version (`dependencies.tailwindcss`).
/// `file` parses as JSON (with comments: `tsconfig.json`) and has the dotted `key` with a value
/// other than `null` or `false`: an object (`eslintConfig`), a dependency's version
/// (`dependencies.tailwindcss`) or a switch that is on (`cmkOptions.enabled`).
fn has_json_key(file: &Path, key: &str) -> bool {
let Ok(text) = std::fs::read_to_string(file) else { return false };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(|v| !v.is_null())
json_key(file, key, 0).is_some_and(|v| !v.is_null() && v != serde_json::Value::Bool(false))
}
/// The dotted `key` of the JSON `file`. A tsconfig.json / jsconfig.json without it inherits it
/// through `extends` from a local file (`./base`, `../tsconfig.base.json`), the first one defining
/// it winning, as CSS Modules Kit reads `cmkOptions`.
fn json_key(file: &Path, key: &str, depth: usize) -> Option<serde_json::Value> {
// ponytail: package `extends` (`@tsconfig/node20`) are not resolved; only local files.
const MAX_DEPTH: usize = 8;
let text = std::fs::read_to_string(file).ok()?;
let value = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text)).ok()?;
if let Some(v) = key.split('.').try_fold(&value, |v, key| v.get(key)) {
return Some(v.clone());
}
let name = file.file_name()?.to_string_lossy();
if depth >= MAX_DEPTH || !(name.starts_with("tsconfig") || name.starts_with("jsconfig")) {
return None;
}
let extends = match value.get("extends")? {
serde_json::Value::String(s) => vec![s.as_str()],
serde_json::Value::Array(a) => a.iter().filter_map(serde_json::Value::as_str).collect(),
_ => return None,
};
extends.into_iter().filter(|e| e.starts_with("./") || e.starts_with("../")).find_map(|e| {
let base = file.parent()?.join(e);
let base = if base.is_file() {
base
} else {
base.with_file_name(format!("{}.json", base.file_name()?.to_string_lossy()))
};
json_key(&base, key, depth + 1)
})
}
/// `path` is (or, after its creation or removal, was) a root marker of the
@@ -191,6 +221,28 @@ mod tests {
std::fs::write(dir.join("package.json"), r#"{"eslintConfig": null}"#).unwrap();
assert!(!has_marker(dir, "package.json#eslintConfig"));
assert!(is_marker_path(&dir.join("package.json"), marker));
// tsconfig.json is JSON with comments; a switch that is off is no marker.
let cmk = "tsconfig.json#cmkOptions.enabled";
let tsconfig =
|enabled: &str| format!("{{\n // CSS Modules Kit\n \"cmkOptions\": {{ \"enabled\": {enabled} }},\n}}");
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
assert!(has_marker(dir, cmk));
std::fs::write(dir.join("tsconfig.json"), tsconfig("false")).unwrap();
assert!(!has_marker(dir, cmk));
// Inherited through a local `extends`, which the file itself can turn off.
std::fs::create_dir_all(dir.join("app")).unwrap();
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": ["@tsconfig/strictest", "../tsconfig"] }"#)
.unwrap();
assert!(has_marker(&dir.join("app"), cmk));
std::fs::write(
dir.join("app/tsconfig.json"),
r#"{ "extends": "../tsconfig.json", "cmkOptions": { "enabled": false } }"#,
)
.unwrap();
assert!(!has_marker(&dir.join("app"), cmk));
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": "./tsconfig.json" }"#).unwrap();
assert!(!has_marker(&dir.join("app"), cmk), "a cycle ends");
}
#[test]
+20
Переглянути файл
@@ -63,6 +63,7 @@ const BUILTIN: &[(&str, &str)] = &[
("lua", include_str!("../../../languages/lua.toml")),
("makefile", include_str!("../../../languages/makefile.toml")),
("markdown", include_str!("../../../languages/markdown.toml")),
("mdx", include_str!("../../../languages/mdx.toml")),
("nix", include_str!("../../../languages/nix.toml")),
("objective-c", include_str!("../../../languages/objective-c.toml")),
("objective-cpp", include_str!("../../../languages/objective-cpp.toml")),
@@ -1073,6 +1074,8 @@ mod tests {
assert_eq!(detect("shop/templates/shop/product_list.html"), "django-html");
assert_eq!(detect("shop/templates/shop/email/order.txt"), "django-html");
assert_eq!(detect("pages/promo.html"), "html");
// No `[debugger]` of its own: `find_config` would take it for debugpy instead of Python's.
assert!(reg.get(&LanguageId::new("django-html")).unwrap().debugger.is_none());
}
/// #4061: the project root is canonical; a template reached under another
@@ -1281,6 +1284,7 @@ mod tests {
("Views/MainWindow.axaml", "axaml"),
("MainWindow.xaml", "xml"),
("README.md", "markdown"),
("Intro.mdx", "mdx"),
("Dockerfile", "dockerfile"),
("Dockerfile.dev", "dockerfile"),
("Makefile", "makefile"),
@@ -1362,6 +1366,22 @@ mod tests {
);
}
#[test]
fn indented_sass_has_its_own_server() {
let reg = reg();
let names = |lang: &str| -> Vec<String> {
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
};
assert_eq!(names("sass"), ["some-sass-language-server"]);
let sass = &reg.get(&LanguageId::new("sass")).unwrap().language_servers[0];
assert_eq!(sass.settings.as_ref().and_then(|s| s.get("somesass")), Some(&serde_json::json!({})));
for lang in ["scss", "css", "less"] {
let names = names(lang);
assert_eq!(names[0], "vscode-css-language-server", "{lang}");
assert!(!names.iter().any(|n| n == "some-sass-language-server"), "{lang}");
}
}
#[test]
fn astro_server_leaves_typescript_sdk_resolution_to_the_launcher() {
let reg = reg();
+5
Переглянути файл
@@ -13,6 +13,7 @@ mod literals;
mod outline;
mod php_align;
mod python_facts;
mod python_fixtures;
mod python_imports;
mod rearrange;
mod rst;
@@ -35,6 +36,10 @@ pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::{merge_kinds, merge_visibility};
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression};
pub use python_fixtures::{
PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule, resolve_fixture,
visible_fixtures,
};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::OnceLock;
+564
Переглянути файл
@@ -0,0 +1,564 @@
//! pytest fixtures in one Python module: the fixtures it defines (`@pytest.fixture`), the
//! places it names one (a test's or fixture's parameters, `usefixtures("x")`,
//! `getfixturevalue("x")`) and the plugin modules it loads (`pytest_plugins`). From the
//! syntax tree only; [`resolve_fixture`] then picks the definition pytest uses, given the
//! modules a test sees, nearest first.
use super::lines::LineIndex;
use crate::{LanguageId, Syntax};
use ide_core::{Pos, Range};
use tree_sitter::{Node, Tree};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PytestModule {
pub fixtures: Vec<PytestFixture>,
pub uses: Vec<PytestFixtureUse>,
/// Where a fixture name may be typed: completion offers the visible fixtures there.
pub slots: Vec<PytestFixtureSlot>,
/// Modules named by a module-level `pytest_plugins`, as written (`pkg.fixtures`).
pub plugins: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PytestFixture {
/// The name tests ask for: the `name=` argument, else the function's name.
pub name: String,
/// That name in the source: the function name, or the `name=` string's content.
pub selection: Range,
/// The class whose method it is; only that class's tests see it.
pub class: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PytestFixtureUseKind {
Parameter,
UseFixtures,
GetFixtureValue,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PytestFixtureUse {
pub name: String,
pub range: Range,
pub kind: PytestFixtureUseKind,
pub class: Option<String>,
/// The fixture whose parameter this is: `def tasks(tasks)` asks for the next `tasks` outward.
pub in_fixture: Option<String>,
/// For a parameter: the names in the function's body that read it (attribute names and
/// keyword argument names left out), which a rename of the fixture renames too.
pub body: Vec<Range>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PytestFixtureSlot {
/// A test's or fixture's parameter list, or the content of a `usefixtures` /
/// `getfixturevalue` string (empty strings included).
pub range: Range,
pub class: Option<String>,
}
impl PytestModule {
/// The use whose name covers `pos` (its end included, where a caret after the name sits).
pub fn use_at(&self, pos: Pos) -> Option<&PytestFixtureUse> {
self.uses.iter().find(|u| u.range.start <= pos && pos <= u.range.end)
}
/// The fixture whose name (function name or `name=` string) covers `pos`.
pub fn definition_at(&self, pos: Pos) -> Option<usize> {
self.fixtures.iter().position(|f| f.selection.start <= pos && pos <= f.selection.end)
}
/// The slot holding `pos`.
pub fn slot_at(&self, pos: Pos) -> Option<&PytestFixtureSlot> {
self.slots.iter().filter(|s| s.range.start <= pos && pos <= s.range.end).min_by_key(|s| s.range.end)
}
}
impl Syntax {
/// The pytest fixtures a Python `text` defines and names; empty for other languages.
pub fn pytest_module(&self, lang: &LanguageId, text: &str) -> PytestModule {
self.analyze(lang, text, |g, tree, text| (g.spec.name == "python").then(|| extract(tree, text)))
.unwrap_or_default()
}
}
/// The fixture pytest uses for a name asked in `layers[0]` (the module), `class` being the
/// asking test's class, the later layers being the `conftest.py` files from the module's
/// folder upward, then plugins and pytest's own modules. `overriding`: the asker is a fixture
/// of that same name, which gets the next definition outward. Returns (layer, fixture) indexes.
pub fn resolve_fixture(
layers: &[&PytestModule],
name: &str,
class: Option<&str>,
overriding: bool,
) -> Option<(usize, usize)> {
visible(layers, class).filter(|&(l, f)| layers[l].fixtures[f].name == name).nth(usize::from(overriding))
}
/// The fixtures a test of `class` in `layers[0]` sees, nearest first, one per name.
pub fn visible_fixtures(layers: &[&PytestModule], class: Option<&str>) -> Vec<(usize, usize)> {
let mut seen = std::collections::HashSet::new();
visible(layers, class).filter(|&(l, f)| seen.insert(layers[l].fixtures[f].name.as_str())).collect()
}
/// Every fixture visible from `class` in `layers[0]`, nearest first: the class's own, then
/// the module's, then each later layer's module-level ones. Within one scope the last
/// definition of a name wins, as Python rebinds it.
fn visible<'a>(layers: &'a [&'a PytestModule], class: Option<&'a str>) -> impl Iterator<Item = (usize, usize)> + 'a {
let scopes = layers.iter().enumerate().flat_map(move |(l, m)| {
let own = (l == 0).then_some(class).flatten().map(|c| (l, m, Some(c)));
own.into_iter().chain(std::iter::once((l, m, None)))
});
scopes.flat_map(|(l, m, scope)| {
let mut picked: Vec<(usize, usize)> = Vec::new();
for (f, fixture) in m.fixtures.iter().enumerate().rev() {
if fixture.class.as_deref() == scope && !picked.iter().any(|&(_, p)| m.fixtures[p].name == fixture.name) {
picked.push((l, f));
}
}
picked.reverse();
picked
})
}
fn extract(tree: &Tree, text: &str) -> PytestModule {
let idx = LineIndex::new(text);
let mut out = PytestModule::default();
let root = tree.root_node();
let mut cursor = root.walk();
for node in root.named_children(&mut cursor) {
statement(node, None, text, &idx, &mut out);
}
// `usefixtures` / `getfixturevalue` calls wherever they are.
let mut walker = root.walk();
visit(&mut walker, &mut |node| {
if node.kind() == "call" {
fixture_call(node, text, &idx, &mut out);
}
});
out
}
/// A top-level statement, or one in a class body (`class` set).
fn statement(node: Node, class: Option<&str>, text: &str, idx: &LineIndex, out: &mut PytestModule) {
let (definition, decorators) = match node.kind() {
"decorated_definition" => {
let mut c = node.walk();
let decorators: Vec<Node> = node.children(&mut c).filter(|n| n.kind() == "decorator").collect();
let Some(definition) = node.child_by_field_name("definition") else { return };
(definition, decorators)
}
_ => (node, Vec::new()),
};
match definition.kind() {
"function_definition" => function(definition, &decorators, class, &[], text, idx, out),
"class_definition" if class.is_none() => {
let Some(name) = definition.child_by_field_name("name") else { return };
let name = text_of(name, text);
let Some(body) = definition.child_by_field_name("body") else { return };
// `@pytest.mark.parametrize` on the class names arguments of every test in it.
let class_args = parametrized(&decorators, text, idx);
let mut c = body.walk();
for child in body.named_children(&mut c) {
let (def, decs) = match child.kind() {
"decorated_definition" => {
let mut c2 = child.walk();
let decs: Vec<Node> = child.children(&mut c2).filter(|n| n.kind() == "decorator").collect();
match child.child_by_field_name("definition") {
Some(d) => (d, decs),
None => continue,
}
}
_ => (child, Vec::new()),
};
if def.kind() == "function_definition" {
function(def, &decs, Some(&name), &class_args, text, idx, out);
}
}
}
"expression_statement" if class.is_none() => plugins(definition, text, idx, &mut out.plugins),
_ => {}
}
}
fn function(
def: Node,
decorators: &[Node],
class: Option<&str>,
class_args: &[String],
text: &str,
idx: &LineIndex,
out: &mut PytestModule,
) {
let Some(name_node) = def.child_by_field_name("name") else { return };
let name = text_of(name_node, text);
let fixture = decorators.iter().find_map(|d| fixture_decorator(*d, text, idx));
let is_test = name.starts_with("test") && class.is_none_or(|c| c.starts_with("Test"));
if fixture.is_none() && !is_test {
return;
}
let fixture_name = fixture.as_ref().and_then(|f| f.as_ref().map(|(n, _)| n.clone())).unwrap_or(name.clone());
if let Some(f) = &fixture {
let selection = match f {
Some((_, string)) => *string,
None => idx.range(name_node.start_byte(), name_node.end_byte()),
};
out.fixtures.push(PytestFixture { name: fixture_name.clone(), selection, class: class.map(str::to_owned) });
}
let Some(params) = def.child_by_field_name("parameters") else { return };
out.slots.push(PytestFixtureSlot {
range: idx.range(params.start_byte(), params.end_byte()),
class: class.map(str::to_owned),
});
// Arguments `parametrize` supplies are no fixtures (unless indirect).
let mut skip: Vec<String> = parametrized(decorators, text, idx);
skip.extend_from_slice(class_args);
let mut c = params.walk();
for (i, param) in params.named_children(&mut c).enumerate() {
let ident = match param.kind() {
"identifier" => param,
"typed_parameter" => match param.named_child(0) {
Some(n) if n.kind() == "identifier" => n,
_ => continue,
},
// Defaulted parameters, `*args`, `**kwargs`: no fixtures.
_ => continue,
};
let param_name = text_of(ident, text);
if (i == 0 && class.is_some() && (param_name == "self" || param_name == "cls")) || skip.contains(&param_name) {
continue;
}
let body = def.child_by_field_name("body").map(|b| reads_of(b, &param_name, text, idx)).unwrap_or_default();
out.uses.push(PytestFixtureUse {
name: param_name,
range: idx.range(ident.start_byte(), ident.end_byte()),
kind: PytestFixtureUseKind::Parameter,
class: class.map(str::to_owned),
in_fixture: fixture.is_some().then(|| fixture_name.clone()),
body,
});
}
}
/// The identifiers `name` in `body`, except attribute names (`x.name`) and keyword argument
/// names (`f(name=…)`). A nested function that rebinds the name is not told apart.
fn reads_of(body: Node, name: &str, text: &str, idx: &LineIndex) -> Vec<Range> {
let mut out = Vec::new();
let mut cursor = body.walk();
visit(&mut cursor, &mut |n| {
if n.kind() != "identifier" || text.get(n.byte_range()) != Some(name) {
return;
}
let field_of = |parent: Node, field: &str| parent.child_by_field_name(field).is_some_and(|c| c.id() == n.id());
if let Some(parent) = n.parent()
&& ((parent.kind() == "attribute" && field_of(parent, "attribute"))
|| (parent.kind() == "keyword_argument" && field_of(parent, "name")))
{
return;
}
out.push(idx.range(n.start_byte(), n.end_byte()));
});
out
}
/// `Some(None)` for `@pytest.fixture` / `@fixture(...)`, `Some(Some((name, range)))` with a
/// `name="…"` argument, `None` for any other decorator.
fn fixture_decorator(decorator: Node, text: &str, idx: &LineIndex) -> Option<Option<(String, Range)>> {
let expr = decorator.named_child(0)?;
let (callee, args) = match expr.kind() {
"call" => (expr.child_by_field_name("function")?, expr.child_by_field_name("arguments")),
_ => (expr, None),
};
let callee = text_of(callee, text);
if callee != "fixture" && !callee.ends_with(".fixture") {
return None;
}
let named = args.and_then(|args| {
let mut c = args.walk();
args.named_children(&mut c).find_map(|a| {
if a.kind() != "keyword_argument" || a.child_by_field_name("name").map(|n| text_of(n, text))? != "name" {
return None;
}
string_content(a.child_by_field_name("value")?, text, idx)
})
});
Some(named)
}
/// The argument names of `@pytest.mark.parametrize("a, b", …)` decorators that are passed
/// directly (no `indirect=`).
fn parametrized(decorators: &[Node], text: &str, idx: &LineIndex) -> Vec<String> {
let mut out = Vec::new();
for d in decorators {
let Some(call) = d.named_child(0).filter(|n| n.kind() == "call") else { continue };
let Some(callee) = call.child_by_field_name("function") else { continue };
if !text_of(callee, text).ends_with("parametrize") {
continue;
}
let Some(args) = call.child_by_field_name("arguments") else { continue };
let mut c = args.walk();
let all: Vec<Node> = args.named_children(&mut c).collect();
let indirect = all.iter().any(|a| {
a.kind() == "keyword_argument"
&& a.child_by_field_name("name").is_some_and(|n| text_of(n, text) == "indirect")
&& a.child_by_field_name("value").is_some_and(|v| text_of(v, text) != "False")
});
if indirect {
continue;
}
let first = all.iter().find(|a| a.kind() != "keyword_argument");
let names: Vec<String> = match first {
Some(n) if n.kind() == "string" => string_content(*n, text, idx)
.map(|(s, _)| s.split(',').map(|p| p.trim().to_owned()).collect())
.unwrap_or_default(),
Some(n) if matches!(n.kind(), "list" | "tuple") => {
let mut c = n.walk();
n.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s)).collect()
}
_ => Vec::new(),
};
out.extend(names.into_iter().filter(|n| !n.is_empty()));
}
out
}
/// `usefixtures("a", "b")` and `request.getfixturevalue("a")`.
fn fixture_call(call: Node, text: &str, idx: &LineIndex, out: &mut PytestModule) {
let Some(callee) = call.child_by_field_name("function") else { return };
let callee_text = text_of(callee, text);
let kind = if callee_text == "usefixtures" || callee_text.ends_with(".usefixtures") {
PytestFixtureUseKind::UseFixtures
} else if callee.kind() == "attribute"
&& callee.child_by_field_name("attribute").is_some_and(|a| text_of(a, text) == "getfixturevalue")
{
PytestFixtureUseKind::GetFixtureValue
} else {
return;
};
let Some(args) = call.child_by_field_name("arguments") else { return };
let class = enclosing_class(call, text);
let mut c = args.walk();
for (i, arg) in args.named_children(&mut c).enumerate() {
if kind == PytestFixtureUseKind::GetFixtureValue && i > 0 {
break;
}
let Some((name, range)) = string_content(arg, text, idx) else { continue };
out.slots.push(PytestFixtureSlot { range, class: class.clone() });
if !name.is_empty() {
out.uses.push(PytestFixtureUse {
name,
range,
kind,
class: class.clone(),
in_fixture: None,
body: Vec::new(),
});
}
}
}
/// The top-level class a node is in, if any.
fn enclosing_class(node: Node, text: &str) -> Option<String> {
let mut at = node.parent();
let mut class = None;
while let Some(n) = at {
if n.kind() == "class_definition" {
class = n.child_by_field_name("name").map(|c| text_of(c, text));
}
at = n.parent();
}
class
}
/// `pytest_plugins = "a"`, `= ["a", "b"]` or `= ("a",)`.
fn plugins(statement: Node, text: &str, idx: &LineIndex, out: &mut Vec<String>) {
let Some(assign) = statement.named_child(0).filter(|n| n.kind() == "assignment") else { return };
if assign.child_by_field_name("left").map(|l| text_of(l, text)).as_deref() != Some("pytest_plugins") {
return;
}
let Some(right) = assign.child_by_field_name("right") else { return };
match right.kind() {
"string" => out.extend(string_content(right, text, idx).map(|(s, _)| s)),
"list" | "tuple" => {
let mut c = right.walk();
out.extend(right.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s)));
}
_ => {}
}
}
/// The content of a plain string literal and its range (between the quotes); none for
/// f-strings, byte strings and concatenations.
fn string_content(node: Node, text: &str, idx: &LineIndex) -> Option<(String, Range)> {
if node.kind() != "string" {
return None;
}
let mut c = node.walk();
let parts: Vec<Node> = node.children(&mut c).collect();
let start = parts.iter().find(|p| p.kind() == "string_start")?;
let end = parts.iter().find(|p| p.kind() == "string_end")?;
if text_of(*start, text).chars().any(|ch| matches!(ch, 'f' | 'F' | 'b' | 'B')) {
return None;
}
if parts.iter().any(|p| p.kind() == "interpolation" || p.kind() == "escape_sequence") {
return None;
}
let (from, to) = (start.end_byte(), end.start_byte());
Some((text.get(from..to)?.to_owned(), idx.range(from, to)))
}
fn text_of(node: Node, text: &str) -> String {
text.get(node.byte_range()).unwrap_or_default().to_owned()
}
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
loop {
f(cursor.node());
if cursor.goto_first_child() {
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn module(src: &str) -> PytestModule {
static S: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
S.get_or_init(Syntax::new).pytest_module(&LanguageId::new("python"), src)
}
fn names(m: &PytestModule) -> Vec<String> {
m.fixtures
.iter()
.map(|f| format!("{}{}", f.class.as_deref().map(|c| format!("{c}.")).unwrap_or_default(), f.name))
.collect()
}
fn uses(m: &PytestModule) -> Vec<String> {
m.uses.iter().map(|u| format!("{:?} {}", u.kind, u.name)).collect()
}
const TEST_MODULE: &str = r#"import pytest
from pytest import fixture
pytest_plugins = ["pkg.fixtures", "other"]
pytestmark = pytest.mark.usefixtures("db")
@pytest.fixture
def tasks(tmp_path):
return []
@fixture(scope="module", name="client")
def make_client(tasks, request):
return request.getfixturevalue("server")
@pytest.mark.parametrize("title, expected", [("a", "a")])
def test_add(tasks, title, expected, monkeypatch, flag=False, *args):
pass
def helper(tasks):
pass
@pytest.mark.usefixtures("client", "")
class TestTasks:
@pytest.fixture
def tasks(self, tasks):
return tasks
def test_one(self, tasks: list, capsys):
pass
"#;
#[test]
fn reads_definitions_uses_and_plugins() {
let m = module(TEST_MODULE);
assert_eq!(names(&m), ["tasks", "client", "TestTasks.tasks"]);
assert_eq!(m.plugins, ["pkg.fixtures", "other"]);
assert_eq!(
uses(&m),
[
"Parameter tmp_path",
"Parameter tasks",
"Parameter request",
"Parameter tasks",
"Parameter monkeypatch",
"Parameter tasks",
"Parameter tasks",
"Parameter capsys",
"UseFixtures db",
"GetFixtureValue server",
"UseFixtures client",
]
);
// `name=` is found by its string; the overriding class fixture knows it overrides.
let client = &m.fixtures[1];
assert_eq!((client.selection.start.line, client.selection.start.col), (12, 31));
let own = m.uses.iter().find(|u| u.class.as_deref() == Some("TestTasks") && u.in_fixture.is_some()).unwrap();
assert_eq!(own.in_fixture.as_deref(), Some("tasks"));
// The empty `usefixtures` string is still a place to complete.
assert!(m.slots.iter().any(|s| s.range.start == s.range.end));
}
#[test]
fn resolves_nearest_first_and_overrides_outward() {
let m = module(TEST_MODULE);
let conftest = module(
"import pytest\n\n@pytest.fixture\ndef tasks():\n return [1]\n\n@pytest.fixture\ndef db():\n pass\n",
);
let builtins = module("from _pytest.fixtures import fixture\n\n@fixture\ndef tmp_path():\n pass\n");
let layers = [&m, &conftest, &builtins];
// In the class: its own `tasks`; at module level: the module's.
assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), false), Some((0, 2)));
assert_eq!(resolve_fixture(&layers, "tasks", None, false), Some((0, 0)));
// The class fixture's `tasks` parameter: the module's; the module's own: conftest's.
assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), true), Some((0, 0)));
assert_eq!(resolve_fixture(&layers, "tasks", None, true), Some((1, 0)));
assert_eq!(resolve_fixture(&layers, "db", None, false), Some((1, 1)));
assert_eq!(resolve_fixture(&layers, "tmp_path", None, false), Some((2, 0)));
assert_eq!(resolve_fixture(&layers, "missing", None, false), None);
// Completion: one entry per name, nearest first; another class's fixtures are hidden.
let visible: Vec<&str> =
visible_fixtures(&layers, None).iter().map(|&(l, f)| layers[l].fixtures[f].name.as_str()).collect();
assert_eq!(visible, ["tasks", "client", "db", "tmp_path"]);
}
#[test]
fn a_parameter_knows_its_reads_in_the_body() {
let m = module("def test_a(tasks):\n tasks.add(tasks=tasks)\n other.tasks = len(tasks)\n");
let u = &m.uses[0];
let reads: Vec<(u32, u32)> = u.body.iter().map(|r| (r.start.line, r.start.col)).collect();
assert_eq!(reads, [(1, 4), (1, 20), (2, 22)]);
assert_eq!(m.definition_at(Pos::new(0, 6)), None);
}
#[test]
fn a_later_definition_replaces_an_earlier_one() {
let m = module("import pytest\n\n@pytest.fixture\ndef a():\n pass\n\n@pytest.fixture\ndef a():\n pass\n");
assert_eq!(resolve_fixture(&[&m], "a", None, false), Some((0, 1)));
}
#[test]
fn finds_the_use_and_slot_at_a_position() {
let m = module(TEST_MODULE);
// `def test_add(tasks, …` is on line 18; the caret right after `tasks`.
let at = m.use_at(Pos::new(18, 18)).unwrap();
assert_eq!(at.name, "tasks");
assert!(m.slot_at(Pos::new(18, 13)).is_some());
assert!(m.use_at(Pos::new(22, 11)).is_none(), "a plain function's parameters are no fixtures");
}
}
+178 -33
Переглянути файл
@@ -38,27 +38,85 @@ struct Rewrite<'a> {
impl Rewrite<'_> {
fn run(mut self, tree: &Tree) -> Vec<TextEdit> {
let mut imports = Vec::new();
let mut chains = Vec::new();
let mut idents = Vec::new();
collect(tree.root_node(), &mut |n| match n.kind() {
"import_statement" | "import_from_statement" => imports.push(n),
"attribute" if !inside_import(n) => chains.push(n),
"identifier" if !inside_import(n) => idents.push(n),
_ => {}
});
let mut renamed: Vec<(String, String)> = Vec::new();
// Unaliased `import a.b` that change: (name node, old, new). They bind `a`, used as `a.b.x`.
let mut dotted: Vec<(Node, String, String)> = Vec::new();
let mut kept: Vec<String> = Vec::new();
for node in imports {
if node.kind() == "import_statement" {
self.import(node, &mut renamed);
self.import(node, &mut dotted, &mut kept);
} else {
self.import_from(node);
}
}
// `import a.b` is used as `a.b.x`: those chains follow the import.
for node in chains {
let t = self.src(node);
if let Some((_, new)) = renamed.iter().find(|(old, _)| *old == t) {
self.edit(node, new.clone());
if dotted.is_empty() {
return self.finish();
}
let root_of = |s: &str| s.split('.').next().unwrap_or_default().to_owned();
let mut needed: Vec<(usize, String)> = Vec::new();
for id in idents {
let name = self.src(id);
if !dotted.iter().any(|(_, old, _)| root_of(old) == name) || is_attribute_field(id) {
continue;
}
// `a`, `a.b`, `a.b.x`: one edit per expression, on the longest prefix that moved.
let mut spine = vec![id];
while let Some(p) = spine
.last()
.and_then(|n| n.parent())
.filter(|p| p.kind() == "attribute" && p.child_by_field_name("object") == spine.last().copied())
{
spine.push(p);
}
let key = |n: Node| self.src(n).chars().filter(|c| !c.is_whitespace()).collect::<String>();
// ponytail: a bare `pkg` (no attribute) is never rewritten, it may be a parameter or a
// local of the same name.
if let Some((node, new)) =
spine.iter().skip(1).rev().find_map(|&n| Some((n, map_module(&key(n), self.moves)?)))
{
self.edit(node, new);
continue;
}
// A use the rewritten imports no longer bind (`pkg.helper()` after `import pkg.models` moved).
if spine.len() < 2 {
continue;
}
let used = key(*spine.last().unwrap_or(&id));
for (i, (_, old, new)) in dotted.iter().enumerate() {
let common: Vec<&str> = old
.split('.')
.zip(used.split('.'))
.take(old.split('.').count() - 1)
.take_while(|(a, b)| a == b)
.map(|(a, _)| a)
.collect();
if common.is_empty() {
continue;
}
let prefix = common.join(".");
let covered = |m: &String| *m == prefix || m.starts_with(&format!("{prefix}."));
let gone = map_module(&prefix, self.moves).is_some();
if !gone && !covered(new) && !kept.iter().any(covered) && !needed.contains(&(i, prefix.clone())) {
needed.push((i, prefix));
}
}
}
for (i, (node, _, new)) in dotted.iter().enumerate() {
let extra: String = needed.iter().filter(|(j, _)| *j == i).map(|(_, p)| format!(", {p}")).collect();
self.edits.push(TextEdit {
range: self.idx.range(node.start_byte(), node.end_byte()),
new_text: format!("{new}{extra}"),
});
}
self.finish()
}
fn finish(mut self) -> Vec<TextEdit> {
self.edits.sort_by_key(|e| (e.range.start.line, e.range.start.col));
self.edits
}
@@ -72,7 +130,7 @@ impl Rewrite<'_> {
}
/// `import a.b`, `import a.b as c`.
fn import(&mut self, node: Node, renamed: &mut Vec<(String, String)>) {
fn import<'t>(&mut self, node: Node<'t>, dotted: &mut Vec<(Node<'t>, String, String)>, kept: &mut Vec<String>) {
let mut cursor = node.walk();
for item in node.children_by_field_name("name", &mut cursor) {
let (name, aliased) = match item.kind() {
@@ -83,12 +141,16 @@ impl Rewrite<'_> {
_ => (item, false),
};
let old = self.src(name).to_owned();
let Some(new) = map_module(&old, self.moves) else { continue };
let Some(new) = map_module(&old, self.moves) else {
if !aliased {
kept.push(old);
}
continue;
};
if aliased {
self.edit(name, new);
} else if old.contains('.') {
renamed.push((old, new.clone()));
self.edit(name, new);
dotted.push((name, old, new));
} else {
// The bound name stays, so the rest of the file needs no change.
self.edit(name, format!("{new} as {old}"));
@@ -166,18 +228,20 @@ impl Rewrite<'_> {
}
return;
}
for (item, text) in &in_place {
self.edit(*item, text.clone());
}
if moved.is_empty() {
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
for (item, text) in in_place {
self.edit(item, text);
}
return;
}
// ponytail: a split statement loses a multi-line names list's layout; fine for the rare
// "some names of one `from` moved elsewhere" case.
let indent = line_indent(self.text, node.start_byte());
// Names imported from elsewhere now go to statements of their own, after this one (or
// after `;` when the statement shares its line: `try: from a import b, c`).
let line_start = self.text[..node.start_byte()].rfind('\n').map_or(0, |i| i + 1);
let before = &self.text[line_start..node.start_byte()];
let sep = if before.trim().is_empty() { format!("\n{before}") } else { "; ".to_owned() };
let mut parents: Vec<&str> = Vec::new();
for m in &moved {
if !parents.contains(&m.1.as_str()) {
@@ -194,28 +258,46 @@ impl Rewrite<'_> {
format!("from {from} import {}", items.join(", "))
});
}
let kept: Vec<String> = names
.iter()
.filter(|n| !moved.iter().any(|m| m.0 == **n))
.map(|n| in_place.iter().find(|(i, _)| i == n).map_or_else(|| self.src(*n).to_owned(), |(_, t)| t.clone()))
.collect();
let sep = format!("\n{indent}");
if kept.is_empty() {
let is_moved = |n: &Node| moved.iter().any(|m| m.0 == *n);
let Some(last_kept) = names.iter().rposition(|n| !is_moved(n)) else {
self.edit(node, added.join(&sep));
return;
}
};
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
let (first, last) = (names[0], names[names.len() - 1]);
let range = self.idx.range(first.start_byte(), last.end_byte());
self.edits.push(TextEdit { range, new_text: kept.join(", ") });
let mut trailing_done = false;
for (i, item) in names.iter().enumerate().filter(|(_, n)| is_moved(n)) {
let (start, end) = if let Some(line) = self.own_lines(*item) {
line
} else if i < last_kept {
(item.start_byte(), names[i + 1].start_byte())
} else if !trailing_done {
trailing_done = true;
(names[last_kept].end_byte(), names[names.len() - 1].end_byte())
} else {
continue;
};
self.edits.push(TextEdit { range: self.idx.range(start, end), new_text: String::new() });
}
let end = self.idx.pos(node.end_byte());
self.edits.push(TextEdit {
range: ide_core::Range { start: end, end },
new_text: format!("{sep}{}", added.join(&sep)),
});
}
/// The whole lines of an import list item that has them to itself (` models, # noqa`).
fn own_lines(&self, item: Node) -> Option<(usize, usize)> {
let start = self.text[..item.start_byte()].rfind('\n').map_or(0, |i| i + 1);
if !self.text[start..item.start_byte()].trim().is_empty() {
return None;
}
let end = self.text[item.end_byte()..].find('\n').map_or(self.text.len(), |i| item.end_byte() + i + 1);
let rest = self.text[item.end_byte()..end].trim_start();
let rest = rest.strip_prefix(',').unwrap_or(rest).trim();
(rest.is_empty() || rest.starts_with('#')).then_some((start, end))
}
}
fn collect<'t>(node: Node<'t>, f: &mut impl FnMut(Node<'t>)) {
@@ -236,9 +318,9 @@ fn inside_import(mut n: Node) -> bool {
false
}
fn line_indent(text: &str, byte: usize) -> &str {
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
&text[start..byte]
/// `x` in `obj.x`.
fn is_attribute_field(n: Node) -> bool {
n.parent().is_some_and(|p| p.kind() == "attribute" && p.child_by_field_name("attribute") == Some(n))
}
fn join(a: &str, b: &str) -> String {
@@ -288,6 +370,11 @@ mod tests {
let moves: Vec<(String, String)> = moves.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
let mut edits = Syntax::new().python_import_edits(text, package, new_package, &moves);
edits.sort_by_key(|e| std::cmp::Reverse((e.range.start.line, e.range.start.col)));
// Like `ide-text`, which rejects a set of overlapping edits.
for w in edits.windows(2) {
let (later, earlier) = (&w[0].range, &w[1].range);
assert!((earlier.end.line, earlier.end.col) <= (later.start.line, later.start.col), "overlap: {edits:?}");
}
let mut out = text.to_owned();
for e in edits {
let (s, t) = (byte_at(&out, e.range.start).unwrap(), byte_at(&out, e.range.end).unwrap());
@@ -388,6 +475,64 @@ mod tests {
assert_eq!(apply(src, "pkg", "pkg", RENAME), src);
}
#[test]
fn nested_chains_get_one_edit() {
let src = "import pkg.models\nimport pkg.models.sub\npkg.models.sub.f()\npkg.models.g()\n";
assert_eq!(
apply(src, "", "", &[("pkg", "lib.pkg")]),
"import lib.pkg.models\nimport lib.pkg.models.sub\nlib.pkg.models.sub.f()\nlib.pkg.models.g()\n"
);
}
#[test]
fn other_uses_of_the_old_prefix_keep_their_binding() {
let moves = &[("pkg.models", "core.models")];
assert_eq!(
apply("import pkg.models\n\npkg.models.Task()\npkg.helper()\n", "", "", moves),
"import core.models, pkg\n\ncore.models.Task()\npkg.helper()\n"
);
let moves = &[("a.b.c", "a.x.c")];
assert_eq!(
apply("import a.b.c\na.b.c.f()\na.b.g()\n", "", "", moves),
"import a.x.c, a.b\na.x.c.f()\na.b.g()\n"
);
// Inside a moved package the other uses follow it.
assert_eq!(
apply("import pkg.models\npkg.helper()\n", "", "", &[("pkg", "lib.pkg")]),
"import lib.pkg.models\nlib.pkg.helper()\n"
);
}
#[test]
fn bare_names_are_left_alone() {
let src = "import pkg.models\ndef f(pkg):\n return pkg.models.x\n";
assert_eq!(
apply(src, "", "", &[("pkg", "lib.pkg")]),
"import lib.pkg.models\ndef f(pkg):\n return lib.pkg.models.x\n"
);
}
#[test]
fn split_statements_stay_valid() {
let moves = &[("pkg.models", "core.models")];
assert_eq!(
apply("try: from pkg import cli, models\nexcept ImportError: pass\n", "", "", moves),
"try: from pkg import cli; from core import models\nexcept ImportError: pass\n"
);
assert_eq!(
apply("import os; from pkg import cli, models\n", "", "", moves),
"import os; from pkg import cli; from core import models\n"
);
assert_eq!(
apply("from pkg import (\n models, # noqa: F401\n cli, # used below\n)\n", "", "", moves),
"from pkg import (\n cli, # used below\n)\nfrom core import models\n"
);
assert_eq!(
apply("from pkg import (\n cli, # used below\n models,\n)\n", "", "", moves),
"from pkg import (\n cli, # used below\n)\nfrom core import models\n"
);
}
#[test]
fn helpers() {
assert_eq!(resolve(1, "m", "a.b").as_deref(), Some("a.b.m"));
+1
Переглянути файл
@@ -28,6 +28,7 @@ percent-encoding = "2"
zip.workspace = true
[dev-dependencies]
ide-sdk.workspace = true
tempfile.workspace = true
encoding_rs.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util"] }
Loaded 100 of 742 files, more files were not shown because too many files have changed in this diff. Show more