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

...
Автор SHA1 Повідомлення Дата
l0ng-ai f6590e6a78 fix(plugins): let capabilities.reasons explain capabilities a contribution brings
A plugin with [[contributes.javaAgents]] gets java.agent without listing it under [capabilities] (listing it is an error), so the manifest check rejected a reason for it and the install dialog and Permissions showed only the IDE's description. Reasons may now also name the capabilities contributions bring: java.agent from javaAgents and project.read from documentIndexers.

Fixes #7088
2026-12-01 03:25:56 +08:00
Ivan 3b488a7824 fix(macos): let background project tabs give their web content memory back (#7060)
A background project tab of a native tab group detaches its WKWebView from the window 30 s after it leaves the front, so WebKit frees the hidden page's graphics and caches. The view comes back when the tab is selected through our tab bar, when its window becomes key (Window menu, Close Project) or when AppKit makes it visible by itself; an inactive app's full-screen group waits for activation (#6937).

Every macOS with_webview caller goes through macos::with_web_view, which hands the retained view to a detached tab instead of panicking in wry; titlebar::set_height uses the NSWindow directly. clippy.toml disallows the raw with_webview calls. Covered by BackgroundTabs unit tests and an AppKit test of the synchronous re-attach on the key notification (it no longer asks a never-loaded web view for its process ids, which WebKit asserts on).

Fixes #6938

Co-authored-by: Pecnikas <[email protected]>

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 03:20:08 +08:00
l0ng-ai b5e89aace0 feat(run): show each invocation of a parameterized test in the Run window (#7099)
The JUnit runner and the Gradle test init script report an invocation of a parameterized, repeated or dynamic test with its display name, and the JVM parser puts it under its method node with its own status, output and stack trace; the method shows the aggregate. Rerunning a failed invocation reruns its method.

Fixes #7046
2026-12-01 03:06:11 +08:00
Akbar Husain 81c95b2ab7 perf(lint): clear remaining non-e2e React perf violations (#7093)
Clears the remaining non-e2e React perf lint violations and turns the three rules on outside e2e/ so they can't come back: data-derived keys for diagram edges and deadlock cycles (index keys stay, with a documented suppression, where position is the identity), context values in tests hoisted to constants or memoized, and array/JSX default props replaced with module-level constants.

Co-authored-by: akbar1214 <[email protected]>
2026-12-01 02:59:24 +08:00
LU XIANGRUIтаwildcatDownstairs f7b5cc388c feat(run): debug Python on a WSL run target (#6777)
A Python run configuration on a WSL target can now be debugged: the program starts under the container debugger's bootstrap in the distribution, which waits for the IDE on the distribution's loopback (WSL forwards it), finding the IDE's debugpy and bootstrap through wslpath when the distro has none. Stop ends the debugged process in the distribution, with pkill or, where it is missing, a /proc scan. Other kinds say they can't be debugged in WSL.

Also carries the WSL run target review fixes that neither #6764 nor #6770 included: Maven options naming this machine's files are dropped from remote runs, a failed wsl.exe listing is reported in Run Targets and retried on focus, an unsafe distribution name is cleared and asked for again, a printed path whose .. climbs above its root is refused, and prepare_wsl is built only on Windows.

Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04): a breakpoint is hit and Stop leaves no debug process.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:54:14 +08:00
LU XIANGRUIтаwildcatDownstairs 277d0e9d1e feat(python): a Python in WSL as the project interpreter (#6770)
Python > Add Interpreter gets a WSL tab: pick a distribution and a Python in it (a bare python3 is looked up on the distribution's PATH; Windows paths are refused). The project interpreter then runs in the distribution: packages are listed from there, the project's virtualenv inside the distro is read, the language server resolves imports from the distro's site-packages through \\wsl.localhost, and runs go through the WSL run target. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:38:34 +08:00
LU XIANGRUIтаwildcatDownstairs d6adb7aa40 feat(run): run configurations in a WSL distribution from a Windows project (#6764)
Settings > Run Targets gets a WSL target that lists the installed distributions. A run configuration on it starts locally as wsl.exe -d <distro> --cd <dir> --exec ..., with the project's Windows paths mapped to /mnt/<drive>/..., arguments passed unchanged, environment variables forwarded through WSLENV, and Stop ending the Linux process. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04), including quoted arguments and Emulate terminal.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:21:28 +08:00
l0ng-ai 6e5e482410 test(memory): make the debounce test tolerate a loaded machine (#7098)
memory::tests::a_burst_of_calls_runs_once_after_the_delay failed on a loaded macOS runner: with a 100 ms delay and 20 ms gaps, oversleeping let the debounced call fire before the burst ended. The test now uses a 500 ms delay, checks "nothing ran yet" only when less than the delay has passed since the last call, waits for the run, and asserts exactly one run only when no gap in the burst reached the delay.
2026-12-01 02:20:22 +08:00
solhovoy cc02c2fe40 feat(vcs): show shelved files under their shelf with grouping and diff preview (#7090)
The Shelf tab now lists each shelf's files beneath it in one tree instead of a separate files pane. View Options groups the files by Directory or Module and toggles Show Diff Preview (a side-by-side diff of the selected file, hidden in non-modal commit mode); Expand All / Collapse All work on the groups. File paths show inline, Delete and Cmd+Backspace delete the selected shelf or file, and the Shelve button, already in Local Changes, is gone from this toolbar.

Co-authored-by: solhovoy <[email protected]>
2026-12-01 02:16:33 +08:00
Игорь Тихомиров 74a3f6470a feat(php): add PHPantom as a built-in language server (#7052)
PHPantom (MIT) joins the selectable PHP language servers, with a tools-registry entry for installing it.

textDocument/implementation now sends a client-created workDoneToken for any server; its progress shows as a cancellable task and is retired when the request ends (response, cancel or timeout). A server's TOML can list server-created progress-token prefixes to ignore (ignored-progress-token-prefixes); php.toml uses it for PHPantom 1.1.0, which can leave find_references/goto_implementation progress open after a cancel (PHPantom-dev/phpantom_lsp#603).

Co-authored-by: fenndooscar <[email protected]>
2026-12-01 02:04:13 +08:00
Ivan 4c8c078666 perf(lsp): bound the cache of virtual document text (#7082)
The window-wide cache of lspVirtualDocument results (decompiled classes, library sources, jdt:// documents) kept one entry per document ever shown, hover previews and go-to-definition included, for the window's lifetime. It now keeps the 32 most recently used; an evicted document is fetched again on next use, and a failed fetch is dropped only while it is still the cached one.

Refs #6938

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 02:00:34 +08:00
Ivan e672b14d52 fix(plugins,mcp): stop idle IPC loops in Restricted Mode windows (#7091)
Idle Restricted Mode windows called the backend over 100 times a second. PluginHost::restrict_project announced CommandsChanged even when the project had no plugins to restrict; every window answered with plugin_list, which restricted the untrusted root again. Separately, the MCP editor and problems reporters retried every 300 ms on commands Restricted Mode refuses.

restrict_project now announces only when it restricted something, and the reporters skip untrusted projects and report once trust is granted. Measured over 4 idle windows: invoke calls 115/s -> 0.7/s, CPU per idle minute 12.3 s -> 1.1 s.

Refs #6938

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 01:59:18 +08:00
audichuang c0300f8959 fix(vcs): find a worktree added below the project when its HEAD lands after the watcher's rescan (#7086)
git worktree add writes the worktree's .git file before its gitdir's commondir and HEAD, so a watcher rescan in between found no repository there, and the later .git/worktrees/<id>/HEAD write never triggered another rescan. That HEAD now rescans too while its worktree is unknown and is one a scan would find (Repos::searched, sharing discover's depth, hidden, vendor and skip rules, plus Directory Mappings exclusions).

Co-authored-by: audichuang <[email protected]>
2026-12-01 01:57:06 +08:00
l0ng-ai 11cf9864a1 fix(vcs): guide GitHub HTTPS failures to project account settings (#7061)
A Git Update, Fetch, Push or branch update that fails on an https://github.com remote with "repository not found" or "Authentication failed" now checks the GitHub CLI accounts. When several are signed in, the original Git error is kept and a hint says the effective account may lack access, with a GitHub Settings action that opens the project-scoped account selector. Nothing switches gh's global account, rewrites remotes or retries the operation; other hosts, SSH remotes and network errors are left as they were.
2026-12-01 01:52:43 +08:00
l0ng-ai 04a4d98d68 fix(vcs): open the Log User filter without waiting for every author (#7095)
The Log's User filter popup waited for git log --all to list every author before opening, which takes 8-10 s on a history of 500K+ commits, on every open.

The popup now opens at once with the authors already known (loaded commits plus each repository's last full list). The full list is fetched in the background, reusing a running fetch and a list younger than five minutes, and only Select..., which shows every author, waits for it.

Fixes #7064
2026-12-01 01:44:26 +08:00
l0ng-ai 9a984f64a3 fix(vcs): keep No Merges fast on long pull-request histories (#7094)
With No Merges on, a hidden commit's graph parents are projected onto its nearest shown ancestors. On a pull-request history (M_k = merge(M_k-1, F_k)) each hidden merge projected onto all older features, because the projection of M_k-1 was kept next to F_k although M_k-1 is F_k's own parent. The lists grew with every merge and the first page walked the whole history, so a 500K-commit repository never finished loading.

Before projecting through a hidden commit, parents that are ancestors of another of its parents are dropped (a bounded walk that keeps the parent when unsure). The graph builder and the filtered log view (path, date and author filters share the projection) both apply it.

Fixes #7063
2026-12-01 01:39:39 +08:00
l0ng-ai e35a607556 fix(welcome): expand JetBrains path variables without re-checking the base (#7092)
expand_jetbrains_path re-checked is_absolute after joining a path variable onto the home or IDE config folder. Those folders are already absolute; on Windows the unit test's /home/me home has no drive, so recent::tests::expands_jetbrains_path_variables failed on Rust (windows-latest) since #6979. Only a path without a variable is checked now.
2026-12-01 01:32:47 +08:00
Muuтаmuutot 3fa990fce2 feat(editor): add Render All Doc Comments (#7066)
Adds the Render All Doc Comments action (IDEA id ToggleRenderedDocPresentationForAll, no default shortcut). It flips Editor > Appearance > Render documentation comments globally and clears every open document's per-file rendered-docs override, so all editors follow the new default.

Co-authored-by: muutot <[email protected]>
2026-12-01 01:31:03 +08:00
RuyimgByCN 11e520dedb feat(project-tree): add "Add as Library…" for JARs and library directories (#7077)
Right-clicking a .jar or a folder of jars (such as WEB-INF/lib) in the Project view, or running it from Find Action, opens a Create Library dialog (name, scope, classes) that appends the library to projectStructure.libraries. Collapsed folders are probed briefly before the menu opens. Registered library folders get the library icon and an Open Library Settings entry instead of a duplicate add, External Libraries refreshes when jars inside them are added or removed, and manifest-free Java projects with libraries show the project JDK there.

Library class entries (jar globs, root-relative paths) are parsed once in platform/languageSettings for both the action and the refresh.

Closes #7051

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 01:24:16 +08:00
Chris-young42таChris-young42 a0c0b69b4a feat(project-structure): add search and batch folder marking (#7069)
Project Structure gets a search field: sections and module tabs are filtered by English or translated labels, the matching section or Sources/Paths tab opens, and staged edits are kept while searching.

The module folder tree now allows Shift and Ctrl/Cmd selection, and the Mark as buttons mark or unmark all selected folders at once (pressed only when every selected folder already has that role). Long paths in the marked folders pane wrap in narrow windows.

Co-authored-by: Chris-young42 <[email protected]>
2026-12-01 01:14:04 +08:00
RuyimgByCN b89128649f fix(project-structure): show full content root tooltips and enable custom test output path (#7076)
Long content root and library paths in Project Structure were truncated with only a native title attribute, which the tooltip host skips and WKWebView suppresses; they now use verbatim tooltips, and the module Sources tree scrolls horizontally.

Test output path was always disabled, although the builder already compiles tests into the module's testCompilerOutput. It is now editable for a root module not managed by Maven or Gradle. Browse dialogs for output paths resolve relative values against the project root.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 01:08:10 +08:00
RuyimgByCN 9973cad74c fix(java): expand JAR directories in Project Structure libraries (#7074)
A Project Structure library whose class root is a folder of jars (such as WebRoot/WEB-INF/lib) was passed through as a bare folder, so jdtls, javac, artifact layouts, External Libraries and the Java launch classpath all missed its jars.

Folder roots and dir/*.jar, dir/**/*.jar globs now expand consistently: jdtls gets a **/*.jar glob, javac gets <dir>/* per folder holding jars, and artifacts, External Libraries and launch classpaths get the individual jars. A folder without jars stays a class folder. The jar walk and glob parsing are shared from ide-core, and the class-root expansion from ide_sdk::libraries::library_class_paths.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 01:02:29 +08:00
RuyimgByCN 8cb7a2fe06 fix(tomcat): keep Project Structure WAR and exploded artifacts across prepare (#7073)
Launching Tomcat with a Project Structure artifact in a project without Maven or Gradle failed with 'The built WAR artifact does not exist': the WAR was written inside Tomcat's runtime directory, which tomcat::prepare deletes and recreates. Project Structure artifacts are now built to their configured output (compile::artifact_file), exploded artifacts are laid out directly without packing and unpacking a WAR, Tomcat deploys a recorded exploded directory as is, and the artifact list falls back to Project Structure web artifacts when there is no build tool. Refs #404.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 00:57:16 +08:00
faysouтаfaysou 5d867d7d2d fix(markdown): preview Git repository versions (#7067)
Open Repository Version opened Markdown in a read-only tab that skipped the Markdown wrapper, so a committed README had no preview. Editor wrappers can now match virtual documents (matchesVirtual), and the Markdown wrapper matches Git revisions of Markdown files: those tabs get Editor Only, Editor and Preview and Preview Only, with the preview rendering the committed text and the source staying read-only.

Co-authored-by: faysou <[email protected]>
2026-12-01 00:54:08 +08:00
Ivan 70f6678271 perf(memory): release freed heap pages after closing a project or tabs (#7072)
Closing a project or a batch of documents now calls release_free_pages once, 2 s after the last close, on a background thread. On macOS the freed pages are already reclaimable, so the footprint change is within noise; on Linux malloc_trim can return pages glibc would keep resident (not measured).

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 00:51:07 +08:00
lleviathe 530388a79d fix(mcp): pick the innermost project across windows and background projects (#7085)
A call naming a folder went to the innermost project open in a window, and the background policy was asked only for folders outside every open project. With a window on a parent folder, a call naming a nested trusted repository served in the background read the parent's files instead, so the answer depended on which windows were open. resolve_project now also asks the policy for a path below the innermost open root, passing that root so only folders strictly inside it are considered and nothing else is looked up on disk. A path at an open root, or one no nested folder serves, stays with the window and loads nothing; a remote window's root answers nothing locally. The MCP guide (English and Chinese) describes how the project is picked. Closes #7040.

Co-authored-by: lleviathe <[email protected]>
2026-12-01 00:49:59 +08:00
Bake Yam 98cb85003a fix(notebook): let commands find a cell document (#7071)
A notebook's cells are documents of the language servers only, never of the editor's document table, so commands that read that table failed on a cell: Reformat Code answered 'document is not open' and Alt+Enter offered no import for an installed package's name. Formatting and the Python import quick fix now fall back to the LSP manager's cell buffer (new LspManager::cell_text), and the formatter is given the notebook path with a .py extension so Ruff parses the cell as Python rather than notebook JSON. Part of #5846 (items 1 and 3).

Co-authored-by: Renjiankang <[email protected]>
2026-12-01 00:46:37 +08:00
l0ng-ai dfae46868c test(lsp): compare server roots without cloning into a slice (#7087)
The Xcode C-family test added in #7023 built a one-element array by cloning the root, which clippy's cloned_ref_to_slice_refs rejects under -D warnings, so the three Rust CI jobs failed to compile ide-lsp's mock_server test. It now compares against std::slice::from_ref.
2026-12-01 00:45:21 +08:00
faysouтаfaysou 635da15486 fix(markdown): follow explicit preview anchors (#7070)
A Markdown link such as #ref-1 can point to an explicit HTML id in the document, but the preview only looked for the generated heading id, so a citation link jumped to a heading with the same slug or nowhere. The preview now tries the exact id first and falls back to the generated heading id.

Co-authored-by: faysou <[email protected]>
2026-11-30 23:56:35 +08:00
lleviathe 249d0526f0 fix(settings): fill the row with the background folders list (#7078)
In Settings › Agents › IDE MCP Server › Background Projects the Folders list was 116 px wide while empty and grew with its longest path up to 480 px. The wrapper that turns it off in mode Off kept it from being the row's flex item; the wrapper now fills the row and the list passes fullWidth like the other stacked lists.

Co-authored-by: lleviathe <[email protected]>
2026-11-30 23:55:06 +08:00
Игорь Тихомиров 181bbdfdc2 fix(remote): clear background tasks when the backend changes (#7068)
After a remote backend disconnected or was replaced, its progress rows stayed in the window because the old connection could no longer deliver completion events. When the connection is lost or the session changes, the window now drops the backend's numeric task IDs, their pending delayed updates and the indexing row, and keeps client-side tasks.

Co-authored-by: fenndooscar <[email protected]>
2026-11-30 23:53:33 +08:00
l0ng-ai c7172184ad feat(editor): choose the styles Cycle Identifier Case goes through (#7081)
Cycle Identifier Case always went through all five styles. Settings › Editor › General › Smart Keys gets a Cycle Identifier Case group with one checkbox per style (snake_case, SCREAMING_SNAKE_CASE, kebab-case, camelCase, PascalCase), all on by default. The action skips the styles that are off and keeps starting from the style the name is written in, even when that one is off. Fixes #6972.
2026-11-30 23:50:27 +08:00
187 змінених файлів з 6197 додано та 543 видалено

No files matched your search

+4 -1
Переглянути файл
@@ -152,7 +152,10 @@
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"excludeFiles": ["e2e/**"],
"rules": {
"no-await-in-loop": "error"
"no-await-in-loop": "error",
"react/no-array-index-key": "error",
"react/jsx-no-constructed-context-values": "error",
"react/no-object-type-as-default-prop": "error"
}
}
]
+102 -24
Переглянути файл
@@ -4,7 +4,8 @@
//! same way into the test output, which also sees the production classes.
use super::*;
use ide_core::settings::{
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings,
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, jar_files,
split_jar_glob,
};
use std::fs;
@@ -104,13 +105,17 @@ fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Ve
module_deps.iter().find(|d| d.kind == "library" && d.target == lib.name).map_or(lib.scope, |d| d.scope);
if wanted(scope) {
for class in &lib.classes {
add(class_entry(root, class));
for entry in class_entries(root, class) {
add(entry);
}
}
}
}
for dep in module_deps.iter().filter(|d| d.kind == "library" && wanted(d.scope)) {
if !ps.libraries.iter().any(|l| l.name == dep.target) && !dep.target.trim().is_empty() {
add(class_entry(root, &dep.target));
for entry in class_entries(root, &dep.target) {
add(entry);
}
}
}
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
@@ -133,29 +138,50 @@ fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf {
root.join(dir)
}
/// The class archives and folders of a library path (`lib/*.jar` lists the folder's jars).
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
let entry = class_entry(root, value);
match entry.strip_suffix('*') {
Some(dir) => {
let mut jars: Vec<PathBuf> = fs::read_dir(dir)
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jar")).collect())
.unwrap_or_default();
jars.sort();
jars
/// The folders under `dir` (itself included) that hold `.jar` files, in walk order.
fn jar_dirs(dir: &Path) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
for jar in jar_files(dir, true) {
if let Some(parent) = jar.parent().filter(|p| !dirs.iter().any(|d| d == p)) {
dirs.push(parent.to_path_buf());
}
None => vec![PathBuf::from(entry)],
}
dirs
}
/// A classpath entry for a library path: a folder of jars (`lib/*`) stays a wildcard javac expands.
fn class_entry(root: &Path, value: &str) -> String {
let path = root.join(value.trim());
let text = path.to_string_lossy().into_owned();
if text.ends_with("/*.jar") || text.ends_with("\\*.jar") {
return text[..text.len() - 4].to_owned();
/// The class archives and folders of a library path (`lib/*.jar`, `lib/**/*.jar`, or a folder
/// containing JARs expands to those JARs; a folder without JARs stays a class folder).
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
if let Some((base, recursive)) = split_jar_glob(value) {
return jar_files(&root.join(base), recursive);
}
text
let path = root.join(value.trim());
if path.is_dir() {
let jars = jar_files(&path, true);
if !jars.is_empty() {
return jars;
}
}
vec![path]
}
/// Classpath entries for a library path: `lib/*.jar` stays `lib/*` for javac to expand; a
/// directory containing JARs expands to `<dir>/*` per folder holding JARs.
fn class_entries(root: &Path, value: &str) -> Vec<String> {
let wildcard = |dir: &Path| format!("{}{}*", dir.to_string_lossy(), std::path::MAIN_SEPARATOR);
if let Some((base, recursive)) = split_jar_glob(value) {
let dir = root.join(base);
let dirs = if recursive { jar_dirs(&dir) } else { Vec::new() };
return if dirs.is_empty() { vec![wildcard(&dir)] } else { dirs.iter().map(|d| wildcard(d)).collect() };
}
let path = root.join(value.trim());
if path.is_dir() {
let dirs = jar_dirs(&path);
if !dirs.is_empty() {
return dirs.iter().map(|d| wildcard(d)).collect();
}
}
vec![path.to_string_lossy().into_owned()]
}
fn classpath(entries: &[String]) -> String {
@@ -440,7 +466,10 @@ pub fn structure_web_artifacts(ps: &ProjectStructureSettings) -> Vec<&ArtifactCo
ps.artifacts.iter().filter(|a| matches!(a.kind, ArtifactKind::War | ArtifactKind::WarExploded)).collect()
}
/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first.
/// A build of `artifact` for Tomcat's deployment, compiling production classes first.
/// When `war` is `Some`, packs a WAR archive at that path; when `None`, writes to the
/// artifact's own output (`artifact_file`: a `.war` archive for `War`, or the exploded
/// directory for `WarExploded`).
#[allow(clippy::too_many_arguments)]
pub fn structure_war_plan(
root: &Path,
@@ -449,7 +478,7 @@ pub fn structure_war_plan(
jdk: Option<&StructureJdk>,
language_level: &str,
artifact: &ArtifactConfig,
war: &Path,
war: Option<&Path>,
cache: &Path,
) -> IdeResult<BuildPlan> {
let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)?
@@ -459,7 +488,7 @@ pub fn structure_war_plan(
plan.steps.retain(|s| !s.args.iter().any(|a| a.ends_with("test.args")));
plan.steps
.retain(|s| !matches!(&s.action, Some((Action::CopyResources { to, .. }, _)) if !to.starts_with(&main_out)));
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache));
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, war, cache));
plan.title = artifact.name.clone();
Ok(plan)
}
@@ -1144,4 +1173,53 @@ mod tests {
bad_result.messages
);
}
#[test]
fn expands_jar_directory_libraries_for_javac_and_artifacts() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("app");
let cache = tmp.path().join("cache");
write(&root.join("src/A.java"), "class A {}");
write(&root.join("WebRoot/WEB-INF/lib/gson.jar"), "jar1");
write(&root.join("WebRoot/WEB-INF/lib/sub/extra.jar"), "jar2");
fs::create_dir_all(root.join("plain-classes")).unwrap();
write(&root.join("plain-classes/Helper.class"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary {
name: "web-libs".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
..Default::default()
},
ProjectLibrary { name: "classes".into(), classes: vec!["plain-classes".into()], ..Default::default() },
],
artifacts: vec![ArtifactConfig {
name: "app:war exploded".into(),
kind: ArtifactKind::WarExploded,
module: ".".into(),
output_directory: "out/artifacts/app_war_exploded".into(),
main_class: String::new(),
include_libraries: vec!["web-libs".into()],
}],
..Default::default()
};
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Artifacts, &cache).unwrap().unwrap();
let javac = &plan.steps[0];
let cp = &javac.args[javac.args.iter().position(|a| a == "-cp").unwrap() + 1];
let sep = std::path::MAIN_SEPARATOR;
assert!(cp.contains(&format!("lib{sep}*")), "expected JAR dir wildcard in cp: {cp}");
assert!(cp.contains(&format!("sub{sep}*")), "expected nested JAR dir wildcard in cp: {cp}");
assert!(cp.contains("plain-classes") && !cp.contains(&format!("plain-classes{sep}*")), "cp={cp}");
let layout = plan.steps.iter().find_map(|s| match &s.action {
Some((Action::Layout { entries, .. }, _)) => Some(entries),
_ => None,
});
let entries = layout.expect("layout step");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/gson.jar")), "{entries:?}");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/extra.jar")), "{entries:?}");
assert!(!entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/lib")), "{entries:?}");
}
}
+25
Переглянути файл
@@ -314,6 +314,30 @@ pub struct SmartKeysSettings {
pub insert_doc_stub: bool,
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
pub backspace_unindent: String,
/// The styles Cycle Identifier Case goes through.
pub cycle_case: CycleCaseSettings,
}
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CycleCaseSettings {
/// `snake_case`
pub snake: bool,
/// `SCREAMING_SNAKE_CASE`
pub screaming: bool,
/// `kebab-case`
pub kebab: bool,
/// `camelCase`
pub camel: bool,
/// `PascalCase`
pub pascal: bool,
}
impl Default for CycleCaseSettings {
fn default() -> Self {
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
}
}
impl Default for SmartKeysSettings {
@@ -335,6 +359,7 @@ impl Default for SmartKeysSettings {
smart_indent: true,
insert_doc_stub: true,
backspace_unindent: "autoindent".into(),
cycle_case: CycleCaseSettings::default(),
}
}
}
+72
Переглянути файл
@@ -1,5 +1,35 @@
//! Returning freed heap pages to the OS.
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// Like [`release_free_pages`], on a background thread once 2 s pass without another call:
/// closing a project or a batch of tabs frees memory in bursts, released once.
pub fn release_free_pages_soon() {
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
debounce(&DUE, Duration::from_secs(2), release_free_pages);
}
/// Runs `run` on a background thread once `delay` passes after the last call.
fn debounce(due: &'static Mutex<Option<Instant>>, delay: Duration, run: fn()) {
let idle = due.lock().unwrap().replace(Instant::now() + delay).is_none();
if idle {
std::thread::spawn(move || {
loop {
let mut slot = due.lock().unwrap();
let left = slot.map_or(Duration::ZERO, |at| at.saturating_duration_since(Instant::now()));
if left.is_zero() {
*slot = None;
drop(slot);
return run();
}
drop(slot);
std::thread::sleep(left);
}
});
}
}
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
/// short-lived allocations (a full index scan); until then they still count towards the
/// process's memory footprint.
@@ -18,3 +48,45 @@ pub fn release_free_pages() {
libc::malloc_trim(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
static RUNS: AtomicUsize = AtomicUsize::new(0);
fn count() {
RUNS.fetch_add(1, SeqCst);
}
#[test]
fn a_burst_of_calls_runs_once_after_the_delay() {
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
let delay = Duration::from_millis(500);
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
for _ in 0..5 {
debounce(&DUE, delay, count);
let now = Instant::now();
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
last = Some(now);
std::thread::sleep(Duration::from_millis(20));
}
if last.unwrap().elapsed() < delay {
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
}
let deadline = Instant::now() + Duration::from_secs(10);
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
// A second run would come within another delay.
std::thread::sleep(delay);
if widest_gap < delay {
assert_eq!(RUNS.load(SeqCst), 1);
} else {
assert!(RUNS.load(SeqCst) >= 1);
}
release_free_pages_soon();
}
}
+7 -1
Переглянути файл
@@ -203,6 +203,9 @@ pub enum RunTargetKind {
Docker,
/// A new container of a Compose service (`docker compose run --rm`).
Compose,
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
/// through `/mnt/<drive>`.
Wsl,
}
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
@@ -215,7 +218,8 @@ pub struct RunTarget {
pub name: String,
/// [`SshConfiguration::id`] (SSH).
pub ssh_config: String,
/// Remote folder the project is synchronised to and run from (SSH).
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
/// path, empty = its `/mnt/<drive>` path (WSL).
pub project_root: String,
/// Upload changed project files before each run (SSH).
pub sync_before_run: bool,
@@ -241,6 +245,8 @@ pub struct RunTarget {
pub run_options: String,
/// Run as the image's user instead of the project folder's owner (Linux).
pub image_user: bool,
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
pub distro: String,
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
+31
Переглянути файл
@@ -2054,6 +2054,37 @@ pub struct ProjectLibrary {
pub scope: DependencyScope,
}
/// A library class entry written as a jar glob: `dir/*.jar` → `(dir, false)`, `dir/**/*.jar` → `(dir, true)`.
pub fn split_jar_glob(entry: &str) -> Option<(&str, bool)> {
let entry = entry.trim();
if let Some(base) = entry.strip_suffix("/**/*.jar").or_else(|| entry.strip_suffix(r"\**\*.jar")) {
return Some((base, true));
}
entry.strip_suffix("/*.jar").or_else(|| entry.strip_suffix(r"\*.jar")).map(|base| (base, false))
}
/// The `.jar` files in `dir` (and its subfolders when `recursive`), sorted by name per folder.
pub fn jar_files(dir: &std::path::Path, recursive: bool) -> Vec<std::path::PathBuf> {
fn walk(dir: &std::path::Path, recursive: bool, out: &mut Vec<std::path::PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
match entry.file_type() {
Ok(t) if t.is_dir() && recursive => walk(&path, true, out),
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")) => {
out.push(path)
}
_ => {}
}
}
}
let mut out = Vec::new();
walk(dir, recursive, &mut out);
out
}
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
+92
Переглянути файл
@@ -35,6 +35,24 @@ pub fn parse(path: &Path) -> Option<WslPath> {
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
}
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
/// other network shares and relative paths.
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
if let Some(w) = parse(path) {
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
}
let s = path.to_string_lossy().replace('\\', "/");
let s = s.strip_prefix("//?/").unwrap_or(&s);
let mut chars = s.chars();
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
let rest = chars.as_str().strip_prefix(':')?;
if !(rest.is_empty() || rest.starts_with('/')) {
return None;
}
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
}
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
pub fn is_valid_distro(name: &str) -> bool {
@@ -86,6 +104,57 @@ pub fn list_distros() -> Vec<String> {
Vec::new()
}
/// Where this machine reads `distro`'s file system.
pub fn share_root(distro: &str) -> std::path::PathBuf {
format!(r"\\wsl.localhost\{distro}").into()
}
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
pub fn path_parts(linux: &str) -> Vec<&str> {
let mut parts: Vec<&str> = Vec::new();
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
if c == ".." {
parts.pop();
} else {
parts.push(c);
}
}
parts
}
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
/// within `linux`, never above the drive or the share.
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
let parts = path_parts(linux);
let base = match parts.as_slice() {
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
return parts[2..].iter().fold(base, |p, c| p.join(c));
}
_ => share_root(distro),
};
parts.iter().fold(base, |p, c| p.join(c))
}
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
use crate::cli_process::{CliTool, Decoding};
if !is_valid_distro(distro) {
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
}
let mut cmd = std::process::Command::new(EXE);
cmd.args(["-d", distro, "--exec"]).args(args);
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
if out.success {
return Ok(stdout);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -103,6 +172,21 @@ mod tests {
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
}
#[test]
fn windows_paths_map_onto_the_distro() {
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
assert_eq!(l(r"\\server\share\a"), None);
assert_eq!(l(r"C:relative"), None);
assert_eq!(l("app"), None);
assert_eq!(l("/home/me"), None);
}
#[test]
fn distro_root_and_foreign_paths() {
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
@@ -127,6 +211,14 @@ mod tests {
assert!(parse_distro_list(b"").is_empty());
}
#[test]
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
use std::path::PathBuf;
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
}
#[test]
fn distro_names_cannot_smuggle_options_or_paths() {
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
+27 -2
Переглянути файл
@@ -391,9 +391,12 @@ impl Manifest {
if !self.capabilities.reasons.is_empty() {
self.needs_api("`capabilities.reasons`", 19)?;
}
let derived = self.derived_capabilities();
for (key, text) in &self.capabilities.reasons {
if !self.capabilities.all().any(|c| c.to_string() == *key) {
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
if !self.capabilities.all().chain(&derived).any(|c| c.to_string() == *key) {
return Err(format!(
"capabilities.reasons: {key:?} is not under `required` or `optional`, nor comes from a contribution"
));
}
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
return Err(format!(
@@ -522,6 +525,17 @@ impl Manifest {
Ok(())
}
/// Capabilities the plugin's contributions bring without being listed under `[capabilities]`:
/// `java.agent` from `[[contributes.javaAgents]]`, `project.read` from
/// `[[contributes.documentIndexers]]` (the extension points in `ide-host` add them to the grant).
pub fn derived_capabilities(&self) -> Vec<Capability> {
[("javaAgents", Capability::JavaAgent), ("documentIndexers", Capability::ProjectRead)]
.into_iter()
.filter(|(point, _)| self.contributes.contains_key(*point))
.map(|(_, cap)| cap)
.collect()
}
/// The declarations of one extension point: `[[contributes.x]]` gives
/// several, `[contributes.x]` one.
pub fn declarations(&self, point: &str) -> Vec<toml::Value> {
@@ -843,6 +857,17 @@ required = [\"lsp:phoxite\"]
assert!(err(&src(&long)).contains("1 to 500 characters"));
}
#[test]
fn capability_reasons_explain_capabilities_that_contributions_bring() {
let src = |rest: &str| format!("{}{rest}", BASE.replace("^1.2", "^1.19"));
let reason = "[capabilities.reasons]\n\"java.agent\" = \"Captures the SQL MyBatis runs.\"\n";
let agent = "[[contributes.javaAgents]]\npath = \"agent.jar\"\n";
let m = Manifest::parse(&src(&format!("{reason}{agent}"))).unwrap();
assert_eq!(m.derived_capabilities(), [Capability::JavaAgent]);
assert_eq!(m.capabilities.reason(&Capability::JavaAgent), Some("Captures the SQL MyBatis runs."));
assert!(err(&src(reason)).contains("nor comes from a contribution"), "no javaAgents declaration");
}
#[test]
fn the_clipboard_read_capability_needs_api_1_11() {
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
+37 -8
Переглянути файл
@@ -448,18 +448,39 @@ pub async fn format(
options: FormatOptions,
) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
let source = FormatSource {
path: snap.path,
language: snap.language,
text: snap.text,
doc: Some(doc),
version: snap.version,
read_only: snap.read_only,
// A notebook cell is a document of the language servers only: `documents` holds what the
// editor opened, so ⌥⌘L in a cell used to answer "document DocId#N is not open".
let source = match project.documents.snapshot(doc) {
Ok(snap) => FormatSource {
path: snap.path,
language: snap.language,
text: snap.text,
doc: Some(doc),
version: snap.version,
read_only: snap.read_only,
},
Err(e) => match project.lsp.cell_text(doc) {
Some(cell) => FormatSource {
path: cell_script_path(&cell.path).into(),
language: cell.language,
text: cell.text,
doc: Some(doc),
version: cell.version,
read_only: false,
},
None => return Err(e),
},
};
format_source(host, window, &project, source, range, options).await
}
/// The file name a formatter is given for a cell's text. It only picks the language and the
/// settings: the text arrives on stdin. The notebook's own `.ipynb` would make Ruff parse the
/// cell as notebook JSON instead of Python.
fn cell_script_path(notebook: &Path) -> PathBuf {
notebook.with_extension("py")
}
/// Format a separate snapshot using the file's language, settings and formatter.
pub async fn format_text(
host: &Host,
@@ -1385,6 +1406,14 @@ mod tests {
assert!(project_configured(Oxfmt, &root.join("c/src/app.ts")));
}
#[test]
fn a_cell_is_formatted_as_python_rather_than_as_notebook_json() {
// Ruff reads the extension of `--stdin-filename` to decide what the text is; `.ipynb`
// made it expect notebook JSON and fail on the cell's source.
assert_eq!(cell_script_path(Path::new("/p/notebooks/a.ipynb")), Path::new("/p/notebooks/a.py"));
assert_eq!(cell_script_path(Path::new("/p/a.b.ipynb")), Path::new("/p/a.b.py"));
}
#[test]
fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() {
let dir = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -551,6 +551,8 @@ impl Host {
if let Some(retired) = retired {
let _ = retired.join();
}
// The project's buffers, index and caches are dropped: hand their pages back.
ide_core::memory::release_free_pages_soon();
})
}
+7 -7
Переглянути файл
@@ -172,15 +172,15 @@ impl Policy {
})
}
fn resolve(&self, path: &Path) -> Option<PathBuf> {
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path)
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path, within)
}
}
/// The root of the project that serves `path` in the background under the current
/// settings and trust decisions. Opens nothing.
pub(crate) fn serving_root(host: &Host, path: &Path) -> Option<PathBuf> {
Policy::current(host)?.resolve(path)
/// settings and trust decisions; with `within`, only a root strictly inside it. Opens nothing.
pub(crate) fn serving_root(host: &Host, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
Policy::current(host)?.resolve(path, within)
}
/// How long a project may stay idle; `None` when `minutes` is 0 (never unloaded).
@@ -283,7 +283,7 @@ impl BackgroundProjects {
state.opening = Some(root.to_path_buf());
Opening(self)
};
if serving_root(host, root).as_deref() != Some(root) {
if serving_root(host, root, None).as_deref() != Some(root) {
return Err(IdeError::unavailable(format!("{} is not served in the background", root.display())));
}
let limit = project_limit(host.global_settings.effective().mcp_server.background_project_limit);
@@ -463,7 +463,7 @@ impl Host {
}
let policy = Policy::current(self);
for root in roots {
if policy.as_ref().and_then(|policy| policy.resolve(&root)).as_deref() != Some(&root) {
if policy.as_ref().and_then(|policy| policy.resolve(&root, None)).as_deref() != Some(&root) {
self.mcp_background.detach(self, &root, None);
}
}
+59 -13
Переглянути файл
@@ -10,7 +10,9 @@ use std::path::{Path, PathBuf};
/// folders containing it and, in `Trusted` mode, of the trusted projects, the trusted recent
/// projects and the nearest trusted folder with a project marker. `None` when the mode is
/// `Off`, when `path` is relative or missing, and when no folder qualifies. Listed and
/// recent folders that are gone or not absolute paths are skipped.
/// recent folders that are gone or not absolute paths are skipped. With `within` (the root
/// of the open project containing `path`) only folders strictly inside it count, and the
/// others aren't looked up on disk.
pub(crate) fn resolve(
mode: McpBackgroundProjects,
listed: &[PathBuf],
@@ -18,6 +20,7 @@ pub(crate) fn resolve(
recents: &[PathBuf],
home: Option<&Path>,
path: &Path,
within: Option<&Path>,
) -> Option<PathBuf> {
let by_trust = match mode {
McpBackgroundProjects::Off => return None,
@@ -28,23 +31,37 @@ pub(crate) fn resolve(
return None;
}
let path = dunce::canonicalize(path).ok()?;
let within = within.map(|root| (root, dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf())));
let open = within.as_ref().map(|(_, root)| root.as_path());
// Only folders strictly inside `within` count. An entry is checked by its text before it
// is canonicalized, so folders elsewhere (a network mount among them) aren't touched; one
// that reaches inside through a link from elsewhere is left out.
let inside = |entry: &Path, canonical: bool| {
within.as_ref().is_none_or(|(raw, root)| {
(entry.starts_with(root) && entry != root) || (!canonical && entry.starts_with(raw) && entry != *raw)
})
};
// A relative entry would be read against the working directory, which says nothing
// about the user's folders (`/` for an app started from the Finder).
let existing = |entry: &PathBuf| entry.is_absolute().then(|| dunce::canonicalize(entry).ok()).flatten();
let existing = |entry: &PathBuf| {
(entry.is_absolute() && inside(entry, false)).then(|| dunce::canonicalize(entry).ok()).flatten()
};
// A listed folder serves its subtree whether or not it is trusted: it opens restricted then.
let mut candidates: Vec<PathBuf> = listed.iter().filter_map(existing).collect();
if by_trust {
candidates.extend(decisions.projects.iter().filter(|p| trusted_here(decisions, p)).cloned());
let projects = decisions.projects.iter().filter(|p| inside(p, true));
candidates.extend(projects.filter(|p| trusted_here(decisions, p)).cloned());
// Remote projects are recorded as locations (`ssh://…`), not as folders of this machine.
let local = recents.iter().filter(|p| !p.to_string_lossy().contains("://"));
candidates.extend(local.filter_map(existing).filter(|p| trusted_here(decisions, p)));
let home = home.map(|h| dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf()));
// A trusted location and the home folder hold projects; neither is one.
candidates
.extend(marker_root(&path).filter(|a| {
.extend(marker_root(&path, open).filter(|a| {
trusted_here(decisions, a) && !decisions.locations.contains(a) && home.as_ref() != Some(a)
}));
}
candidates.retain(|candidate| inside(candidate, true));
innermost(&candidates, &path).cloned()
}
@@ -64,9 +81,10 @@ fn trusted_here(decisions: &TrustDecisions, root: &Path) -> bool {
/// The first ancestor of `path`, itself included, that looks like a project: it holds an
/// `.openidea` folder, or a `.git` or `.jj` entry (a linked worktree's `.git` is a file).
fn marker_root(path: &Path) -> Option<PathBuf> {
/// The search stops short of `within`.
fn marker_root(path: &Path, within: Option<&Path>) -> Option<PathBuf> {
let marked = |dir: &&Path| dir.join(".openidea").is_dir() || dir.join(".git").exists() || dir.join(".jj").exists();
path.ancestors().find(marked).map(Path::to_path_buf)
path.ancestors().take_while(|dir| Some(*dir) != within).find(marked).map(Path::to_path_buf)
}
#[cfg(test)]
@@ -159,7 +177,35 @@ mod tests {
restricted: paths(restricted),
};
let home = base.join("home");
let found = resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path));
let found =
resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path), None);
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
}
}
#[test]
fn inside_an_open_project_only_a_folder_below_its_root_serves_a_path() {
let (_tmp, base) = tree();
let at = |folders: &[&str]| folders.iter().map(|folder| base.join(folder)).collect::<Vec<_>>();
let trusted = |projects: &[&str], locations: &[&str]| TrustDecisions {
projects: at(projects),
locations: at(locations),
..Default::default()
};
let within = base.join("code/app");
let (none, root, location) = (trusted(&[], &[]), trusted(&["code/app"], &[]), trusted(&[], &["code"]));
let (src, nested) = ("code/app/src", "code/app/.wt/feature");
let below = trusted(&[nested], &[]);
let nested_src = "code/app/.wt/feature/src";
for (what, mode, listed, decisions, path, expected) in [
("a listed folder below the root", Listed, &[src][..], &none, src, Some(src)),
("the listed root and a listed folder around it", Listed, &["code", "code/app"], &none, src, None),
("the trusted root", Trusted, &[], &root, src, None),
("the root's own marker", Trusted, &[], &location, src, None),
("a repository below the root", Trusted, &[], &location, nested_src, Some(nested)),
("a trusted project below the root", Trusted, &[], &below, nested_src, Some(nested)),
] {
let found = resolve(mode, &at(listed), decisions, &[], None, &base.join(path), Some(&within));
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
}
}
@@ -170,7 +216,7 @@ mod tests {
let listed = [base.join("code/app"), PathBuf::from("code/app"), PathBuf::from(".")];
let none = TrustDecisions::default();
for path in ["code/app/src", ".", "src"] {
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path)), None, "{path}");
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path), None), None, "{path}");
}
}
@@ -188,7 +234,7 @@ mod tests {
("the same folder listed by its full path", Listed, absolute, &none, &[][..], Some(&here)),
("the same folder recent by its full path", Trusted, &[][..], &around, absolute, Some(&here)),
] {
assert_eq!(resolve(mode, listed, decisions, recents, None, &here).as_ref(), expected, "{what}");
assert_eq!(resolve(mode, listed, decisions, recents, None, &here, None).as_ref(), expected, "{what}");
}
}
@@ -200,13 +246,13 @@ mod tests {
let none = TrustDecisions::default();
// Listed by the link, asked for by the real path, and the other way round (`/tmp` and `/private/tmp`).
for (listed, path) in [("link/app", "code/app/src"), ("code/app", "link/app/src"), ("link/app", "link/app")] {
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path));
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path), None);
assert_eq!(found, Some(base.join("code/app")), "{listed} for {path}");
}
let trusted = TrustDecisions { locations: vec![base.join("code")], ..Default::default() };
let recent = [base.join("link/plain")];
assert_eq!(
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src")),
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src"), None),
Some(base.join("code/plain"))
);
}
@@ -219,10 +265,10 @@ mod tests {
std::fs::create_dir_all(base.join("ssh:/box/app/src")).unwrap();
let recent = [PathBuf::from(format!("{}/ssh://box/app", base.display()))];
let trusted = TrustDecisions { locations: vec![base.clone()], ..Default::default() };
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src")), None);
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src"), None), None);
let local = [base.join("ssh:/box/app")];
assert_eq!(
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src")),
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src"), None),
Some(base.join("ssh:/box/app"))
);
}
+3 -3
Переглянути файл
@@ -708,7 +708,7 @@ async fn a_host_that_serves_none_refuses_every_folder_whatever_the_settings_say(
let root = f.root("inventory");
f.host.mcp_background.serve_none();
let registry = crate::mcp::Registry::new(f.host.clone());
assert_eq!(registry.resolve(&root.join("parts")), None);
assert_eq!(registry.resolve(&root.join("parts"), None), None);
assert_eq!(f.refused("inventory"), format!("{} is not served in the background", root.display()));
assert!(f.loaded().is_empty());
assert!(f.host.projects().is_empty());
@@ -726,11 +726,11 @@ async fn a_call_that_arrives_after_the_server_was_turned_off_opens_nothing() {
assert!(f.loaded().is_empty());
assert!(f.host.projects().is_empty());
let registry = crate::mcp::Registry::new(f.host.clone());
assert_eq!(registry.resolve(&root.join("parts")), None, "no folder is served with the server off");
assert_eq!(registry.resolve(&root.join("parts"), None), None, "no folder is served with the server off");
assert!(registry.tools(&root).is_err());
f.set("enabled", json!(true));
assert_eq!(registry.resolve(&root.join("parts")), Some(root));
assert_eq!(registry.resolve(&root.join("parts"), None), Some(root));
f.open("inventory");
assert_eq!(f.loaded(), ["inventory"]);
}
+8 -3
Переглянути файл
@@ -119,7 +119,7 @@ impl Registry {
if let Some(project) = self.0.mcp_background.project(&self.0, root) {
return Ok(project.is_trusted());
}
if background::serving_root(&self.0, root).as_deref() == Some(root) {
if background::serving_root(&self.0, root, None).as_deref() == Some(root) {
return Ok(self.0.trust.window_trusted(root).unwrap_or(false));
}
Err("project is no longer open".into())
@@ -138,8 +138,13 @@ impl ToolRegistry for Registry {
let attached: Vec<_> = open.iter().flat_map(|p| tool::attached_projects(&p.root)).collect();
open.into_iter().map(|p| p.root.clone()).chain(attached).chain(self.0.mcp_reports.remote_roots()).collect()
}
fn resolve(&self, path: &Path) -> Option<PathBuf> {
background::serving_root(&self.0, path)
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
// A remote window's project holds that host's folders, even where this computer has
// folders at the same paths.
if within.is_some_and(|root| self.0.mcp_reports.remote_roots().iter().any(|remote| remote == root)) {
return None;
}
background::serving_root(&self.0, path, within)
}
fn tools(&self, root: &Path) -> Result<Vec<ide_mcp::Tool>, String> {
let trusted = self.lists_as_trusted(root)?;
+1
Переглянути файл
@@ -26,6 +26,7 @@ pub async fn doc_close(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
project.documents.close(doc);
ide_core::memory::release_free_pages_soon();
Ok(())
})
.await
+24 -2
Переглянути файл
@@ -695,8 +695,10 @@ fn apply_library_classpath(
DependencyScope::Compile | DependencyScope::Runtime => true,
DependencyScope::Test | DependencyScope::Provided => test,
};
lib.classes.iter().filter_map(move |entry| {
ide_sdk::apply::setting_path(root, entry).map(|path| (path.to_string_lossy().into_owned(), allowed))
lib.classes.iter().flat_map(move |entry| {
ide_sdk::libraries::library_class_paths(root, entry)
.into_iter()
.map(move |p| (p.to_string_lossy().into_owned(), allowed))
})
})
.collect();
@@ -1492,6 +1494,26 @@ mod tests {
let mut info = JavaLaunchInfo::default();
apply_library_classpath(&mut info, root.path(), &libraries, false);
assert_eq!(info.class_paths, &paths[..2]);
// Directory library roots expand to the JAR files inside them.
let web_lib = root.path().join("WebRoot/WEB-INF/lib");
std::fs::create_dir_all(&web_lib).unwrap();
let a_jar = web_lib.join("a.jar");
let b_jar = web_lib.join("b.jar");
std::fs::write(&a_jar, b"").unwrap();
std::fs::write(&b_jar, b"").unwrap();
let dir_libs = vec![ProjectLibrary {
name: "web".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
scope: DependencyScope::Compile,
..Default::default()
}];
let mut dir_info = JavaLaunchInfo::default();
apply_library_classpath(&mut dir_info, root.path(), &dir_libs, false);
assert_eq!(
dir_info.class_paths,
vec![a_jar.to_string_lossy().into_owned(), b_jar.to_string_lossy().into_owned()]
);
}
/// JDT LS and our build model spell a module output differently on Windows; the
+11 -3
Переглянути файл
@@ -521,11 +521,19 @@ pub async fn nav_python_library_imports(
let config_dir = host.config_dir.clone();
let token = host.begin_request(request);
let result = blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.language.as_str() != "python" {
// A notebook cell is a document of the language servers only: `documents` holds what the
// editor opened, so ⌥↵ on a cell's unresolved name used to answer nothing.
let (language, path) = match project.documents.snapshot(doc) {
Ok(snap) => (snap.language, snap.path.0),
Err(e) => match project.lsp.cell_text(doc) {
Some(cell) => (cell.language, cell.path),
None => return Err(e),
},
};
if language.as_str() != "python" {
return Ok(Vec::new());
}
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&snap.path)) else {
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&path)) else {
return Ok(Vec::new());
};
let roots = interpreter_site_packages(&python);
+87 -11
Переглянути файл
@@ -448,13 +448,18 @@ async fn start_inner(
}
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind != RunTargetKind::Ssh {
// A local run of the docker CLI: the command is resolved in the container, and
// this machine's toolchains and `PYTHONPATH` don't apply.
let mut config = config;
if ide_run::is_python_kind(&config.kind) {
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
}
let (config, note) = container::prepare(host, &project.root, target, config).await?;
// A local run of the docker CLI or `wsl.exe`: the command is resolved in the
// container or distribution, and this machine's toolchains and `PYTHONPATH` don't apply.
// The settings of the workspace member it belongs to derived its values.
let mut member = config.clone();
let (member_root, member_settings, fallback) = settings_for(host, &project, &mut member)?;
let derived = Derived { root: &member_root, fallback: fallback.as_deref(), settings: &member_settings };
let config = remote_config(&config, derived, &project.root, &super::python::paths(&project));
let (config, note) = if target.kind == RunTargetKind::Wsl {
(container::prepare_wsl(host, &project.root, target, config).await?, None)
} else {
container::prepare(host, &project.root, target, config).await?
};
if let Some(note) = note {
on_output(OutputChunk::System { text: format!("{note}\n") });
}
@@ -462,7 +467,7 @@ async fn start_inner(
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths: Vec::new(),
// A folder on this machine: not in the container.
// A folder on this machine: not in the container or distribution.
ruby_reporter: None,
plots: None,
capture_junit_reports: false,
@@ -864,6 +869,44 @@ pub use commands::*;
mod ownership_tests {
use super::*;
#[cfg(unix)]
#[test]
fn a_remote_run_gets_none_of_this_machines_derived_values() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let venv = root.join(".venv");
std::fs::create_dir_all(venv.join("bin")).unwrap();
std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
std::fs::write(venv.join("bin/python"), "").unwrap();
let mut settings = ide_core::settings::Settings::default();
settings.languages.python.interpreter = venv.join("bin/python").to_string_lossy().into_owned();
let mut config = RunConfig {
id: "app".into(),
name: "app".into(),
kind: "python".into(),
command: "python".into(),
args: vec!["main.py".into()],
cwd: None,
env: [("FOO".to_owned(), "bar".to_owned())].into(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
config.extras.target = Some("wsl".into());
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert!(config.env.contains_key("VIRTUAL_ENV") && config.env.contains_key("PATH"), "{:?}", config.env);
config.env.insert("GOFLAGS".into(), "-mod=mod".into());
let derived = Derived { root, fallback: None, settings: &settings };
let out = remote_config(&config, derived, root, &[root.to_path_buf()]);
assert_eq!(out.env.keys().collect::<Vec<_>>(), ["FOO", "GOFLAGS", "PYTHONPATH"], "{:?}", out.env);
assert_eq!(out.command, "python", "the interpreter is the target's");
assert_eq!(out.extras.target.as_deref(), Some("wsl"));
assert!(has_local_path("/opt/go") && has_local_path("/a/bin:/b/bin"));
assert!(!has_local_path("-mod=mod") && !has_local_path("https://proxy.golang.org,direct"), "kept: not paths");
}
#[cfg(unix)]
#[test]
fn source_roots_go_on_the_container_pythonpath() {
@@ -1062,6 +1105,9 @@ pub async fn run_container_path(
if !path.starts_with('/') {
return Ok(None);
}
if run_target.kind == RunTargetKind::Wsl {
return Ok(ide_remote::wsl::local_file(&path, &run_target, &root).filter(|f| f.is_file()).map(Into::into));
}
let library = snapshots
.and_then(|dir| ide_sdk::container_python::current(&dir))
.and_then(|(dir, snapshot)| ide_sdk::container_python::snapshot_file(&dir, &snapshot, &path));
@@ -1074,9 +1120,39 @@ pub async fn run_container_path(
.await
}
/// The project's source roots on `PYTHONPATH` in a container, as a local run gets them:
/// they are mounted with the project, and `container::prepare` maps their paths. The
/// container's separator is `:`, whatever this machine's is.
/// `config` for a container or WSL distribution: without what settings derived from this
/// machine (its `PATH`, `VIRTUAL_ENV`, toolchain homes, resolved interpreter paths), which
/// would replace the values there, and with the project's source roots on `PYTHONPATH`.
/// Values that settings derive but that are not paths of this machine (`GOPROXY`, `GOFLAGS`)
/// still apply there and are kept.
fn remote_config(config: &RunConfig, derived: Derived<'_>, root: &Path, python_roots: &[PathBuf]) -> RunConfig {
let plain = ide_sdk::apply::without_derived_in(config, derived.root, derived.fallback, derived.settings);
let mut out = config.clone();
out.command = plain.command;
out.env.retain(|key, value| plain.env.contains_key(key) || !has_local_path(value));
if ide_run::is_python_kind(&out.kind) {
container_python_path(&mut out.env, python_roots, root);
}
out
}
/// The settings a configuration's derived values come from (see [`settings_for`]).
#[derive(Clone, Copy)]
struct Derived<'a> {
root: &'a Path,
fallback: Option<&'a Path>,
settings: &'a ide_core::settings::Settings,
}
/// `value` is an absolute path of this machine, alone or first in a path list (a URL such
/// as `GOPROXY`'s is not: its first part is `https`).
fn has_local_path(value: &str) -> bool {
std::env::split_paths(value).find(|p| !p.as_os_str().is_empty()).is_some_and(|p| p.is_absolute())
}
/// The project's source roots on `PYTHONPATH` in a container or WSL distribution, as a local
/// run gets them: they are mounted with the project, and `container::prepare` /
/// `prepare_wsl` map their paths. The separator there is `:`, whatever this machine's is.
fn container_python_path(env: &mut std::collections::BTreeMap<String, String>, roots: &[PathBuf], root: &Path) {
let mut paths: Vec<String> =
roots.iter().filter(|p| p.starts_with(root)).map(|p| p.to_string_lossy().into_owned()).collect();
+112 -11
Переглянути файл
@@ -253,8 +253,10 @@ fn project_web_artifacts(ps: &ide_core::settings::ProjectStructureSettings) -> V
.collect()
}
/// Compiles the project and packs the Project Structure artifact `name` as the WAR Tomcat
/// deploys, recorded in `base` like a build tool's archive.
/// Compiles the project and builds the Project Structure artifact `name` for Tomcat to
/// deploy, recording its output path in `base` like a build tool's archive.
/// The artifact lives outside `base` (at `artifact_file`), so `tomcat::prepare` recreating
/// the runtime directory does not delete what was just built.
fn build_project_war(
root: &std::path::Path,
settings: &ide_core::settings::Settings,
@@ -270,10 +272,7 @@ fn build_project_war(
.iter()
.find(|a| a.name == name)
.ok_or_else(|| IdeError::invalid(format!("No artifact named {name} in Project Structure › Artifacts")))?;
let war = base.join("artifact").join(format!(
"{}.war",
name.split(':').next().unwrap_or(name).replace(|c: char| !c.is_alphanumeric() && c != '-', "_")
));
let target = compile::artifact_file(root, artifact);
let plan = compile::structure_war_plan(
root,
&ps,
@@ -281,7 +280,7 @@ fn build_project_war(
jdk.as_ref(),
&settings.languages.java.language_level,
artifact,
&war,
None,
cache,
)?;
let result = compile::run(root, &plan, &ide_core::CancellationToken::new(), &|_| {})?;
@@ -300,7 +299,7 @@ fn build_project_war(
}
std::fs::create_dir_all(base)?;
std::fs::write(base.join("artifact-id.txt"), format!("{PROJECT_ARTIFACT}{name}"))?;
std::fs::write(base.join("artifact-path.txt"), war.to_string_lossy().as_bytes())?;
std::fs::write(base.join("artifact-path.txt"), target.to_string_lossy().as_bytes())?;
Ok(())
}
@@ -332,8 +331,14 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
}
let project = host.project(window)?;
tokio::task::spawn_blocking(move || {
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
let artifacts = ide_build::web::artifacts(&project.root, &model);
let settings = project.settings.effective();
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &settings);
let mut artifacts = ide_build::web::artifacts(&project.root, &model);
if model.maven.is_none() && model.gradle.is_empty() {
let detected = project.detected_roots.read().clone();
let (ps, _, _) = crate::ops::build::structure_inputs(&project.root, &settings, &detected);
artifacts.extend(project_web_artifacts(&ps));
}
let id = config
.extras
.params
@@ -345,7 +350,6 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
let base = ide_run::tomcat::state_dir(&base, &config);
if let Some(name) = id.strip_prefix(PROJECT_ARTIFACT) {
let settings = project.settings.effective();
let detected = project.detected_roots.read().clone();
build_project_war(&project.root, &settings, &detected, name, &base, &project.build_cache_dir())?;
return Ok(None);
@@ -467,3 +471,100 @@ ide_command::domain!(
run_tomcat_sync,
run_tomcat_update,
);
#[cfg(test)]
mod tests {
use super::*;
use ide_core::settings::{ArtifactConfig, ArtifactKind, FacetConfig, Settings};
use std::io::Write;
fn fake_tomcat(home: &std::path::Path) {
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::create_dir_all(home.join("conf")).unwrap();
std::fs::create_dir_all(home.join("lib")).unwrap();
std::fs::write(home.join("bin/catalina.sh"), "").unwrap();
std::fs::write(home.join("bin/catalina.bat"), "").unwrap();
let server = "<Server port='8005'><Service><Connector port='8080'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
std::fs::write(home.join("conf/server.xml"), server).unwrap();
let mut zip = zip::ZipWriter::new(std::fs::File::create(home.join("lib/catalina.jar")).unwrap());
zip.start_file("org/apache/catalina/util/ServerInfo.properties", zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(b"server.info=Apache Tomcat/10.1").unwrap();
zip.finish().unwrap();
}
#[test]
fn project_structure_war_and_exploded_artifacts_survive_tomcat_prepare() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("EJSH");
let cache = root.parent().unwrap().join("cache");
let tomcat_home = root.parent().unwrap().join("tomcat-home");
fake_tomcat(&tomcat_home);
std::fs::create_dir_all(root.join("WebRoot/WEB-INF")).unwrap();
std::fs::write(root.join("WebRoot/WEB-INF/web.xml"), "<web-app/>").unwrap();
std::fs::write(root.join("WebRoot/index.jsp"), "<h1>ok</h1>").unwrap();
let mut settings = Settings::default();
settings.project_structure.facets.push(FacetConfig {
kind: "web".into(),
module: ".".into(),
descriptor: "WebRoot/WEB-INF/web.xml".into(),
web_root: "WebRoot".into(),
});
settings.project_structure.artifacts.push(ArtifactConfig {
name: "EJSH:war exploded".into(),
kind: ArtifactKind::WarExploded,
module: ".".into(),
output_directory: "out/artifacts/EJSH_war_exploded".into(),
..Default::default()
});
settings.project_structure.artifacts.push(ArtifactConfig {
name: "EJSH:war".into(),
kind: ArtifactKind::War,
module: ".".into(),
output_directory: "out/artifacts/EJSH_war".into(),
..Default::default()
});
for (artifact_name, expect_exploded_dir) in [("EJSH:war exploded", true), ("EJSH:war", false)] {
let mut config = RunConfig {
id: format!("tomcat-{artifact_name}"),
name: "Tomcat".into(),
kind: "tomcat".into(),
command: "catalina".into(),
args: vec![],
cwd: None,
env: Default::default(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
config.extras.params.insert("tomcatHome".into(), tomcat_home.to_string_lossy().into_owned());
config.extras.params.insert("deployment".into(), "artifact".into());
config.extras.params.insert("artifact".into(), format!("{PROJECT_ARTIFACT}{artifact_name}"));
config.extras.params.insert("artifactName".into(), "EJSH".into());
config.extras.params.insert("httpPort".into(), "8080".into());
let base = ide_run::tomcat::effective_base_dir(&root, &cache, &config).unwrap();
let state = ide_run::tomcat::state_dir(&base, &config);
build_project_war(&root, &settings, &[], artifact_name, &state, &cache.join("build")).unwrap();
// `prepare` deletes and recreates `base`; the built artifact must remain intact.
ide_run::tomcat::prepare(&root, &cache, &mut config).unwrap();
let catalina_base = std::path::PathBuf::from(&config.env["CATALINA_BASE"]);
let ctx = std::fs::read_to_string(catalina_base.join("conf/Catalina/localhost/EJSH.xml")).unwrap();
if expect_exploded_dir {
let expected = root.join("out/artifacts/EJSH_war_exploded");
assert!(expected.join("WEB-INF/web.xml").is_file());
assert!(ctx.contains(expected.to_string_lossy().as_ref()), "{ctx}");
} else {
assert!(root.join("out/artifacts/EJSH_war/EJSH.war").is_file());
assert!(catalina_base.join("deployment/WEB-INF/web.xml").is_file());
assert!(ctx.contains("deployment"), "{ctx}");
}
}
}
}
+33 -2
Переглянути файл
@@ -1,5 +1,5 @@
//! Docker and Compose run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`).
//! Docker, Compose and WSL run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`) or of `wsl.exe` (see `ide_remote::wsl`).
use crate::Host;
use ide_core::remote_settings::{RunTarget, RunTargetKind};
@@ -73,6 +73,37 @@ pub(super) async fn prepare(
.await
}
/// `config` rewritten to run in `target`'s WSL distribution.
pub(super) async fn prepare_wsl(
host: &Host,
root: &Path,
target: RunTarget,
config: RunConfig,
) -> IdeResult<RunConfig> {
if !cfg!(windows) {
return Err(IdeError::invalid(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let root = root.to_path_buf();
host.blocking(move || {
let linux_root = ide_remote::wsl::project_root(&target, &root)?;
let file_env = env_files(&root, &config)?;
let inherited = std::env::var("WSLENV").ok();
ide_remote::wsl::wsl_config(
&config,
&target,
&root,
&linux_root,
ide_core::wsl::EXE,
&file_env,
inherited.as_deref(),
)
})
.await
}
/// The project can only be bind-mounted from a daemon on this machine.
pub(crate) fn require_local(endpoint: &DockerEndpoint, target: &RunTarget) -> IdeResult<()> {
if !ide_docker::endpoint_is_local(endpoint)? {
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
pub mod container_python;
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons};
/// Executables found for "run this file", and where single files are compiled to.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
+126 -12
Переглянути файл
@@ -4,6 +4,9 @@
//! A snapshot runs the target's Python once in a new container (the image's entrypoint
//! and the service's dependencies skipped), then copies its `sys.path` folders out of
//! the stopped container with `docker cp`. Nothing is installed in the container.
//!
//! A WSL run target's snapshot only records its Python's `sys.path`: the folders are read
//! in place through `\\wsl.localhost\<distro>`.
use crate::Host;
use crate::project::Project;
@@ -23,6 +26,8 @@ use std::time::Duration;
const PROBE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const COPY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
const QUICK: Duration = Duration::from_secs(30);
/// Starting the distribution may come first.
const WSL_TIMEOUT: Duration = Duration::from_secs(2 * 60);
/// The project interpreter when it is a run target's.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
@@ -34,8 +39,10 @@ pub struct ContainerPython {
pub name: String,
/// The Python version of the snapshot in use; `None`: no snapshot yet.
pub version: Option<String>,
/// The image the snapshot was copied from.
/// The image the snapshot was copied from; `None` for WSL.
pub image: Option<String>,
/// The interpreter's path in the container or distribution.
pub executable: Option<String>,
/// The copied library folders on this machine.
pub folders: Vec<IpcPath>,
/// Packages of the snapshot (read-only).
@@ -108,22 +115,25 @@ pub(crate) fn library_group(host: &Host, root: &Path, settings: &Settings) -> Op
}
/// The project interpreter when it is a Docker or Compose run target's, with its snapshot.
/// Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
#[command(trust = trusted)]
pub fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
pub async fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
host.require_trust(window)?;
let project = host.project(window)?;
Ok(describe(host, &project.root, &project.settings.effective()))
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
}
fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPython> {
fn describe(dirs: &Dirs, root: &Path, settings: &Settings) -> Option<ContainerPython> {
let target = settings.languages.python.run_target()?;
let name = settings.run_targets.iter().find(|t| t.id == target).map(|t| t.name.clone()).unwrap_or_default();
let dir = Dirs::of(host).target(root, target);
let dir = dirs.target(root, target);
let mut out = ContainerPython {
target: target.to_owned(),
name,
version: None,
image: None,
executable: None,
folders: Vec::new(),
packages: Vec::new(),
updating: updating(&dir),
@@ -132,7 +142,8 @@ fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPy
out.folders = snapshots::local_folders(&dir, &snapshot).into_iter().map(Into::into).collect();
out.packages = snapshots::packages(&dir, &snapshot);
out.version = Some(snapshot.probe.version);
out.image = Some(snapshot.image);
out.executable = Some(snapshot.probe.executable);
out.image = snapshot.distro.is_none().then_some(snapshot.image);
}
Some(out)
}
@@ -144,7 +155,8 @@ pub async fn sdk_container_python_refresh(host: &Host, window: &str) -> IdeResul
host.require_trust(window)?;
let project = host.project(window)?;
update(Dirs::of(host), &project, true).await?;
Ok(describe(host, &project.root, &project.settings.effective()))
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
}
/// Takes a snapshot when the project interpreter is a run target's and the current image
@@ -154,13 +166,22 @@ pub(crate) fn ensure(host: &Host, project: &Arc<Project>) {
return;
}
let (dirs, project) = (Dirs::of(host), project.clone());
let settings = project.settings.effective();
let wsl = settings
.languages
.python
.run_target()
.and_then(|id| settings.run_targets.iter().find(|t| t.id == id))
.is_some_and(|t| t.kind == RunTargetKind::Wsl);
let title =
if wsl { "Cannot read the WSL Python's libraries" } else { "Cannot copy the container's Python libraries" };
host.runtime.spawn(async move {
if let Err(e) = update(dirs, &project, false).await
&& e.kind != ide_core::error::ErrorKind::Cancelled
{
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: "Cannot copy the container's Python libraries".into(),
title: title.into(),
body: Some(e.message),
});
}
@@ -173,7 +194,7 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind == RunTargetKind::Ssh {
return Err(IdeError::invalid(format!(
"Run target '{}' runs over SSH: only a Docker or Compose run target can be the project interpreter",
"Run target '{}' is an SSH host: only a Docker, Compose or WSL run target can be the project interpreter",
target.name
)));
}
@@ -182,7 +203,10 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
return Ok(());
}
let _done = Updating(dir.clone());
let endpoint = crate::ops::run::container::endpoint(&dirs.data, &target)?;
let endpoint = match target.kind {
RunTargetKind::Wsl => None,
_ => Some(crate::ops::run::container::endpoint(&dirs.data, &target)?),
};
let task = TaskId::next();
let title = format!("Python libraries of {}", target.name);
let (root, sink) = (project.root.clone(), project.sink.clone());
@@ -198,7 +222,11 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
};
let report = progress.clone();
let result = tokio::task::spawn_blocking(move || {
take(&endpoint, &root, &target, &dir, &dirs.cache, force, &|message| report(message, false))
let report = |message: &str| report(message, false);
match endpoint {
Some(endpoint) => take(&endpoint, &root, &target, &dir, &dirs.cache, force, &report),
None => take_wsl(&root, &target, &dir, &dirs.cache, &report),
}
})
.await
.map_err(|e| IdeError::internal(e.to_string()))
@@ -288,6 +316,7 @@ fn take(
image: image.clone(),
probe,
folders,
distro: None,
};
snapshots::write(&partial, &snapshot)?;
if dir.exists() {
@@ -298,6 +327,72 @@ fn take(
Ok(true)
}
/// Records where the WSL target's Python finds its libraries and makes that the snapshot in
/// use; `false` when nothing changed. Nothing is copied, so packages installed later show up.
fn take_wsl(
root: &Path,
target: &RunTarget,
target_dir: &Path,
cache: &Path,
progress: &dyn Fn(&str),
) -> IdeResult<bool> {
if !cfg!(windows) {
return Err(IdeError::unavailable(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let linux_root = ide_remote::wsl::project_root(target, root)?;
let distro = target.distro.trim();
progress("Starting the WSL Python");
let out = ide_core::wsl::exec(distro, &[ide_remote::wsl::python(target), "-c", snapshots::PROBE], WSL_TIMEOUT)?;
let probe = snapshots::parse_probe(&out)?;
let id = format!("wsl-{}-{}", probe.executable, probe.version);
let snapshot = Snapshot {
image: id.clone(),
folders: wsl_folders(&probe, &linux_root),
neutral_python: snapshots::neutral_python(cache, &probe.version),
distro: Some(distro.to_owned()),
probe,
};
// What the language server is given: the probe's other details (its raw `sys.path` order,
// say) are kept in the snapshot but don't restart it.
let libraries = |s: &Snapshot| (s.image.clone(), s.folders.clone(), s.neutral_python.clone(), s.distro.clone());
let changed = snapshots::current(target_dir).map(|(_, s)| libraries(&s)) != Some(libraries(&snapshot));
let dir = target_dir.join(snapshots::dir_name(&id));
std::fs::create_dir_all(&dir)?;
snapshots::write(&dir, &snapshot)?;
snapshots::make_current(target_dir, &id)?;
Ok(changed)
}
/// The library folders of a WSL Python: as a container's, plus a virtualenv's in the project
/// (`.venv/lib/python3.12/site-packages`), which a container mount would hold anyway.
fn wsl_folders(probe: &snapshots::Probe, linux_root: &str) -> Vec<String> {
let root = linux_root.trim_end_matches('/');
let in_project = |f: &str| root.is_empty() || f == root || f.starts_with(&format!("{root}/"));
let packages = |f: &str| f.split('/').any(|c| c == "site-packages" || c == "dist-packages");
snapshots::folders_to_copy(probe, "").into_iter().filter(|f| !in_project(f) || packages(f)).collect()
}
/// The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
/// `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
#[command(trust = trusted)]
pub async fn sdk_wsl_pythons(host: &Host, window: &str, distro: String) -> IdeResult<Vec<String>> {
host.require_trust(window)?;
if !cfg!(windows) {
return Ok(Vec::new());
}
let root = host.project(window)?.root.clone();
host.blocking(move || {
let distro = distro.trim();
let linux_root = ide_core::wsl::linux_path(&root, distro).unwrap_or_default();
let script = ["sh", "-c", ide_remote::wsl::FIND_PYTHONS, "sh", &linux_root];
Ok(ide_remote::wsl::parse_pythons(&ide_core::wsl::exec(distro, &script, WSL_TIMEOUT)?))
})
.await
}
/// Distinguishes probe containers.
fn unique() -> String {
use std::sync::atomic::{AtomicU32, Ordering};
@@ -306,4 +401,23 @@ fn unique() -> String {
format!("{:x}-{}-{}", secs & 0xff_ffff, std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))
}
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh);
#[cfg(test)]
mod wsl_tests {
#[test]
fn a_virtualenv_in_the_project_is_read_and_its_sources_are_not() {
let probe = super::snapshots::Probe {
version: "3.12.3".into(),
executable: "/mnt/c/p/.venv/bin/python".into(),
stdlib: vec![Some("/usr/lib/python3.12".into())],
path: ["/mnt/c/p/src", "/usr/lib/python3.12", "/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
.map(String::from)
.to_vec(),
};
assert_eq!(
super::wsl_folders(&probe, "/mnt/c/p"),
["/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
);
}
}
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons);
+5
Переглянути файл
@@ -760,6 +760,11 @@ impl PluginHost {
.filter(|(_, p)| p.dev_root.as_deref() == Some(root))
.map(|(id, _)| id.clone())
.collect();
// Nothing to unload, nothing to announce: `CommandsChanged` makes every window list the
// plugins again, and listing restricts an untrusted project again, which looped while idle.
if ids.is_empty() {
return;
}
for id in ids {
self.unload(&id);
}
+36 -5
Переглянути файл
@@ -565,6 +565,21 @@ impl Host {
.collect();
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
});
// `git worktree add` writes the worktree's gitfile before its gitdir's
// `HEAD`: a rescan in between finds no repository there yet, so that `HEAD`
// rescans too while its worktree is unknown and one a rescan would find.
git_dirs |= batch.vcs.iter().any(|p| {
let Some(gitdir) = p.parent().filter(|_| p.ends_with("HEAD")) else { return false };
if !gitdir.parent().is_some_and(|d| d.ends_with(".git/worktrees")) {
return false;
}
// `gitdir` may be relative to itself (`git worktree add --relative-paths`).
let worktree = std::fs::read_to_string(gitdir.join("gitdir"))
.and_then(|gitfile| dunce::canonicalize(gitdir.join(gitfile.trim())));
worktree.ok().as_deref().and_then(Path::parent).is_some_and(|dir| {
!known.iter().any(|r| r == dir) && repository_searched(&root, dir, &settings.effective())
})
});
// A repository folder moved or restored into the project: no `.git` event is
// written inside it before the watcher sees the new directory, its creation is
// the signal. A `git clone` / `git init` inside the project already arrives
@@ -1186,18 +1201,34 @@ fn detect_repositories(
build_cache: &Path,
trusted: bool,
) -> IdeResult<Repos> {
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(settings, root, build_cache, trusted));
Repos::discover_roots(&roots, &repository_scan_skips(settings))
}
/// Folders the search for nested repositories leaves out, besides hidden and dependency ones.
fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Path) -> bool {
let ignored = settings.ignored_names();
let skip = |p: &Path| {
move |p: &Path| {
p.file_name().is_some_and(|n| {
let name = n.to_string_lossy();
ignored.is_ignored_name(&name)
|| (ide_workspace::unity::GENERATED_DIRS.contains(&name.as_ref())
&& p.parent().is_some_and(ide_workspace::unity::is_project))
})
};
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(settings, root, build_cache, trusted));
Repos::discover_roots(&roots, &skip)
}
}
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
settings.vcs.git.enabled
&& !settings
.vcs
.mappings
.excluded
.iter()
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
&& Repos::searched(root, dir, &repository_scan_skips(settings))
}
impl Project {
+1 -1
Переглянути файл
@@ -107,7 +107,7 @@ async fn compose_target_is_the_python_interpreter() {
eprintln!("run target interpreter: {after:?}");
assert!(after.iter().all(|m| !m.contains("could not be resolved")), "{after:?}");
let info = ops::sdk::sdk_container_python(&host, WINDOW).unwrap().expect("a run target interpreter");
let info = ops::sdk::sdk_container_python(&host, WINDOW).await.unwrap().expect("a run target interpreter");
eprintln!("snapshot: version {:?}, image {:?}, folders {:?}", info.version, info.image, info.folders);
assert_eq!(info.name, "Compose web");
assert!(info.version.as_deref().is_some_and(|v| v.starts_with("3.12.")), "{info:?}");
+64 -8
Переглянути файл
@@ -1603,14 +1603,15 @@ async fn post(server: &ide_mcp::McpServer, body: &Value) -> Value {
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_open_in_a_window_answers_before_any_background_project() {
async fn a_project_open_in_a_window_answers_for_its_folders_that_no_nested_project_holds() {
let h = Harness::new();
let inventory = h.serve_inventory();
// A listed folder inside the open project: the window's project answers for it.
h.set("backgroundProjectPaths", json!([inventory, h.root.join("src")]));
// A listed folder around the open project leaves the project's folders to its window.
let around = h.root.parent().unwrap().to_path_buf();
h.set("backgroundProjectPaths", json!([inventory, around]));
let (server, discovery) = h.server();
let inside = json!({"projectPath": h.root.join("src"), "file_path": "src/b.txt"});
let read = rpc(1, "tools/call", json!({"name":"read_file","arguments":inside.clone()}));
let read = rpc(1, "tools/call", json!({"name":"read_file","arguments":inside}));
let replies = bridged(&discovery, &inventory, &[read]).await;
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: needle\nL2: ", "{replies:?}");
assert!(h.background().is_empty());
@@ -1621,13 +1622,13 @@ async fn a_project_open_in_a_window_answers_before_any_background_project() {
let unnamed = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/b.txt"}}));
let reply = post(&server, &unnamed).await;
assert_eq!(reply["result"]["content"][0]["text"], "L1: needle\nL2: ", "{reply}");
// Nor does a background project loaded inside the window's project take its folder over.
// A folder listed inside the window's project is a project of its own (#7040).
let nested = h.root.join("src");
h.call_at(&nested, "read_file", json!({"file_path":"b.txt"})).await.unwrap();
assert_eq!(h.background(), [inventory.clone(), nested]);
let read = rpc(3, "tools/call", json!({"name":"read_file","arguments":inside}));
h.set("backgroundProjectPaths", json!([inventory, around, nested]));
let read = rpc(3, "tools/call", json!({"name":"read_file","arguments":{"projectPath":nested,"file_path":"b.txt"}}));
let replies = bridged(&discovery, &inventory, &[read]).await;
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: needle\nL2: ", "{replies:?}");
assert_eq!(h.background(), [inventory.clone(), nested]);
// A second window on another root is served as before.
let second = h.root.parent().unwrap().join("second");
std::fs::create_dir_all(&second).unwrap();
@@ -1638,6 +1639,61 @@ async fn a_project_open_in_a_window_answers_before_any_background_project() {
assert_eq!(h.background().len(), 2);
}
/// The layout of #7040: `marker.txt` in the window's project and in `contracts`, a trusted
/// repository inside it that trusted mode serves in the background.
#[tokio::test(flavor = "multi_thread")]
async fn a_nested_trusted_project_answers_for_its_folders_whether_or_not_a_window_is_open_around_it() {
let h = Harness::new();
std::fs::write(h.root.join("marker.txt"), "from packages").unwrap();
let contracts = h.root.join("contracts");
std::fs::create_dir_all(contracts.join(".git")).unwrap();
std::fs::create_dir_all(contracts.join("src")).unwrap();
std::fs::write(contracts.join("marker.txt"), "from contracts").unwrap();
std::fs::write(contracts.join("src/only.txt"), "only in contracts").unwrap();
h.trust().await;
h.host.trust.decide(&contracts, true, false).unwrap();
h.set("enabled", json!(true));
h.set("backgroundProjects", json!("trusted"));
let (server, discovery) = h.server();
let read = |file: &str| {
let arguments = json!({"projectPath": contracts, "file_path": file});
rpc(1, "tools/call", json!({"name":"read_file","arguments":arguments}))
};
let text = |reply: Value| reply["result"]["content"][0]["text"].as_str().map(str::to_owned).ok_or(reply);
h.host.close_project("main");
assert_eq!(text(post(&server, &read("marker.txt")).await), Ok("L1: from contracts".to_owned()));
// A window opens on the folder around it between two calls.
h.host.open_project("main", &h.root).unwrap();
assert_eq!(text(post(&server, &read("marker.txt")).await), Ok("L1: from contracts".to_owned()));
assert_eq!(text(post(&server, &read("src/only.txt")).await), Ok("L1: only in contracts".to_owned()));
let roots = rpc(2, "tools/call", json!({"name":"get_workspace_roots","arguments":{"projectPath":contracts}}));
let roots = post(&server, &roots).await;
assert_eq!(roots["result"]["structuredContent"]["projectRoot"], json!(contracts), "{roots}");
// The stdio bridge started in the nested project reaches it too.
let unnamed = rpc(3, "tools/call", json!({"name":"read_file","arguments":{"file_path":"marker.txt"}}));
let replies = bridged(&discovery, &contracts.join("src"), &[unnamed]).await;
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: from contracts", "{replies:?}");
assert_eq!(h.background(), std::slice::from_ref(&contracts));
// A folder of the window's project that no nested project holds stays with the window.
let outside = json!({"projectPath": h.root.join("src"), "file_path": "marker.txt"});
let reply = post(&server, &rpc(4, "tools/call", json!({"name":"read_file","arguments":outside}))).await;
assert_eq!(text(reply), Ok("L1: from packages".to_owned()));
assert_eq!(h.background(), std::slice::from_ref(&contracts), "it loads nothing");
// A remote window's project at the same path keeps its folders, the nested one included:
// they are that host's.
h.host.close_project("main");
h.host.mcp_reports.set_remote("remote", h.root.clone());
let reply = post(&server, &read("marker.txt")).await;
assert_eq!(
reply["result"]["content"][0]["text"],
"project is on a remote host; connect to the MCP server on that host"
);
h.host.close_project_detached("remote");
}
#[tokio::test(flavor = "multi_thread")]
async fn tools_fed_by_a_window_say_that_a_background_project_has_none() {
let h = Harness::new();
+17
Переглянути файл
@@ -8170,3 +8170,20 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent
assert_eq!(dirs.len(), 1);
assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}");
}
#[test]
fn restricting_a_project_without_its_plugins_announces_nothing() {
let tmp = tempfile::tempdir().unwrap();
let events: Events = Arc::default();
let sink = {
let events = events.clone();
move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e))
};
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(sink), Limits::default()).unwrap();
host.load_all();
events.lock().clear();
// A restricted window lists the plugins, which restricts its project again each time.
host.restrict_project(tmp.path());
host.restrict_project(tmp.path());
assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged)));
}
+50 -1
Переглянути файл
@@ -28,6 +28,10 @@ struct Fixture {
impl Fixture {
async fn new() -> Self {
Self::with_sink(Arc::new(ide_core::NullSink)).await
}
async fn with_sink(sink: ide_core::SharedSink) -> Self {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
@@ -40,7 +44,8 @@ impl Fixture {
std::fs::write(root.join("file.txt"), "original\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "original"]);
let host = Host::new(common::host_config(&base));
let host =
Host::new(ide_host::HostConfig { sink_for: Box::new(move |_| sink.clone()), ..common::host_config(&base) });
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
wait_for_repos(&project, 1).await;
@@ -278,6 +283,50 @@ async fn watcher_picks_up_a_worktree_added_below_the_project() {
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
}
/// `git worktree add` writes the worktree's gitfile before its gitdir's `commondir` and `HEAD`; a
/// slow git lets the watcher rescan in between and find no repository there yet.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn watcher_picks_up_a_worktree_whose_head_is_written_after_a_rescan() {
let changes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counter = changes.clone();
let sink: ide_core::SharedSink = Arc::new(move |event: ide_core::IdeEvent| {
if matches!(event, ide_core::IdeEvent::VcsChanged { .. }) {
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
});
let f = Fixture::with_sink(sink).await;
// The watcher reports a batch that rescans only once the rescan is done.
let next_change = || {
let (changes, seen) = (changes.clone(), changes.load(std::sync::atomic::Ordering::SeqCst));
async move {
for _ in 0..200 {
if changes.load(std::sync::atomic::Ordering::SeqCst) > seen {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
panic!("the watcher reported no change");
}
};
let linked = f.root.join("watched");
let gitdir = f.root.join(".git/worktrees/watched");
let registered = next_change();
std::fs::create_dir_all(&gitdir).unwrap();
std::fs::write(gitdir.join("gitdir"), format!("{}\n", linked.join(".git").display())).unwrap();
registered.await;
let rescanned = next_change();
std::fs::create_dir_all(&linked).unwrap();
std::fs::write(linked.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap();
rescanned.await;
assert_eq!(f.project.repos().all().len(), 1, "a gitfile without its gitdir's HEAD is no repository yet");
std::fs::write(gitdir.join("commondir"), "../..\n").unwrap();
// As git does: through a lock file.
std::fs::write(gitdir.join("HEAD.lock"), "ref: refs/heads/main\n").unwrap();
std::fs::rename(gitdir.join("HEAD.lock"), gitdir.join("HEAD")).unwrap();
wait_for_repos(&f.project, 2).await;
assert!(f.project.repos().roots().contains(&linked));
}
impl Fixture {
async fn open(&self, root: &std::path::Path) {
self.host.trust.decide(root, true, false).unwrap();
+4
Переглянути файл
@@ -227,6 +227,10 @@ pub struct LanguageServerConfig {
/// it parses a document.
#[serde(default)]
pub resync_on_configuration: bool,
/// Server-created work-done tokens to ignore, including slash-delimited suffixes.
/// Client-created request tokens are handled independently.
#[serde(default)]
pub ignored_progress_token_prefixes: Vec<String>,
/// Set by the settings hook: what the user sees as the server when another program serves
/// in its place (TypeScript 7's own `tsc --lsp` for vtsls).
#[serde(skip)]
+4 -1
Переглянути файл
@@ -909,7 +909,10 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
assert_eq!(names, ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
let phpantom = &cfg.language_servers[1];
assert!(phpantom.fallback && phpantom.args.is_empty());
assert_eq!(phpantom.command, "phpantom_lsp");
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
+1
Переглянути файл
@@ -73,6 +73,7 @@ fn server_config() -> LanguageServerConfig {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
+17
Переглянути файл
@@ -151,6 +151,23 @@ impl ClientHandler {
}
fn progress(&self, mgr: &LspManager, params: Value) {
if let Some(token) = params["token"].as_str() {
if let Some(id) = token.strip_prefix(crate::server::REQUEST_PROGRESS_PREFIX) {
if let (Ok(id), Ok(update)) = (id.parse::<u32>(), serde_json::from_value(params["value"].clone())) {
self.server.request_progress(mgr.sink(), TaskId(id), update);
}
return;
}
if self
.server
.config
.ignored_progress_token_prefixes
.iter()
.any(|prefix| token.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')))
{
return;
}
}
let token = progress_key(&params["token"]);
let value = &params["value"];
let kind = value.get("kind").and_then(Value::as_str);
+65 -2
Переглянути файл
@@ -122,10 +122,24 @@ pub fn configure_project_structure(
// JDT resolves relative library globs against its own root, which may be a submodule.
Some(root.join(trimmed).to_string_lossy().replace('\\', "/"))
};
let normalize_class = |entry: &str| -> Option<String> {
let trimmed = entry.trim();
if trimmed.is_empty() {
return None;
}
let resolved = root.join(trimmed);
let path = resolved.to_string_lossy().replace('\\', "/");
// A directory library root (e.g. `WebRoot/WEB-INF/lib`) needs a `**/*.jar` glob so jdtls
// indexes the JAR archives inside it rather than ignoring the bare folder path.
if resolved.is_dir() && !ide_core::settings::jar_files(&resolved, true).is_empty() {
return Some(format!("{}/**/*.jar", path.trim_end_matches('/')));
}
Some(path)
};
let mut include: Vec<String> = Vec::new();
let mut sources = serde_json::Map::new();
for lib in &structure.libraries {
let class_entries: Vec<String> = lib.classes.iter().filter_map(|c| normalize(c)).collect();
let class_entries: Vec<String> = lib.classes.iter().filter_map(|c| normalize_class(c)).collect();
let source_entries: Vec<String> = lib.sources.iter().filter_map(|s| normalize(s)).collect();
for c in &class_entries {
if !include.contains(c) {
@@ -133,7 +147,9 @@ pub fn configure_project_structure(
}
}
for (class, source) in class_entries.iter().zip(&source_entries) {
sources.insert(class.clone(), json!(source));
if !class.contains('*') {
sources.insert(class.clone(), json!(source));
}
}
}
for facet in &structure.facets {
@@ -1953,4 +1969,51 @@ mod tests {
configure_project_structure(&mut cfg, tmp.path(), tmp.path(), &structure);
assert!(cfg.launch_error.as_deref().unwrap().contains("inside its module"));
}
#[test]
fn directory_library_root_expands_to_recursive_jar_glob_for_jdtls() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let web_lib = root.join("WebRoot/WEB-INF/lib");
std::fs::create_dir_all(&web_lib).unwrap();
std::fs::write(web_lib.join("gson.jar"), b"").unwrap();
let structure = ide_core::settings::ProjectStructureSettings {
libraries: vec![ide_core::settings::ProjectLibrary {
name: "lib".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
sources: vec![],
javadocs: vec![],
scope: ide_core::settings::DependencyScope::Runtime,
}],
..Default::default()
};
let mut cfg: ide_language::LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
configure_project_structure(&mut cfg, root, root, &structure);
let include = cfg
.settings
.as_ref()
.unwrap()
.pointer("/java/project/referencedLibraries/include")
.and_then(Value::as_array)
.unwrap();
let expected = format!("{}/**/*.jar", web_lib.to_string_lossy().replace('\\', "/"));
assert!(include.contains(&json!(expected)), "include={include:?}");
// A class folder without jars stays a plain path.
let classes = root.join("classes");
std::fs::create_dir_all(&classes).unwrap();
let structure = ide_core::settings::ProjectStructureSettings {
libraries: vec![ide_core::settings::ProjectLibrary {
name: "classes".into(),
classes: vec!["classes".into()],
..Default::default()
}],
..Default::default()
};
let mut cfg: ide_language::LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
configure_project_structure(&mut cfg, root, root, &structure);
let include = cfg.settings.as_ref().unwrap().pointer("/java/project/referencedLibraries/include").cloned();
assert!(!format!("{include:?}").contains("classes/**"), "include={include:?}");
}
}
+13 -3
Переглянути файл
@@ -58,7 +58,7 @@ pub use jdtls::stream_trace::JdtStreamTracer;
pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable};
pub use launch::{LaunchError, Launcher, ProcessLauncher};
pub use message_requests::answer as answer_message_request;
pub use notebook::{NotebookCell, NotebookCellDoc, cell_uri};
pub use notebook::{NotebookCell, NotebookCellDoc, NotebookCellText, cell_uri};
pub use plugin_requests::plugin_method_allowed;
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
pub use uri::{path_to_uri_string, uri_target, uri_to_path};
@@ -1598,10 +1598,20 @@ impl LspManager {
cancel: Option<&CancellationToken>,
timeout: Duration,
) -> IdeResult<R> {
let params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
let mut params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
// ImplementationParams accepts an optional client work-done token. Servers
// may report on it even when implementationProvider is advertised as `true`.
let progress = (method == "textDocument/implementation")
.then(|| t.server.track_request_progress(t.run.generation, self.sink(), cancel));
let cancel = if let Some(progress) = &progress {
params["workDoneToken"] = json!(progress.wire_token());
Some(progress.cancel.clone())
} else {
cancel.cloned()
};
let stamp = self.injected_request_stamp(&params);
let fut = async {
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel.cloned()).await?;
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel).await?;
virtual_doc::normalize_uris(&mut value);
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
};
+47
Переглянути файл
@@ -40,6 +40,14 @@ pub struct NotebookCellDoc {
pub uri: String,
}
/// A cell document's buffer, as the notebook service keeps it.
pub struct NotebookCellText {
pub path: std::path::PathBuf,
pub language: LanguageId,
pub text: String,
pub version: u32,
}
pub(crate) struct NotebookState {
uri: lsp::Uri,
language: LanguageId,
@@ -154,6 +162,22 @@ impl LspManager {
.collect()
}
/// A cell document's buffer, for work that runs without asking a server — formatting reads
/// it from `documents`, which only holds files the editor opened, never a notebook's cells.
pub fn cell_text(&self, doc: DocId) -> Option<NotebookCellText> {
let docs = self.docs.lock();
let d = docs.get(&doc)?;
// The notebook file, not the cell's own `vscode-notebook-cell:` uri: a formatter
// looks the file up to find the project's settings and the language of the file.
let path = d.notebook.clone()?;
Some(NotebookCellText {
path,
language: d.language.clone(),
text: d.text.as_str().to_owned(),
version: d.version.max(0) as u32,
})
}
/// Opens the notebooks of `server`'s language on its instance that just became ready.
pub(crate) fn reopen_notebooks(&self, server: &Arc<Server>, run: &Running) {
let mut pull = Vec::new();
@@ -384,4 +408,27 @@ mod tests {
assert!(is_cell_uri(&uri) && parse_uri(&uri).is_some());
assert!(!is_cell_uri("file:///a.ipynb") && !is_cell_uri("vscode-notebook-cellx:/a"));
}
/// A cell lives in `docs` only, never in `documents`; formatting asks for its buffer here.
#[test]
fn cell_text_answers_for_a_cell_document_and_nothing_else() {
let manager = LspManager::new(
PathBuf::from("/work"),
std::sync::Arc::new(crate::LanguageRegistry::load(None).unwrap()),
std::sync::Arc::new(|_: ide_core::IdeEvent| {}),
);
let path = PathBuf::from("/work/a.ipynb");
let cells = [NotebookCell { id: "cell-a".into(), source: "x=1".into() }];
manager.sync_notebook(&path, &LanguageId::new("python"), &cells);
let doc = manager.notebook_cells(&path)[0].doc;
let text = manager.cell_text(doc).expect("a cell document answers");
assert_eq!(text.text, "x=1");
// The notebook file, so a formatter finds the project's settings for it.
assert_eq!(text.path, path);
assert_eq!(text.language.as_str(), "python");
// A document the notebook service does not know stays unknown.
assert!(manager.cell_text(DocId(9999)).is_none());
}
}
+107
Переглянути файл
@@ -53,10 +53,58 @@ struct State {
generation: u64,
conn: Conn,
restarting: bool,
request_progress: HashMap<TaskId, RequestProgressState>,
events: VecDeque<IdeEvent>,
publishing: bool,
}
pub(crate) const REQUEST_PROGRESS_PREFIX: &str = "openidea/request/";
struct RequestProgressState {
title: Option<String>,
message: Option<String>,
fraction: Option<f32>,
_cancel: ide_core::task::CancelHandle,
}
impl RequestProgressState {
fn event(&self, id: TaskId, done: bool) -> Option<IdeEvent> {
Some(IdeEvent::Task {
id,
title: self.title.clone()?,
message: self.message.clone(),
fraction: self.fraction,
done,
cancellable: !done,
})
}
}
/// Progress provided to an LSP request. Dropping the request always retires its token.
pub(crate) struct RequestProgress<'a> {
id: TaskId,
server: &'a Server,
sink: &'a SharedSink,
pub(crate) cancel: CancellationToken,
}
impl RequestProgress<'_> {
pub(crate) fn wire_token(&self) -> String {
format!("{REQUEST_PROGRESS_PREFIX}{}", self.id.0)
}
}
impl Drop for RequestProgress<'_> {
fn drop(&mut self) {
let mut st = self.server.state.lock();
if let Some(progress) = st.request_progress.remove(&self.id) {
st.events.extend(progress.event(self.id, true));
}
drop(st);
self.server.publish(self.sink);
}
}
/// A file opened on the server by the client itself (not by the user) for the
/// duration of a request, e.g. to widen a references search.
struct Transient {
@@ -172,6 +220,7 @@ impl Server {
generation: 0,
conn: Conn::Idle,
restarting: false,
request_progress: HashMap::new(),
events: VecDeque::new(),
publishing: false,
}),
@@ -552,6 +601,9 @@ impl Server {
fn queue_cleanup(&self, st: &mut State) {
*self.initializing.lock() = None;
for (id, progress) in st.request_progress.drain() {
st.events.extend(progress.event(id, true));
}
for (id, title) in self.take_progress() {
st.events.push_back(IdeEvent::Task {
id,
@@ -572,6 +624,61 @@ impl Server {
}
}
pub(crate) fn track_request_progress<'a>(
&'a self,
generation: u64,
sink: &'a SharedSink,
parent_cancel: Option<&CancellationToken>,
) -> RequestProgress<'a> {
let id = TaskId::next();
let cancel = parent_cancel.map(CancellationToken::child_token).unwrap_or_default();
let mut st = self.state.lock();
if st.generation == generation && matches!(st.conn, Conn::Ready(_)) {
let token = cancel.clone();
st.request_progress.insert(
id,
RequestProgressState {
title: None,
message: None,
fraction: None,
_cancel: ide_core::task::on_cancel(id, move || token.cancel()),
},
);
}
RequestProgress { id, server: self, sink, cancel }
}
pub(crate) fn request_progress(&self, sink: &SharedSink, id: TaskId, update: lsp::WorkDoneProgress) {
let mut st = self.state.lock();
let Some(progress) = st.request_progress.get_mut(&id) else { return };
let fraction = |p: u32| p.min(100) as f32 / 100.0;
let event = match update {
lsp::WorkDoneProgress::Begin(begin) => {
progress.title = Some(begin.title);
progress.message = begin.message;
progress.fraction = begin.percentage.map(fraction);
progress.event(id, false)
}
lsp::WorkDoneProgress::Report(report) => {
progress.message = report.message.or_else(|| progress.message.take());
progress.fraction = report.percentage.map(fraction).or(progress.fraction);
progress.event(id, false)
}
lsp::WorkDoneProgress::End(end) => {
progress.message = end.message.or_else(|| progress.message.take());
progress.fraction = Some(1.0);
let event = progress.event(id, true);
st.request_progress.remove(&id);
event
}
};
// Queue under the state lock so a reply or cancellation can't publish `done`
// before a concurrent progress update and leave a stale row.
st.events.extend(event);
drop(st);
self.publish(sink);
}
pub fn emit(&self, sink: &SharedSink, event: IdeEvent) {
self.state.lock().events.push_back(event);
self.publish(sink);
+162 -1
Переглянути файл
@@ -277,6 +277,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
@@ -2225,6 +2226,54 @@ async fn a_progress_token_begun_again_ends_the_task_it_replaces() {
h.wait_status("mock", ServerStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn toml_progress_quirk_ignores_server_tokens_left_open_after_cancel() {
let registry = LanguageRegistry::load(None).unwrap();
let php = registry.get(&LanguageId::new("php")).unwrap();
let quirk = &php.language_servers.iter().find(|s| s.name == "phpantom").unwrap().ignored_progress_token_prefixes;
let h = harness_configured("php", "php", &[("mock", incremental_caps())], |cfg| {
cfg.ignored_progress_token_prefixes = quirk.clone();
});
let (doc, path) = h.open("a.php", "<?php target();");
h.wait_status("mock", ServerStatus::Ready).await;
let server = h.launcher.state("mock");
let peer = server.peer();
let progress = |token, kind, title| {
peer.notify("$/progress", json!({ "token": token, "value": { "kind": kind, "title": title } })).unwrap();
};
let method = "textDocument/references";
let search = || h.mgr.references_streaming(doc, Pos::new(0, 7), true, false, true, Default::default(), None);
progress("find_references/1", "begin", "Find References");
progress("find_references", "begin", "Find References");
progress("goto_implementation/1", "begin", "Go to Implementation");
progress("find_references_index/1", "begin", "Indexing");
h.wait_status("mock", ServerStatus::Busy).await;
server.errors.lock().insert(method.into(), (-32800, "Canceled".into()));
assert_eq!(search().await.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
server.errors.lock().remove(method);
server.respond(
method,
json!([{
"uri": uri_of(&path),
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 12 } }
}]),
);
progress("find_references/2", "begin", "Find References");
assert_eq!(search().await.unwrap().locations.len(), 1);
progress("find_references/2", "end", "Find References");
progress("find_references_index/1", "end", "Indexing");
h.wait_status("mock", ServerStatus::Ready).await;
let events = h.events.lock();
assert!(!events.iter().any(
|e| matches!(e, IdeEvent::Task { title, .. } if title == "Find References" || title == "Go to Implementation")
));
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: false, .. } if title == "Indexing")));
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: true, .. } if title == "Indexing")));
}
#[tokio::test(flavor = "multi_thread")]
async fn replacing_progress_keeps_cancellation_reports_and_indexing_on_the_new_task() {
let h = harness(&[("mock", incremental_caps())]);
@@ -4239,6 +4288,118 @@ async fn implementations_per_position() {
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
#[tokio::test]
async fn implementation_progress_ends_on_cancel_without_server_end() {
implementation_progress_ends_with_request(false).await;
}
#[tokio::test]
async fn implementation_progress_ends_on_timeout_without_server_end() {
implementation_progress_ends_with_request(true).await;
}
async fn implementation_progress_ends_with_request(timeout: bool) {
let caps = json!({ "textDocumentSync": 1, "implementationProvider": true });
let h = harness_for("php", "php", &[("mock", caps)], &[]);
let (doc, path) = h.open("a.php", "<?php\ninterface A {}\nclass B implements A {}\n");
h.wait_status("mock", ServerStatus::Ready).await;
let server = h.launcher.state("mock");
let method = "textDocument/implementation";
let gate = Arc::new(Gate::default());
let uri = uri_of(&path);
*server.responder.lock() =
Some(Arc::new({
let gate = gate.clone();
move |server, requested, params| {
if requested != method {
return None;
}
let token = &params["workDoneToken"];
let peer = server.peer();
peer.notify("$/progress", json!({
"token": token, "value": { "kind": "begin", "title": "Go to Implementation", "cancellable": false }
})).unwrap();
if params["position"]["character"] == 10 {
peer.notify(
"$/progress",
json!({
"token": token, "value": { "kind": "report", "percentage": 88 }
}),
)
.unwrap();
gate.hold();
}
// The mock answers without sending `end`.
Some(json!([{
"uri": uri,
"range": { "start": { "line": 2, "character": 6 }, "end": { "line": 2, "character": 7 } }
}]))
}
}));
let mgr = h.mgr.clone();
let batch = tokio::spawn(async move {
mgr.implementations(doc, &[Pos::new(1, 10), Pos::new(2, 6)], Default::default()).await.unwrap()
});
let task_events = || {
h.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Task { id, title, done, fraction, cancellable, .. } if title == "Go to Implementation" => {
Some((*id, *done, *fraction, *cancellable))
}
_ => None,
})
.collect::<Vec<_>>()
};
eventually(|| {
let events = task_events();
gate.entered() && events.iter().any(|e| e.2 == Some(0.88)) && events.iter().any(|(_, done, _, _)| *done)
})
.await;
let scanning = task_events().into_iter().find(|e| e.2 == Some(0.88)).expect("scan reported 88%");
let (task, _, _, cancellable) = scanning;
assert!(cancellable);
assert!(!task_events().iter().any(|(id, done, _, _)| *id == task && *done));
let requests = server.requested(method);
assert_eq!(requests.len(), 2);
assert_ne!(requests[0]["workDoneToken"], requests[1]["workDoneToken"]);
if timeout {
tokio::time::pause();
tokio::time::advance(Duration::from_secs(31)).await;
tokio::time::resume();
} else {
assert!(ide_core::task::cancel(task));
}
let found = batch.await.unwrap();
gate.open();
eventually(|| !server.notified("$/cancelRequest").is_empty()).await;
assert!(found[0].is_empty());
assert_eq!(found[1][0].range.start.line, 2);
assert!(!ide_core::task::cancel(task));
assert_eq!(task_events().iter().filter(|(id, done, _, _)| *id == task && *done).count(), 1);
// Late progress for either retired token must not bring back its task.
let before = task_events();
let peer = server.peer();
for request in requests {
peer.notify(
"$/progress",
json!({
"token": request["workDoneToken"], "value": { "kind": "begin", "title": "Go to Implementation" }
}),
)
.unwrap();
}
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
assert_eq!(task_events(), before);
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "end" } })).unwrap();
h.wait_status("mock", ServerStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_implementations_come_from_sources_first() {
let caps = json!({
@@ -8859,7 +9020,7 @@ async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() {
h.wait_status("sourcekit-lsp", ServerStatus::Ready).await;
eventually(|| h.launcher.state("sourcekit-lsp").docs.lock().contains_key(&uri_of(&path))).await;
assert!(h.statuses("clangd").is_empty(), "{language}");
assert_eq!(h.mgr.servers().iter().map(|s| s.root.clone()).collect::<Vec<_>>(), [h.root.clone()]);
assert_eq!(h.mgr.servers().iter().map(|s| s.root.clone()).collect::<Vec<_>>(), std::slice::from_ref(&h.root));
h.mgr.shutdown_all().await;
// sourcekit-lsp not installed: clangd still serves.
+3
Переглянути файл
@@ -428,6 +428,7 @@ async fn missing_binary_is_reported_with_install_hint() {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
};
@@ -721,6 +722,7 @@ async fn typescript_language_server_end_to_end() {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
};
@@ -775,6 +777,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
+4 -3
Переглянути файл
@@ -67,9 +67,10 @@ pub trait ToolRegistry: Send + Sync + 'static {
/// Roots of the projects open in a window of the IDE that the server serves.
fn projects(&self) -> Vec<PathBuf>;
/// The root of the project the IDE serves `path` from without a window (a background
/// project), asked when no project of [`Self::projects`] contains `path`. Opens nothing:
/// the first call for that root does.
fn resolve(&self, _path: &Path) -> Option<PathBuf> {
/// project). `within` is the root of the innermost project of [`Self::projects`] that
/// contains `path`, when one does: then only a root strictly inside it answers, and the
/// open project keeps the path otherwise. Opens nothing: the first call for that root does.
fn resolve(&self, _path: &Path, _within: Option<&Path>) -> Option<PathBuf> {
None
}
/// The tools callable for `project` (one of [`Self::projects`] or a root
+32 -10
Переглянути файл
@@ -223,9 +223,7 @@ impl Session<'_> {
roots.sort();
roots.dedup();
if let Some(requested) = requested.filter(|p| !p.trim().is_empty()) {
let path = Path::new(requested);
// An open project wins; the registry is asked only for a folder outside all of them.
return resolve(&roots, path).or_else(|| self.registry.resolve(path)).ok_or_else(|| {
return self.serving_root(&roots, Path::new(requested)).ok_or_else(|| {
RpcError::new(
NOT_OPEN,
format!(
@@ -247,10 +245,30 @@ impl Session<'_> {
),
))
}
/// The innermost project containing `path`, whether a window has it open (one of `roots`)
/// or the registry serves it in the background, so the answer doesn't depend on which
/// windows are open. Inside an open project the registry is asked only for a path below
/// its root, about the folders inside that root: a folder of a window's project that no
/// nested project holds loads nothing.
fn serving_root(&self, roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
let Some(open) = resolve(roots, path) else { return self.registry.resolve(path, None) };
let nested = if open.below { self.registry.resolve(path, Some(&open.root)) } else { None };
Some(nested.unwrap_or(open.root))
}
}
/// The innermost open project containing a path.
#[derive(Debug, PartialEq)]
struct OpenRoot {
/// As the registry lists it.
root: PathBuf,
/// Whether the path lies below the root rather than at it.
below: bool,
}
/// The project among `roots` containing `path` (the innermost one).
fn resolve(roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
fn resolve(roots: &[PathBuf], path: &Path) -> Option<OpenRoot> {
if !path.is_absolute() {
return None;
}
@@ -274,7 +292,7 @@ fn resolve(roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
path.starts_with(&canonical).then(|| (canonical.components().count(), root))
})
.max_by_key(|(depth, _)| *depth)
.map(|(_, root)| root.clone())
.map(|(depth, root)| OpenRoot { root: root.clone(), below: path.components().count() > depth })
}
fn tool_json(tool: &Tool) -> Value {
@@ -299,11 +317,15 @@ mod tests {
let inner = outer.join("inner");
std::fs::create_dir_all(inner.join("src")).unwrap();
let roots = [outer.clone(), inner.clone()];
assert_eq!(resolve(&roots, &inner.join("src")), Some(inner.clone()));
assert_eq!(resolve(&roots, &outer.join("other")), Some(outer.clone()));
assert_eq!(resolve(&roots[1..], &outer), None);
assert_eq!(resolve(&roots, Path::new("relative/path")), None);
let root = |roots: &[PathBuf], path: &Path| resolve(roots, path).map(|open| open.root);
assert_eq!(root(&roots, &inner.join("src")), Some(inner.clone()));
assert_eq!(root(&roots, &outer.join("other")), Some(outer.clone()));
assert_eq!(root(&roots[1..], &outer), None);
assert_eq!(root(&roots, Path::new("relative/path")), None);
// Siblings sharing a prefix are not inside.
assert_eq!(resolve(&roots[1..], &outer.join("inner-two")), None);
assert_eq!(root(&roots[1..], &outer.join("inner-two")), None);
// Only a path below the root is below it.
assert_eq!(resolve(&roots, &inner), Some(OpenRoot { root: inner.clone(), below: false }));
assert_eq!(resolve(&roots, &inner.join("src")), Some(OpenRoot { root: inner.clone(), below: true }));
}
}
+45 -10
Переглянути файл
@@ -225,18 +225,22 @@ async fn folders_that_are_not_open_are_named_in_the_error() {
assert!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"].is_array());
}
/// One project open in a window and, optionally, one folder served without a window.
/// One project open in a window and the folders served without a window.
struct WithBackground {
open: PathBuf,
background: Option<PathBuf>,
background: Vec<PathBuf>,
}
impl ToolRegistry for WithBackground {
fn projects(&self) -> Vec<PathBuf> {
vec![self.open.clone()]
}
fn resolve(&self, path: &Path) -> Option<PathBuf> {
self.background.clone().filter(|root| path.starts_with(root))
/// The innermost served folder containing `path`, strictly inside `within`, as the
/// background policy answers.
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
let inside = |root: &&PathBuf| within.is_none_or(|open| root.starts_with(open) && *root != open);
let served = self.background.iter().filter(|root| path.starts_with(root)).filter(inside);
served.max_by_key(|root| root.components().count()).cloned()
}
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
Ok(vec![Tool {
@@ -253,13 +257,16 @@ impl ToolRegistry for WithBackground {
}
}
/// The server over [`WithBackground`]; the folder `inventory` next to the open project.
fn setup_with_background(served: bool) -> (Setup, PathBuf) {
/// The server over [`WithBackground`] serving the `served` folders, relative to the folder
/// that holds the open project; the folder `inventory` next to the open project.
fn setup_with_background(served: &[&str]) -> (Setup, PathBuf) {
let mut s = setup();
s.server.take().unwrap().stop();
let inventory = s.project.parent().unwrap().join("inventory");
let base = s.project.parent().unwrap().to_path_buf();
let inventory = base.join("inventory");
std::fs::create_dir_all(inventory.join("src")).unwrap();
let registry = WithBackground { open: s.project.clone(), background: served.then(|| inventory.clone()) };
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
let registry = WithBackground { open: s.project.clone(), background };
s.server = Some(
McpServer::start_with(Arc::new(registry), None, &tokio::runtime::Handle::current(), ServerOptions::default())
.unwrap(),
@@ -277,7 +284,7 @@ async fn rpc_for(s: &Setup, folder: &Path, method: &str, params: Value) -> Value
#[tokio::test(flavor = "multi_thread")]
async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
let (s, inventory) = setup_with_background(true);
let (s, inventory) = setup_with_background(&["inventory"]);
let inside = inventory.join("src");
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
@@ -296,9 +303,37 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
assert_eq!(open["result"]["structuredContent"]["project"], json!(s.project), "{open}");
}
#[tokio::test(flavor = "multi_thread")]
async fn the_innermost_project_answers_whether_a_window_has_it_open_or_it_is_served_in_the_background() {
// The layout of #7040: a window on `project` and `contracts` inside it served in the
// background. The policy serves the window's root and the folder around it as well, as
// trusted projects and listed folders do.
let (s, _) = setup_with_background(&["", "project", "project/contracts"]);
let contracts = s.project.join("contracts");
std::fs::create_dir_all(contracts.join("src")).unwrap();
let base = s.project.parent().unwrap().to_path_buf();
for (folder, served) in [
(contracts.join("src"), &contracts),
(contracts.clone(), &contracts),
// Folders of the window's project that no nested project holds stay with the window.
(s.project.join("src"), &s.project),
(s.project.clone(), &s.project),
(base.join("elsewhere"), &base),
] {
let at = folder.display();
let call = rpc(&s, "tools/call", json!({ "name": "where", "arguments": { "projectPath": folder } })).await;
assert_eq!(call["result"]["structuredContent"]["project"], json!(served), "{at}: {call}");
let list = rpc_for(&s, &folder, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", served.display()), "{at}: {list}");
let init = rpc_for(&s, &folder, "initialize", json!({})).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(&format!("serves at {}:", served.display())), "{at}: {instructions}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
let (s, inventory) = setup_with_background(false);
let (s, inventory) = setup_with_background(&[]);
for (method, params) in [("tools/list", json!({})), ("tools/call", json!({ "name": "where" }))] {
let reply = rpc_for(&s, &inventory, method, params).await;
assert_eq!(reply["error"]["code"], -32001, "{method}: {reply}");
+4 -2
Переглянути файл
@@ -225,7 +225,9 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
args.push("--no-TTY".into());
}
}
RunTargetKind::Ssh => return Err(IdeError::internal("an SSH target does not run in a container")),
RunTargetKind::Ssh | RunTargetKind::Wsl => {
return Err(IdeError::internal("this run target does not run in a container"));
}
}
args.extend(["--name".into(), run.name.to_owned(), "--label".into(), format!("openidea.run={}", config.id)]);
args.extend(["--workdir".into(), command.cwd.clone()]);
@@ -341,7 +343,7 @@ pub fn python_probe_args(target: &RunTarget, root: &Path, name: &str, code: &str
}
args.extend(["run", "--no-deps", "--no-TTY"].map(String::from));
}
RunTargetKind::Ssh => {
RunTargetKind::Ssh | RunTargetKind::Wsl => {
return Err(IdeError::invalid(format!("Run target '{}' is not a container", target.name)));
}
}
+3 -1
Переглянути файл
@@ -1,5 +1,6 @@
//! Remote work over SSH: SFTP deployment ([`deploy`], [`mapping`]) and run
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`]).
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`], WSL
//! ones in [`wsl`]).
pub mod container_tunnel;
pub mod deploy;
@@ -10,6 +11,7 @@ pub mod mapping;
pub mod service;
pub mod target;
pub mod upload;
pub mod wsl;
pub use deploy::{
Deployment, DeploymentCoverage, SyncAction, SyncEntry, SyncStatus, SyncStep, TransferReport, coverage,
+1 -1
Переглянути файл
@@ -438,7 +438,7 @@ impl RemoteService {
let target_id = config.extras.target.as_deref().unwrap_or_default();
let target = run_target(settings, target_id)?;
if target.kind != ide_core::remote_settings::RunTargetKind::Ssh {
return Err(IdeError::internal("container run targets start as local runs of the docker CLI"));
return Err(IdeError::internal("container and WSL run targets start as local runs"));
}
let session = self.ssh.session(&target.ssh_config).await?;
let fs = RemoteFs::new(session.sftp().await?).with_shell(session.clone());
+8 -2
Переглянути файл
@@ -72,7 +72,8 @@ fn replace_root(s: &str, root: &str, remote: &str) -> String {
out.push_str(remote);
if root.contains('\\') {
let end = after
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ',' | '"' | '\''))
// `:` too: past the drive letter, it only separates a POSIX path list.
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ':' | ',' | '"' | '\''))
.unwrap_or(after.len());
out.push_str(&after[..end].replace('\\', "/"));
after = &after[end..];
@@ -191,7 +192,7 @@ pub fn debugpy_probe(debug: &RemoteCommand, bootstrap: &str) -> String {
/// `java` flags whose value is a path list that may point outside the project
/// (`~/.m2` jars, `--module-path` entries): deployment sync only uploads the
/// project root, so these entries need their own sync + rewrite (#2641).
const PATH_LIST_FLAGS: [&str; 6] =
pub(crate) const PATH_LIST_FLAGS: [&str; 6] =
["-cp", "-classpath", "--class-path", "-p", "--module-path", "--upgrade-module-path"];
/// The separator of a `-cp` value on this (client) machine.
@@ -635,6 +636,11 @@ mod tests {
assert_eq!(replace_root("/work/proj2/x:/work/proj/y", "/work/proj", "/srv"), "/work/proj2/x:/srv/y");
assert_eq!(replace_root("/work/proj", "/work/proj", "/srv"), "/srv");
assert_eq!(replace_root(r"C:\p\src/a.py C:\p2", r"C:\p", "/srv"), r"/srv/src/a.py C:\p2");
assert_eq!(
replace_root(r"C:\work\proj:C:\work\proj\src", r"C:\work\proj", "/mnt/c/work/proj"),
"/mnt/c/work/proj:/mnt/c/work/proj/src",
"each root of a PYTHONPATH list"
);
}
/// Unix/Windows spellings of the same layout: one inside-root entry, one
+426
Переглянути файл
@@ -0,0 +1,426 @@
//! Run configurations on WSL run targets: rewritten into a local run of
//! `wsl.exe -d <distro> --cd <dir> --exec <program> <args>`, with the project's paths
//! and interpreters swapped for their Linux counterparts. The console, stdin, Stop and
//! test parsers then work as for any local run.
use crate::target::remote_command;
use ide_core::remote_settings::RunTarget;
use ide_core::{IdeError, IdeResult};
use ide_run::RunConfig;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// Where the project is inside the target's distribution.
pub fn project_root(target: &RunTarget, root: &Path) -> IdeResult<String> {
match target.project_root.trim().trim_end_matches('/') {
"" if target.project_root.trim().starts_with('/') => Ok("/".into()),
"" => ide_core::wsl::linux_path(root, target.distro.trim()).ok_or_else(|| {
IdeError::invalid(format!(
"Run target '{}' can't reach {} from WSL: set the project's Linux path in Settings › Run Targets",
target.name,
root.display()
))
}),
folder => Ok(folder.to_owned()),
}
}
/// The file on this machine of a path a run in the target's distribution printed (a
/// traceback line): in the project, on a drive under `/mnt/<drive>`, else in the
/// distribution's own file system (`\\wsl.localhost\<distro>`).
pub fn local_file(path: &str, target: &RunTarget, root: &Path) -> Option<PathBuf> {
if !path.starts_with('/') {
return None;
}
if let Ok(linux_root) = project_root(target, root) {
let linux_root = linux_root.trim_end_matches('/');
if let Some(rest) =
path.strip_prefix(linux_root).filter(|r| r.is_empty() || r.starts_with('/') || linux_root.is_empty())
{
return Some(ide_core::wsl::path_parts(rest).into_iter().fold(root.to_path_buf(), |p, c| p.join(c)));
}
}
Some(ide_core::wsl::windows_path(path, target.distro.trim()))
}
fn is_java(command: &str) -> bool {
let name = command.trim().rsplit(['/', '\\']).next().unwrap_or("");
name.to_ascii_lowercase().trim_end_matches(".exe") == "java"
}
/// The `-cp` / `--module-path` values of `java` arguments as the distribution reads them:
/// each absolute entry outside the project through its `/mnt` path, joined with `:`.
/// Entries in the project stay as they are: `remote_command` maps them onto its folder there.
fn linux_path_lists(args: &[String], root: &Path, distro: &str) -> Vec<String> {
let mut out = args.to_vec();
for i in 1..out.len() {
if !crate::target::PATH_LIST_FLAGS.contains(&out[i - 1].as_str()) || out[i].contains("${") {
continue;
}
let entries: Vec<String> = out[i]
.split(crate::target::classpath_separator())
.filter(|e| !e.is_empty())
.map(|e| {
let path = Path::new(e);
if path.starts_with(root) {
return e.to_owned();
}
match path.is_absolute().then(|| ide_core::wsl::linux_path(path, distro)).flatten() {
Some(linux) => linux,
None => e.replace('\\', "/"),
}
})
.collect();
out[i] = entries.join(":");
}
out
}
/// The target's Python: its own, or `python3` on the distribution's `PATH`.
pub fn python(target: &RunTarget) -> &str {
match target.python.trim() {
"" => "python3",
python => python,
}
}
/// Run with `sh -c` in a distribution, the project's Linux folder as `$1`: prints the
/// Pythons found there, one path a line.
pub const FIND_PYTHONS: &str = r#"for p in "$(command -v python3)" "$(command -v python)" /usr/bin/python3* /usr/local/bin/python3* "$HOME"/.pyenv/versions/*/bin/python "$1/.venv/bin/python" "$1/venv/bin/python"; do case "$p" in *-config) continue ;; esac; [ -f "$p" ] && [ -x "$p" ] && echo "$p"; done; true"#;
/// The paths [`FIND_PYTHONS`] printed, without repeats and without the tools named after
/// Python (`python3-pytest`, `python3.12-config`).
pub fn parse_pythons(out: &str) -> Vec<String> {
let interpreter = |path: &str| {
let name = path.rsplit('/').next().unwrap_or("");
let version = name.strip_prefix("python").unwrap_or("-");
version.chars().all(|c| c.is_ascii_digit() || c == '.')
};
let mut found: Vec<String> = Vec::new();
for line in out.lines().map(str::trim).filter(|l| l.starts_with('/') && interpreter(l)) {
if !found.iter().any(|f| f == line) {
found.push(line.to_owned());
}
}
found
}
/// `config` as a local run of `wsl_exe` that runs it in the target's distribution.
/// `file_env` holds the variables of the configuration's `.env` files, already read;
/// `inherited_wslenv` is this machine's `WSLENV`, kept for the distribution.
pub fn wsl_config(
config: &RunConfig,
target: &RunTarget,
root: &Path,
linux_root: &str,
wsl_exe: &str,
file_env: &BTreeMap<String, String>,
inherited_wslenv: Option<&str>,
) -> IdeResult<RunConfig> {
let distro = target.distro.trim();
if !ide_core::wsl::is_valid_distro(distro) {
return Err(IdeError::invalid(format!(
"Run target '{}' has no WSL distribution; choose one in Settings › Run Targets",
target.name
)));
}
let mut command = if is_java(&config.command) {
let mut java = config.clone();
java.args = linux_path_lists(&config.args, root, distro);
remote_command(&java, target, root, linux_root)
} else {
remote_command(config, target, root, linux_root)
};
// Outside the project `remote_command` falls back to the project folder: a folder of
// this machine is reached through its own `/mnt` path instead.
if let Some(dir) = config.cwd.as_ref().map(|d| d.to_path_buf()).filter(|d| d.is_absolute() && !d.starts_with(root))
{
command.cwd = ide_core::wsl::linux_path(&dir, distro).ok_or_else(|| {
IdeError::invalid(format!(
"Run target '{}' can't reach the working folder {} from WSL",
target.name,
dir.display()
))
})?;
}
let mut env = file_env.clone();
if ide_run::is_python_kind(&config.kind) && !command.env.contains_key("PYTHONUNBUFFERED") {
env.insert("PYTHONUNBUFFERED".into(), "1".into());
}
env.extend(command.env.clone());
// The distribution keeps its own `PATH`: a value here is this machine's, or a `.env`
// `PATH=$PATH:…` already expanded against it.
env.remove("PATH");
let mut args: Vec<String> = ["-d", distro, "--cd", &command.cwd, "--exec"].map(String::from).to_vec();
// A Python run finds the console scripts next to the target's interpreter (a virtualenv's
// `pytest`) first, as a local run with the project interpreter does.
let scripts = (ide_run::is_python_kind(&config.kind) && target.python.trim().starts_with('/'))
.then(|| target.python.trim().rsplit_once('/').map(|(dir, _)| dir.to_owned()))
.flatten()
.filter(|dir| !dir.is_empty());
match (command.shell_line, scripts) {
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
(Some(line), Some(dir)) => args.extend(["sh".into(), "-c".into(), format!("PATH=\"$0:$PATH\"; {line}"), dir]),
(None, None) => {
args.push(command.program);
args.extend(command.args);
}
(None, Some(dir)) => {
args.extend(["sh".into(), "-c".into(), r#"PATH="$0:$PATH" exec "$@""#.into(), dir, command.program]);
args.extend(command.args);
}
}
// Values cross into the distribution through the environment (`WSLENV` lists the
// names), so they stay out of the command line echoed in the console. The configuration's
// own `WSLENV` entries (`FOO/p`) are kept with their flags.
let own = env.remove("WSLENV");
let mut wslenv: Vec<&str> = inherited_wslenv
.into_iter()
.chain(own.as_deref())
.flat_map(|v| v.split(':'))
.filter(|n| !n.is_empty())
.collect();
let listed = |name: &str, list: &[&str]| list.iter().any(|n| n.split('/').next() == Some(name));
for name in env.keys() {
if !listed(name, &wslenv) {
wslenv.push(name);
}
}
let wslenv = wslenv.join(":");
if !wslenv.is_empty() {
env.insert("WSLENV".into(), wslenv);
}
let mut out = config.clone();
out.command = wsl_exe.to_owned();
out.args = args;
out.cwd = Some(root.to_path_buf().into());
out.env = env;
let extras = &mut out.extras;
extras.target = None;
extras.env_files.clear();
// `wsl.exe` needs this machine's environment; the distribution gets only `WSLENV`'s names.
extras.include_system_env = true;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::remote_settings::RunTargetKind;
fn target() -> RunTarget {
RunTarget { kind: RunTargetKind::Wsl, name: "wsl".into(), distro: "Ubuntu-24.04".into(), ..Default::default() }
}
fn config(command: &str, args: &[&str]) -> RunConfig {
RunConfig {
id: "app".into(),
name: "app".into(),
kind: "python".into(),
command: command.into(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
cwd: None,
env: BTreeMap::new(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
}
}
#[test]
fn the_project_root_is_the_targets_or_its_mnt_path() {
let t = target();
assert_eq!(project_root(&t, Path::new(r"C:\work\proj")).unwrap(), "/mnt/c/work/proj");
assert_eq!(project_root(&t, Path::new(r"\\wsl.localhost\Ubuntu-24.04\home\me\p")).unwrap(), "/home/me/p");
let err = project_root(&t, Path::new(r"\\server\share\p")).unwrap_err();
assert!(err.message.contains("set the project's Linux path"), "{}", err.message);
let custom = RunTarget { project_root: " /c/work/proj/ ".into(), ..t.clone() };
assert_eq!(project_root(&custom, Path::new(r"\\server\share\p")).unwrap(), "/c/work/proj");
let slash = RunTarget { project_root: "/".into(), ..t };
assert_eq!(project_root(&slash, Path::new("x")).unwrap(), "/");
}
// Unix paths are not absolute on Windows; `windows_paths_are_mapped` covers Windows.
#[cfg(unix)]
#[test]
fn a_program_runs_through_wsl_exe_with_its_variables_by_name() {
let mut c = config("/work/proj/.venv/bin/python", &["-u", "/work/proj/main.py", "a b"]);
c.cwd = Some(Path::new("/work/proj/src").to_path_buf().into());
c.env.insert("DATA".into(), "/work/proj/data".into());
c.extras.target = Some("t".into());
c.extras.env_files = vec![".env".into()];
let files = BTreeMap::from([("SECRET".to_owned(), "s3".to_owned())]);
let out =
wsl_config(&c, &target(), Path::new("/work/proj"), "/mnt/c/proj", "wsl.exe", &files, Some("USERPROFILE/p"))
.unwrap();
assert_eq!(out.command, "wsl.exe");
assert_eq!(
out.args,
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj/src", "--exec", "python3", "-u", "/mnt/c/proj/main.py", "a b"]
);
assert_eq!(out.env["DATA"], "/mnt/c/proj/data");
assert_eq!(out.env["SECRET"], "s3");
assert_eq!(out.env["PYTHONUNBUFFERED"], "1");
assert_eq!(out.env["WSLENV"], "USERPROFILE/p:DATA:PYTHONUNBUFFERED:SECRET");
assert_eq!(out.cwd.as_ref().map(|p| p.to_path_buf()), Some(Path::new("/work/proj").to_path_buf()));
assert_eq!(out.extras.target, None);
assert!(out.extras.env_files.is_empty());
assert!(out.extras.include_system_env);
}
#[test]
fn a_shell_line_runs_in_sh_and_the_targets_interpreter_is_used() {
let mut shell = config("npm run dev", &[]);
shell.kind = "shell".into();
let out =
wsl_config(&shell, &target(), Path::new("proj"), "/mnt/c/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args, ["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj", "--exec", "sh", "-c", "npm run dev"]);
assert!(!out.env.contains_key("WSLENV"));
let t = RunTarget { python: "/home/me/.venv/bin/python".into(), ..target() };
let out =
wsl_config(&config("python.exe", &["-V"]), &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None)
.unwrap();
let path_first = r#"PATH="$0:$PATH" exec "$@""#;
assert_eq!(
&out.args[4..],
["--exec", "sh", "-c", path_first, "/home/me/.venv/bin", "/home/me/.venv/bin/python", "-V"],
"the virtualenv's scripts come first on PATH"
);
let mut pytest = config("pytest", &["tests"]);
pytest.kind = "pytest".into();
let out = wsl_config(&pytest, &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(&out.args[9..], ["pytest", "tests"]);
}
#[test]
fn a_configurations_wslenv_keeps_its_flags_and_an_outside_folder_is_refused() {
let mut c = config("python", &[]);
c.env.insert("WSLENV".into(), "DATA/p".into());
c.env.insert("DATA".into(), "x".into());
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), Some("A/u")).unwrap();
assert_eq!(out.env["WSLENV"], "A/u:DATA/p:PYTHONUNBUFFERED");
c.env.insert("PATH".into(), "/here/bin:/usr/bin".into());
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert!(!out.env.contains_key("PATH") && !out.env["WSLENV"].contains("PATH"), "{:?}", out.env);
// An absolute folder of this machine outside the project (`/elsewhere` has no `/mnt` path).
let outside = if cfg!(windows) { r"\\server\share\x" } else { "/elsewhere" };
c.cwd = Some(Path::new(outside).to_path_buf().into());
let root = if cfg!(windows) { r"C:\proj" } else { "/proj" };
let err = wsl_config(&c, &target(), Path::new(root), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap_err();
assert!(err.message.contains("can't reach the working folder"), "{}", err.message);
}
#[cfg(unix)]
#[test]
fn java_path_lists_are_joined_with_colons() {
let args: Vec<String> = ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"].map(String::from).to_vec();
assert_eq!(linux_path_lists(&args, Path::new("/p"), "Ubuntu"), ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"]);
assert!(is_java("/usr/lib/jvm/bin/java") && is_java(r"C:\jdk\bin\JAVA.EXE") && !is_java("javac"));
}
#[test]
fn printed_paths_lead_back_to_files_here() {
let t = RunTarget { project_root: "/mnt/c/work/proj".into(), ..target() };
let root = Path::new("proj-here");
assert_eq!(local_file("/mnt/c/work/proj/app/main.py", &t, root), Some(root.join("app").join("main.py")));
assert_eq!(
local_file("/mnt/d/lib/x.py", &t, root),
Some(PathBuf::from("D:\\").join("lib").join("x.py")),
"another drive"
);
assert_eq!(
local_file("/usr/lib/python3/dist-packages/a.py", &t, root),
Some(
ide_core::wsl::share_root("Ubuntu-24.04")
.join("usr")
.join("lib")
.join("python3")
.join("dist-packages")
.join("a.py")
)
);
assert_eq!(
local_file("/mnt/c/work/proj2/a.py", &t, root),
Some(PathBuf::from("C:\\").join("work").join("proj2").join("a.py"))
);
assert_eq!(local_file("main.py", &t, root), None);
assert_eq!(local_file("/mnt/c/work/proj/app/../lib/a.py", &t, root), Some(root.join("lib").join("a.py")));
}
#[test]
fn pythons_are_listed_once_and_python3_is_the_default() {
let out = "/usr/bin/python3\n\n/usr/bin/python3\n/usr/bin/python3.12\nsh: 1: bad\n/usr/bin/python3-pytest\n\
/usr/bin/python3.12-config\n/mnt/c/p/.venv/bin/python\r\n";
assert_eq!(parse_pythons(out), ["/usr/bin/python3", "/usr/bin/python3.12", "/mnt/c/p/.venv/bin/python"]);
assert_eq!(python(&target()), "python3");
assert_eq!(python(&RunTarget { python: " /opt/py/bin/python ".into(), ..target() }), "/opt/py/bin/python");
}
// The script itself, in this machine's `sh`.
#[cfg(unix)]
#[test]
fn the_python_finder_lists_a_venv_of_the_project() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join(".venv/bin");
std::fs::create_dir_all(&bin).unwrap();
let python = bin.join("python");
std::fs::write(&python, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&python, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
let out = std::process::Command::new("sh").args(["-c", FIND_PYTHONS, "sh"]).arg(dir.path()).output().unwrap();
assert!(out.status.success());
let found = parse_pythons(&String::from_utf8_lossy(&out.stdout));
assert!(found.contains(&python.to_string_lossy().into_owned()), "{found:?}");
assert!(found.iter().all(|p| !p.ends_with("-config")), "{found:?}");
}
#[test]
fn a_target_without_a_valid_distribution_is_refused() {
for distro in ["", " ", "-u root", "a;b"] {
let t = RunTarget { distro: distro.into(), ..target() };
let err = wsl_config(&config("python", &[]), &t, Path::new("p"), "/p", "wsl.exe", &BTreeMap::new(), None)
.unwrap_err();
assert!(err.message.contains("no WSL distribution"), "{distro}: {}", err.message);
}
}
#[cfg(windows)]
#[test]
fn windows_paths_are_mapped() {
let root = Path::new(r"C:\work\proj");
let linux = project_root(&target(), root).unwrap();
let mut c = config(r"C:\work\proj\.venv\Scripts\python.exe", &[r"C:\work\proj\app\main.py"]);
c.cwd = Some(Path::new(r"C:\work\proj\app").to_path_buf().into());
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(
out.args,
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/work/proj/app", "--exec", "python3", "/mnt/c/work/proj/app/main.py"]
);
let java = config(
r"C:\jdk\bin\java.exe",
&["-cp", r"C:\work\proj\out;D:\m2\a.jar;lib\*", "--module-path", r"C:\work\proj\mods", "app.Main"],
);
let out = wsl_config(&java, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(
&out.args[4..],
[
"--exec",
"java",
"-cp",
"/mnt/c/work/proj/out:/mnt/d/m2/a.jar:lib/*",
"--module-path",
"/mnt/c/work/proj/mods",
"app.Main"
]
);
let custom = RunTarget { project_root: "/home/me/proj".into(), ..target() };
let java = config(r"C:\jdk\bin\java.exe", &["-cp", r"C:\work\proj\out;D:\m2\a.jar", "app.Main"]);
let out = wsl_config(&java, &custom, root, "/home/me/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args[7], "/home/me/proj/out:/mnt/d/m2/a.jar", "project entries go to its folder there");
c.cwd = Some(Path::new(r"D:\data").to_path_buf().into());
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args[3], "/mnt/d/data", "a folder outside the project, through its /mnt path");
}
}
+47 -8
Переглянути файл
@@ -1027,13 +1027,13 @@ pub fn artifact_is_current(root: &Path, base: &Path, config: &RunConfig, modules
let id_matches = selected.is_none_or(|id| recorded_id.as_deref().map(str::trim) == Some(id.as_str()));
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
let war = match recorded.filter(|_| id_matches) {
Some(war) if war.is_file() && is_war(&war) => war,
Some(war) if (war.is_file() && is_war(&war)) || war.is_dir() => war,
_ => match find_built_war(root, Some(&module)) {
Some(war) => war,
None => return false,
},
};
let Ok(war_time) = fs::metadata(&war).and_then(|m| m.modified()) else { return false };
let Some(war_time) = newest_mtime_under(&war) else { return false };
let mut newest = newest_mtime_under(&module.join("src"));
// Web content packaged from outside `src` (a custom `warSourceDirectory`, `webResources`
// directories, a custom Gradle web app dir) also lands in the WAR — the running-session
@@ -1077,12 +1077,10 @@ pub fn deployment(root: &Path, base: &Path, config: &RunConfig, resources_only:
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
let module = artifact_module_dir(root, config);
let war = match recorded.filter(|_| id_matches) {
Some(war) => {
if war.is_file() && is_war(&war) {
war
} else {
return Err(invalid(format!("The built WAR artifact does not exist: {}", war.display())));
}
Some(path) if path.is_file() && is_war(&path) => path,
Some(path) if path.is_dir() => return Ok(path),
Some(path) => {
return Err(invalid(format!("The built WAR artifact does not exist: {}", path.display())));
}
None => find_built_war(root, Some(module.as_path())).ok_or_else(|| {
invalid("No built WAR artifact found - build the project first, or add 'Build' to Before launch")
@@ -2417,4 +2415,45 @@ mod tests {
let error = prepare(root, &cache, &mut c).unwrap_err().to_string();
assert!(error.contains("Two deployments use the application context /"), "{error}");
}
#[test]
fn deploys_recorded_exploded_artifact_directory_directly() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let home = root.join("Tomcat Home");
fs::create_dir_all(home.join("bin")).unwrap();
fs::create_dir_all(home.join("conf")).unwrap();
fs::write(home.join("bin/catalina.sh"), "").unwrap();
fs::write(home.join("bin/catalina.bat"), "").unwrap();
archive(
&home.join("lib/catalina.jar"),
&[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat/10.1")],
);
let server = "<Server port='8005'><Service><Connector port='8080'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
fs::write(home.join("conf/server.xml"), server).unwrap();
let exploded = root.join("out/artifacts/EJSH_war_exploded");
fs::create_dir_all(exploded.join("WEB-INF")).unwrap();
fs::write(exploded.join("WEB-INF/web.xml"), "<web-app/>").unwrap();
let mut c = config();
for (k, v) in [
("tomcatHome", "Tomcat Home"),
("deployment", "artifact"),
("artifact", "project:EJSH:war exploded"),
("artifactName", "EJSH"),
] {
c.extras.params.insert(k.into(), v.into());
}
let cache = root.join("cache");
let base = base_dir(&cache, &c.id);
fs::create_dir_all(&base).unwrap();
fs::write(base.join("artifact-id.txt"), "project:EJSH:war exploded").unwrap();
fs::write(base.join("artifact-path.txt"), exploded.to_string_lossy().as_bytes()).unwrap();
prepare(root, &cache, &mut c).unwrap();
let runtime = PathBuf::from(&c.env["CATALINA_BASE"]);
let ctx = fs::read_to_string(runtime.join("conf/Catalina/localhost/EJSH.xml")).unwrap();
assert!(ctx.contains(&format!("docBase=\"{}\"", escape(&exploded.to_string_lossy()))), "{ctx}");
assert!(artifact_is_current(root, &runtime, &c, &[]));
}
}
+1
Переглянути файл
@@ -1811,6 +1811,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
+39 -5
Переглянути файл
@@ -81,7 +81,11 @@ pub fn folders_to_copy(probe: &Probe, container_root: &str) -> Vec<String> {
/// Where a snapshot in `dir` keeps its copy of the container folder `container`.
pub fn local_folder(dir: &Path, container: &str) -> PathBuf {
container.split('/').filter(|c| !c.is_empty() && *c != "." && *c != "..").fold(dir.join("fs"), |p, c| p.join(c))
below(dir.join("fs"), container)
}
fn below(base: PathBuf, path: &str) -> PathBuf {
path.split('/').filter(|c| !c.is_empty() && *c != "." && *c != "..").fold(base, |p, c| p.join(c))
}
/// Where a snapshot in `dir` keeps the file `container_path` of its container (a
@@ -91,7 +95,7 @@ pub fn snapshot_file(dir: &Path, snapshot: &Snapshot, container_path: &str) -> O
.folders
.iter()
.any(|f| container_path.strip_prefix(f.trim_end_matches('/')).is_some_and(|rest| rest.starts_with('/')));
(copied && !container_path.split('/').any(|c| c == "..")).then(|| local_folder(dir, container_path))
(copied && !container_path.split('/').any(|c| c == "..")).then(|| snapshot.local(dir, container_path))
}
/// `snapshot.json` of a snapshot folder.
@@ -105,6 +109,21 @@ pub struct Snapshot {
pub folders: Vec<String>,
/// The neutral interpreter given to the language server; `None` without a local Python.
pub neutral_python: Option<PathBuf>,
/// A WSL interpreter's distribution. Its folders are read in place, not copied: on their
/// drive under `/mnt/<drive>`, the rest through `\\wsl.localhost\<distro>`.
#[serde(skip_serializing_if = "Option::is_none")]
pub distro: Option<String>,
}
impl Snapshot {
/// Where this machine reads the interpreter's folder or file `path`.
pub fn local(&self, dir: &Path, path: &str) -> PathBuf {
match &self.distro {
// `..` never climbs above the drive or the distribution's share.
Some(distro) => ide_core::wsl::windows_path(path, distro),
None => local_folder(dir, path),
}
}
}
const SNAPSHOT_FILE: &str = "snapshot.json";
@@ -160,8 +179,11 @@ pub fn make_current(target_dir: &Path, image: &str) -> IdeResult<()> {
}
/// The local folders of a snapshot that exist.
/// A WSL snapshot's folders are taken as they were probed: checking them would read the
/// distribution's file system, which may be slow or still starting.
pub fn local_folders(dir: &Path, snapshot: &Snapshot) -> Vec<PathBuf> {
snapshot.folders.iter().map(|f| local_folder(dir, f)).filter(|p| p.is_dir()).collect()
let folders = snapshot.folders.iter().map(|f| snapshot.local(dir, f));
if snapshot.distro.is_some() { folders.collect() } else { folders.filter(|p| p.is_dir()).collect() }
}
/// basedpyright / pyright: the neutral interpreter and the snapshot's folders as
@@ -189,8 +211,8 @@ pub fn library_group(target_name: &str, dir: &Path, snapshot: &Snapshot) -> Opti
let roots: Vec<LibraryRoot> = snapshot
.folders
.iter()
.map(|f| (f, local_folder(dir, f)))
.filter(|(_, p)| p.is_dir())
.map(|f| (f, snapshot.local(dir, f)))
.filter(|(_, p)| snapshot.distro.is_some() || p.is_dir())
.map(|(f, p)| LibraryRoot { name: f.rsplit('/').next().unwrap_or(f).to_owned(), path: p.into() })
.collect();
(!roots.is_empty()).then(|| LibraryGroup {
@@ -318,6 +340,17 @@ mod tests {
local_folder(dir, "/usr/local/lib/../site-packages"),
Path::new("snap").join("fs").join("usr").join("local").join("lib").join("site-packages")
);
let wsl = Snapshot { distro: Some("U".into()), ..Snapshot::default() };
assert_eq!(
wsl.local(dir, "/usr/lib/python3/dist-packages"),
ide_core::wsl::share_root("U").join("usr").join("lib").join("python3").join("dist-packages"),
"a WSL snapshot reads the distribution in place"
);
assert_eq!(
wsl.local(dir, "/mnt/c/p/.venv/lib"),
PathBuf::from("C:\\").join("p").join(".venv").join("lib"),
"a drive directly"
);
assert_eq!(dir_name("sha256:0123456789abcdef0123"), "0123456789abcdef");
assert_eq!(dir_name("target/../x y"), "target____x_y");
}
@@ -344,6 +377,7 @@ mod tests {
probe: probe(),
folders: vec!["/usr/local/lib/python3.12/site-packages".into(), "/gone".into()],
neutral_python: neutral,
distro: None,
};
let site = local_folder(dir, &snapshot.folders[0]);
std::fs::create_dir_all(site.join("Django-5.1.3.dist-info")).unwrap();
+37 -2
Переглянути файл
@@ -506,7 +506,8 @@ fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationT
let java = [".classpath", ".project"].iter().any(|f| root.join(f).is_file())
|| idea_java_project(root)
|| !s.languages.java.jdk.trim().is_empty()
|| !s.project_structure.source_roots.is_empty();
|| !s.project_structure.source_roots.is_empty()
|| !s.project_structure.libraries.is_empty();
if !java {
return Vec::new();
}
@@ -521,11 +522,45 @@ fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationT
})
}
/// The class roots of Project Structure library entry `entry`: `dir/*.jar` and `dir/**/*.jar` list the
/// folder's jars, a folder holding jars (e.g. `WEB-INF/lib`) lists them all, anything else is itself.
pub fn library_class_paths(root: &Path, entry: &str) -> Vec<PathBuf> {
if let Some((base, recursive)) = ide_core::settings::split_jar_glob(entry) {
return crate::apply::setting_path(root, base)
.map(|dir| ide_core::settings::jar_files(&dir, recursive))
.unwrap_or_default();
}
let Some(path) = crate::apply::setting_path(root, entry.trim()) else { return Vec::new() };
if path.is_dir() {
let jars = ide_core::settings::jar_files(&path, true);
if !jars.is_empty() {
return jars;
}
}
vec![path]
}
fn project_structure_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
let mut out = Vec::new();
let push_archive = |roots: &mut Vec<LibraryRoot>, path: &Path| {
let label =
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
roots.push(LibraryRoot { name: label, path: ide_vfs::archive_root(path).into() });
};
for lib in &s.project_structure.libraries {
let mut roots = Vec::new();
for entry in lib.classes.iter().chain(&lib.sources) {
for path in lib.classes.iter().flat_map(|entry| library_class_paths(root, entry)) {
if path.is_file() {
push_archive(&mut roots, &path);
} else if path.is_dir() {
let label = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
roots.push(LibraryRoot { name: label, path: path.into() });
}
}
for entry in &lib.sources {
let Some(path) = crate::apply::setting_path(root, entry) else { continue };
let label = path
.file_name()
+17
Переглянути файл
@@ -46,6 +46,7 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
@@ -3655,6 +3656,22 @@ fn project_structure_module_jdk_language_level_and_external_libraries() {
});
let groups = crate::libraries::project_libraries(root, &settings, &[]);
assert!(groups.iter().any(|g| g.name == "servlet-api" && g.kind == "library" && g.roots.len() == 1));
let web_lib = root.join("WebRoot/WEB-INF/lib");
std::fs::create_dir_all(&web_lib).unwrap();
std::fs::write(web_lib.join("a.jar"), b"").unwrap();
std::fs::write(web_lib.join("b.jar"), b"").unwrap();
settings.project_structure.libraries.push(ide_core::settings::ProjectLibrary {
name: "web-lib".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
sources: vec![],
javadocs: vec![],
scope: ide_core::settings::DependencyScope::Runtime,
});
let groups = crate::libraries::project_libraries(root, &settings, &[]);
let web = groups.iter().find(|g| g.name == "web-lib" && g.kind == "library").unwrap();
let names: Vec<&str> = web.roots.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, vec!["a.jar", "b.jar"]);
}
#[test]
+22
Переглянути файл
@@ -681,6 +681,28 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/laravel/lsp",
needs: &[],
},
ToolSpec {
name: "phpantom",
display: "PHPantom",
kind: LanguageServer,
commands: &["phpantom_lsp"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "PHPantom-dev/phpantom_lsp" },
assets: &[
rule(Mac, Arm64, "phpantom_lsp-aarch64-apple-darwin.tar.gz"),
rule(Mac, X64, "phpantom_lsp-x86_64-apple-darwin.tar.gz"),
rule(Linux, Arm64, "phpantom_lsp-aarch64-unknown-linux-gnu.tar.gz"),
rule(Linux, X64, "phpantom_lsp-x86_64-unknown-linux-gnu.tar.gz"),
rule(Windows, Arm64, "phpantom_lsp-aarch64-pc-windows-msvc.zip"),
rule(Windows, X64, "phpantom_lsp-x86_64-pc-windows-msvc.zip"),
],
locate: &["phpantom_lsp"],
},
fallback: None,
version: ver("phpantom_lsp"),
homepage: "https://github.com/PHPantom-dev/phpantom_lsp",
needs: &[],
},
ToolSpec {
name: "phoxite",
display: "Phoxite",
+8
Переглянути файл
@@ -190,6 +190,7 @@ fn everything_missing_on_an_empty_system() {
#[test]
fn interchangeable_servers_list_their_alternatives() {
let env = Env::new();
env.script(&env.sys, "curl", "exit 1");
let list = env.tools().list(&langs());
let python = ["basedpyright", "pyright", "ty", "pyrefly"];
for name in python {
@@ -203,6 +204,13 @@ fn interchangeable_servers_list_their_alternatives() {
for name in ["kotlin-lsp", "kotlin-language-server"] {
assert_eq!(find(&list, name).alternatives, ["kotlin-lsp", "kotlin-language-server", "kmp-lsp"]);
}
let php = ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls"];
for name in php {
assert_eq!(find(&list, name).alternatives, php);
}
let phpantom = find(&list, "phpantom");
assert!(phpantom.can_install, "{:?}", phpantom.unavailable_reason);
assert!(find(&list, "laravel-lsp").alternatives.is_empty());
// A regular server after a fallback starts no group with it.
assert!(find(&list, "angular-language-server").alternatives.is_empty());
assert!(find(&list, "ruff").alternatives.is_empty());
+108 -2
Переглянути файл
@@ -920,6 +920,7 @@ fn log_indexed_rows(
text,
matches: HashMap::new(),
projected: HashMap::new(),
pruned: HashMap::new(),
cancel,
index,
table: table.as_ref(),
@@ -1010,6 +1011,7 @@ fn sort_subset(
let mut children = vec![0usize; ids.len()];
let mut times = Vec::with_capacity(ids.len());
let mut projected: HashMap<ObjectId, Vec<usize>> = HashMap::new();
let mut pruned: HashMap<ObjectId, Vec<ObjectId>> = HashMap::new();
for id in &ids {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -1071,11 +1073,27 @@ fn sort_subset(
.collect()
};
if !expanded {
let ancestors = without_redundant_parents(ancestors, cancel, |id| {
if let Some((ps, time)) = nodes.get(&id) {
return Ok(Some((
if shallow.contains(&id) { Vec::new() } else { ps.clone() },
*time,
)));
}
let Ok(commit) = repo.find_commit(id) else { return Ok(None) };
let parents = if shallow.contains(&id) {
Vec::new()
} else {
commit.parent_ids().map(|p| p.detach()).collect()
};
Ok(Some((parents, commit.time().map(|t| t.seconds).unwrap_or(0))))
})?;
stack.push((curr, true));
stack.extend(ancestors.iter().rev().map(|&p| (p, false)));
pruned.insert(curr, ancestors);
} else {
let mut combined = Vec::new();
for a in ancestors {
for a in pruned.remove(&curr).unwrap_or(ancestors) {
for &p in projected.get(&a).into_iter().flatten() {
if !combined.contains(&p) {
combined.push(p);
@@ -1177,6 +1195,70 @@ fn sort_subset(
/// Visibility and graph projection share exactly the same predicates. Revision parents
/// remain immutable; only graph parents skip hidden commits. Memoisation avoids walking
/// the same hidden ancestry for each visible child, without a truncation limit.
/// How many commits one ancestry check of [`without_redundant_parents`] may walk.
const REDUNDANT_PARENT_WALK: usize = 2_000;
/// `parents` of a commit the graph hides, without those that are ancestors of another of them:
/// whatever such a parent leads to is reached through the other one too. Without this, hiding the
/// merges of a pull-request history (`M_k = merge(M_k-1, F_k)`) projects every merge onto all older
/// features, so the projection grows with each merge and a long history never finishes.
/// `lookup` gives a commit's parents and time (`None`: not available). Each check walks back from
/// the other parent, skipping commits older than the candidate, for at most
/// [`REDUNDANT_PARENT_WALK`] commits; when unsure the parent is kept.
fn without_redundant_parents(
mut parents: Vec<ObjectId>,
cancel: &CancellationToken,
mut lookup: impl FnMut(ObjectId) -> IdeResult<Option<(Vec<ObjectId>, i64)>>,
) -> IdeResult<Vec<ObjectId>> {
let mut seen = HashSet::new();
parents.retain(|p| seen.insert(*p));
if parents.len() < 2 {
return Ok(parents);
}
let mut times = Vec::with_capacity(parents.len());
for p in &parents {
times.push(lookup(*p)?.map(|(_, t)| t));
}
let mut keep = vec![true; parents.len()];
for i in 0..parents.len() {
let Some(target_time) = times[i] else { continue };
for j in 0..parents.len() {
if i == j || !keep[j] || times[j].is_some_and(|t| t < target_time) {
continue;
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let (mut stack, mut visited) = (vec![parents[j]], HashSet::new());
let mut found = false;
while let Some(id) = stack.pop() {
if visited.len() >= REDUNDANT_PARENT_WALK {
break;
}
if !visited.insert(id) {
continue;
}
let Some((ps, time)) = lookup(id)? else { continue };
if id != parents[j] && time < target_time {
continue;
}
if ps.contains(&parents[i]) {
found = true;
break;
}
stack.extend(ps);
}
if found {
keep[i] = false;
break;
}
}
}
let mut keep = keep.into_iter();
parents.retain(|_| keep.next().unwrap_or(true));
Ok(parents)
}
struct Visibility<'a> {
speed_refs: &'a HashMap<ObjectId, Vec<String>>,
query: &'a LogQuery,
@@ -1186,6 +1268,8 @@ struct Visibility<'a> {
text: Option<TextFilter>,
matches: HashMap<ObjectId, bool>,
projected: HashMap<ObjectId, Vec<ObjectId>>,
/// The parents a hidden commit projects through, between its two visits.
pruned: HashMap<ObjectId, Vec<ObjectId>>,
cancel: &'a CancellationToken,
index: &'a mut crate::log_index::LogIndex,
table: Option<&'a redb::ReadOnlyTable<&'static str, &'static [u8]>>,
@@ -1272,6 +1356,26 @@ impl Visibility<'_> {
Ok(shown)
}
/// `parents` of a hidden commit without those reachable through another of them.
fn prune(&mut self, repo: &gix::Repository, parents: Vec<ObjectId>) -> IdeResult<Vec<ObjectId>> {
let (index, table, shallow) = (&mut *self.index, self.table, &self.shallow);
without_redundant_parents(parents, self.cancel, |id| {
if let Some((ps, time)) = index.nodes.get(&id) {
return Ok(Some((if shallow.contains(&id) { Vec::new() } else { ps.clone() }, *time)));
}
if !index.has_cached(&id) && !repo.has_object(id) {
return Ok(None);
}
let commit = index.get_with_table(repo, id, table)?;
let parents = if shallow.contains(&id) {
Vec::new()
} else {
commit.parents.iter().map(|p| ObjectId::from_hex(p.as_bytes()).map_err(gx)).collect::<IdeResult<_>>()?
};
Ok(Some((parents, (commit.commit_time_ms / 1000.0) as i64)))
})
}
fn parents(&mut self, repo: &gix::Repository, parents: &[ObjectId]) -> IdeResult<Vec<ObjectId>> {
let parents = if self.query.first_parent { &parents[..parents.len().min(1)] } else { parents };
let mut out = Vec::new();
@@ -1301,11 +1405,13 @@ impl Visibility<'_> {
.collect::<IdeResult<Vec<_>>>()?
};
if !expanded {
let ancestors = self.prune(repo, ancestors)?;
stack.push((id, true));
stack.extend(ancestors.iter().rev().map(|p| (*p, false)));
self.pruned.insert(id, ancestors);
} else {
let mut nearest = Vec::new();
for p in ancestors {
for p in self.pruned.remove(&id).unwrap_or(ancestors) {
for ancestor in self.projected.get(&p).into_iter().flatten() {
if !nearest.contains(ancestor) {
nearest.push(*ancestor);
+37 -3
Переглянути файл
@@ -15,6 +15,12 @@ const MAX_DEPTH: usize = 4;
/// Folders never searched for nested repositories (dependencies, build output).
const SKIPPED: &[&str] = &["node_modules", "target", "build", "dist", "out", "vendor", "venv", "__pycache__"];
/// A folder the nested-repository search neither looks at nor descends into.
fn not_searched(path: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
let name = path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(path)
}
/// The repositories of a project, sorted by root; lookups pick the innermost one.
#[derive(Clone, Default)]
pub struct Repos {
@@ -46,6 +52,18 @@ impl Repos {
Ok(Self { repos, primary })
}
/// Whether [`Self::discover`] from `project_root` looks for a repository at `dir`, below it.
pub fn searched(project_root: &Path, dir: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
let Ok(rel) = dir.strip_prefix(project_root) else { return false };
let depth = rel.components().count();
let mut path = project_root.to_path_buf();
(1..=MAX_DEPTH).contains(&depth)
&& rel.components().all(|c| {
path.push(c);
!not_searched(&path, skip)
})
}
/// The repository containing `project_root` and every repository whose worktree
/// root lies below it (up to [`MAX_DEPTH`] levels; hidden and dependency folders and
/// folders `skip` rejects are not searched).
@@ -61,10 +79,8 @@ impl Repos {
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let name = entry.file_name();
let name = name.to_string_lossy();
let path = entry.path();
if name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(&path) {
if not_searched(&path, skip) {
continue;
}
if path.join(".git").exists()
@@ -350,6 +366,24 @@ mod tests {
assert!(ok, "git {args:?}");
}
#[test]
fn searched_matches_what_discover_finds() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git_init(&root);
let dirs = ["a", "a/b/c/d", "a/b/c/d/e", ".hidden/x", "vendor/x", "skipped/x", "a/skipped/x"];
for dir in dirs {
git_init(&root.join(dir));
}
let skip = |p: &Path| p.file_name().is_some_and(|n| n == "skipped");
let found = Repos::discover(&root, &skip).unwrap().roots();
for dir in dirs {
let dir = root.join(dir);
assert_eq!(Repos::searched(&root, &dir, &skip), found.contains(&dir), "{}", dir.display());
}
assert!(!Repos::searched(&root, &root, &skip), "the project root itself is no nested repository");
}
#[test]
fn ignored_files_use_git_rules_without_listing_other_repositories_twice() {
let tmp = tempfile::tempdir().unwrap();
+54
Переглянути файл
@@ -267,3 +267,57 @@ fn a_user_filter_links_shown_commits_past_hidden_ones() {
assert_eq!(next.iter().map(|c| c.id.clone()).collect::<Vec<_>>(), std::slice::from_ref(&m1));
let _ = m3;
}
/// A pull-request history: each feature commit `F_k` branches from merge `M_k-1` and is merged
/// back as `M_k = merge(M_k-1, F_k)`, written with `git fast-import`. Returns the feature commits
/// newest first.
fn pull_request_history(dir: &Path, merges: usize) -> Vec<String> {
git(dir, &["init", "-q"], None);
let mut stream =
String::from("commit refs/heads/main\nmark :1\ncommitter T <[email protected]> 1000 +0000\ndata 4\nroot\n");
let mut prev = 1;
let mut mark = 1;
for k in 0..merges {
let t = 1001 + 2 * k as i64;
let feature = mark + 1;
let merge = mark + 2;
stream += &format!(
"commit refs/heads/main\nmark :{feature}\ncommitter T <[email protected]> {t} +0000\ndata 1\nf\nfrom :{prev}\n\
commit refs/heads/main\nmark :{merge}\ncommitter T <t@example.com> {} +0000\ndata 1\nm\nfrom :{prev}\nmerge :{feature}\n",
t + 1
);
prev = merge;
mark = merge;
}
let mut child = Command::new("git")
.current_dir(dir)
.args(["fast-import", "--quiet", "--export-marks=marks"])
.stdin(std::process::Stdio::piped())
.spawn()
.unwrap();
std::io::Write::write_all(child.stdin.as_mut().unwrap(), stream.as_bytes()).unwrap();
assert!(child.wait().unwrap().success());
let marks: std::collections::HashMap<usize, String> = std::fs::read_to_string(dir.join("marks"))
.unwrap()
.lines()
.filter_map(|l| l.strip_prefix(':')?.split_once(' ').map(|(m, id)| (m.parse().unwrap(), id.to_string())))
.collect();
(0..merges).rev().map(|k| marks[&(2 + 2 * k)].clone()).collect()
}
#[test]
fn no_merges_on_a_long_pull_request_history_links_each_feature_to_the_previous_one() {
let tmp = tempfile::tempdir().unwrap();
let features = pull_request_history(tmp.path(), 3000);
let repo = Repo::discover(tmp.path()).unwrap().unwrap();
let started = std::time::Instant::now();
let out = repo
.log(&LogQuery { branches: vec!["main".into()], no_merges: true, limit: 100, ..Default::default() })
.unwrap();
let elapsed = started.elapsed();
assert_eq!(ids(&out)[..3], features[..3]);
// Every older feature is reachable through the previous one, so it is the only graph parent.
assert_eq!(parents_of(&out, &features[0]), vec![features[1].clone()]);
assert_eq!(parents_of(&out, &features[1]), vec![features[2].clone()]);
assert!(elapsed < std::time::Duration::from_secs(10), "took {elapsed:?}");
}
+5 -5
Переглянути файл
@@ -276,11 +276,11 @@ fn expand_jetbrains_path(raw: &str, home: Option<&Path>, config: &Path) -> Optio
return None;
}
let rest = if cfg!(windows) { rest.replace('/', "\\") } else { rest.to_owned() };
let path = match base {
Some(base) => base.join(rest.trim_start_matches(['/', '\\'])),
None => PathBuf::from(rest),
};
path.is_absolute().then_some(path)
// `home` and `config` are absolute already; only a path without a variable is checked.
match base {
Some(base) => Some(base.join(rest.trim_start_matches(['/', '\\']))),
None => Some(PathBuf::from(rest)).filter(|p| p.is_absolute()),
}
}
impl RecentProjects {
+1 -1
Переглянути файл
@@ -77,7 +77,7 @@ The stdio configuration looks like this (the path is the one on your machine):
Use the executable path from **Copy Stdio Config**; the macOS path above is only an example. On Windows it is `openidea.exe` in the installation (or portable) folder.
OpenIDEA must be running for the tools to work, and the project must be open in a window or served as a [background project](#background-projects). A client may name any folder inside such a project; the server picks the project that contains it. HTTP clients name it with the `X-OpenIDEA-Project` header or the `?project=` query.
OpenIDEA must be running for the tools to work, and the project must be open in a window or served as a [background project](#background-projects). A client may name any folder inside such a project, and the server picks the innermost project that contains it, whether a window has it open or it is served in the background. A project served in the background inside a project open in a window answers for its own folders, so relative paths in a call are relative to its root. For example, with **Trusted projects** a repository inside a trusted location, a Git submodule among them, loads as a background project of its own when a call names its folder, even while a window has the project around it open. HTTP clients name it with the `X-OpenIDEA-Project` header or the `?project=` query.
While the server runs, OpenIDEA writes its port and token to `mcp/server.json` in its application data directory (readable only by you); the stdio bridge reads it from there.
+11
Переглянути файл
@@ -145,6 +145,17 @@ The **Ports** tool window is available in a WSL window too. Because the distribu
`localhost`, a forwarded port is reachable here on the same port; the window lists, opens and remembers ports as it
does for SSH.
### Run a Windows project in WSL
A project on the Windows file system can keep its local window and run its configurations in a distribution: in
**Settings › Build, Execution, Deployment › Run Targets**, add a target of **Type** **WSL** (offered when a
distribution is installed) and pick the **WSL distribution**. A configuration with that target under **Run on** runs as
`wsl.exe -d <distribution> --cd <folder> --exec <program> <arguments>`. Project paths become their `/mnt/<drive>`
paths (`C:\work\app` is `/mnt/c/work/app`); set **Project folder in WSL** when the distribution mounts drives
elsewhere. Interpreters left empty are looked up on the distribution's `PATH` (`python3`, `node`, `java`). Environment
variables reach the distribution through `WSLENV`. Debugging, coverage and profiling are not available on a WSL
target.
## Other uses of SSH configurations
- **Run targets** (**Settings › Build, Execution, Deployment › Run Targets**) run a configuration on an SSH host. See
+8
Переглянути файл
@@ -68,6 +68,14 @@ When the project's dependencies are installed only in an image, choose a Docker
A `pyrightconfig.json` or a `[tool.basedpyright]` / `[tool.pyright]` section with its own `extraPaths` replaces the copied paths. The interpreter's Python version is the empty virtualenv's, from a local Python of the same version when there is one.
### A Python in WSL as the interpreter
On Windows with WSL, **Add Python Interpreter** has a **WSL** entry: pick the **Distribution** and the **Python interpreter** (the ones found on its `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's `.venv` / `venv`; another path can be typed). **OK** adds a WSL [run target](/en/guide/remote/ssh#run-a-windows-project-in-wsl) with that Python and makes it the project interpreter.
- **Editor.** The IDE runs that Python once in the distribution to read its `sys.path`. basedpyright and Pyright read those folders in place through `\\wsl.localhost\<distribution>` (nothing is copied), with an empty local virtualenv as their interpreter, as for a Docker target. They are shown under **External Libraries**.
- **Run.** Python run configurations without a run target of their own run in the distribution.
- **Packages.** The list is read-only: install packages in WSL, then reload it.
### Creating an environment
On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add Python Interpreter** and pick the **Interpreter type**:
+1 -1
Переглянути файл
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
```
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, or ones a contribution brings (`java.agent` from `[[contributes.javaAgents]]`, `project.read` from `[[contributes.documentIndexers]]`), and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
When code finds an optional capability refused, `host::open_permissions()` opens **Settings › Plugins** at the plugin's permissions, so a notice can offer a button that goes straight there (from a command or event only).
+1 -1
Переглянути файл
@@ -76,7 +76,7 @@ stdio 配置大致如下(路径以你机器上的为准):
请以 **复制 Stdio 配置** 得到的可执行文件路径为准,上面的 macOS 路径只是示例。在 Windows 上,它是安装目录(或便携版目录)中的 `openidea.exe`。
工具只在 OpenIDEA 运行,且项目已在窗口中打开或作为[后台项目](#后台项目)提供服务时可用。客户端可以指定这类项目中的任意目录,服务器会选出包含它的那个项目。HTTP 客户端通过 `X-OpenIDEA-Project` 请求头或 `?project=` 查询参数指定项目。
工具只在 OpenIDEA 运行,且项目已在窗口中打开或作为[后台项目](#后台项目)提供服务时可用。客户端可以指定这类项目中的任意目录,服务器会选出包含它的最内层项目,无论该项目在窗口中打开还是作为后台项目提供服务。位于窗口项目之内的后台项目负责它自己的目录,调用中的相对路径以它的根目录为准。例如在 **受信任的项目** 模式下,受信任位置中的仓库(包括 Git 子模块)在调用指定它的目录时会作为单独的后台项目加载,即使外层项目已在窗口中打开。HTTP 客户端通过 `X-OpenIDEA-Project` 请求头或 `?project=` 查询参数指定项目。
服务器运行期间,OpenIDEA 会把端口和令牌写入应用数据目录下的 `mcp/server.json`(只有你自己可读),stdio 转发程序从这里读取。
+8
Переглянути файл
@@ -114,6 +114,14 @@ Shell。IDE 内置的 SSH 客户端会使用配置里保存的密码、密钥或
WSL 窗口中也可以使用**端口**工具窗口。由于发行版与本机的 `localhost` 相通,转发的端口在本机可用同一端口访问;端口的列表、在浏览器中打开和记忆方式与 SSH 相同。
### 在 WSL 中运行 Windows 项目
位于 Windows 文件系统上的项目可以保留本地窗口,把运行配置放到发行版中运行:在**设置 › 构建、执行、部署 › 运行目标**中添加
**类型**为 **WSL** 的目标(装有发行版时才会出现),并选择 **WSL 发行版**。在**运行于**中选了该目标的配置,会以
`wsl.exe -d <distribution> --cd <folder> --exec <program> <arguments>` 运行。项目路径换成对应的 `/mnt/<盘符>` 路径
(`C:\work\app` 对应 `/mnt/c/work/app`);发行版把磁盘挂载在别处时,请填写 **WSL 中的项目文件夹**。留空的解释器从发行版的
`PATH` 查找(`python3`、`node`、`java`)。环境变量通过 `WSLENV` 传入发行版。WSL 目标不支持调试、覆盖率和性能分析。
## SSH 配置的其他用途
- **运行目标**(**设置 › 构建、执行、部署 › 运行目标**)可以在 SSH 主机上执行运行配置,见[运行配置](/zh/guide/run)。
+8
Переглянути файл
@@ -68,6 +68,14 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
如果 `pyrightconfig.json` 或 `[tool.basedpyright]` / `[tool.pyright]` 设置了自己的 `extraPaths`,它们会取代复制的路径。解释器的 Python 版本取自空虚拟环境;本机有相同版本的 Python 时会用它来创建。
### 以 WSL 中的 Python 作为解释器
在装有 WSL 的 Windows 上,**添加 Python 解释器**中有 **WSL** 一项:选择**发行版**和 **Python 解释器**(列出其 `PATH` 上、`/usr/bin` 和 `/usr/local/bin` 中、pyenv 的,以及项目 `.venv` / `venv` 中的 Python;也可以输入其他路径)。点击**确定**后会添加一个使用该 Python 的 WSL [运行目标](/zh/guide/remote/ssh#在-wsl-中运行-windows-项目),并将其设为项目解释器。
- **编辑器。** IDE 在发行版中运行一次该 Python 来读取其 `sys.path`。basedpyright 和 Pyright 通过 `\\wsl.localhost\<发行版>` 直接读取这些文件夹(不复制),解释器与 Docker 目标一样是一个本地的空虚拟环境。这些文件夹显示在**外部库**下。
- **运行。** 没有设置自己运行目标的 Python 运行配置会在该发行版中运行。
- **软件包。** 列表只读:请在 WSL 中安装软件包,然后重新加载列表。
### 创建环境
在 **设置 › 语言和框架 › Python 解释器** 中选择 **添加 Python 解释器**,再选 **解释器类型**:
+1 -1
Переглянути файл
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
```
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,或者由贡献点带来的能力(`[[contributes.javaAgents]]` 带来的 `java.agent`、`[[contributes.documentIndexers]]` 带来的 `project.read`),每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
代码发现某个 optional 能力被拒绝时,可以调用 `host::open_permissions()` 打开 **设置 › 插件** 并定位到本插件的权限,这样通知里可以放一个直接跳过去的按钮(仅限命令或事件中调用)。
+90
Переглянути файл
@@ -20,6 +20,96 @@ async function ratio(editor: Locator, preview: Locator, axis: "height" | "width"
return source![axis] / (source![axis] + rendered![axis]);
}
test("opens a repository version with all three read-only Markdown layouts", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const repo = "/dev/acme-api";
const revision = "a".repeat(40);
const path = "docs/history.md";
const source = "# Committed heading\n\nThis text belongs to the selected commit.\n";
const revisionInput = "/src/features/vcs/revisionInput.ts";
const vcsStore = "/src/features/vcs/store.ts";
const editorBackend = "/src/editor/core/backend.ts";
const { openRevisionFile } = await import(revisionInput);
const { useVcs } = await import(vcsStore);
const { docBackend } = await import(editorBackend);
docBackend().files.set(`${repo}/${path}`, "# Working copy heading\n");
useVcs.setState({ root: repo });
window.__ipc.handlers.lsp_virtual_document = ({ uri }) => {
docBackend().files.set(uri, source);
return {
uri,
text: source,
title: "history.md",
description: revision,
languageId: "markdown",
decompiled: false,
encoding: "utf-8",
hasBom: false,
canReloadEncoding: true,
};
};
openRevisionFile(repo, revision, path);
});
const editor = page.locator(".cm-content").filter({ hasText: "Committed heading" });
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(editor).toBeVisible();
await expect(editor).toHaveAttribute("aria-readonly", "true");
await page.getByRole("button", { name: "Preview Only", exact: true }).click();
await expect(editor).toBeHidden();
await expect(preview.getByRole("heading", { name: "Committed heading", exact: true })).toBeVisible();
await expect(preview).toContainText("This text belongs to the selected commit.");
await page.getByRole("button", { name: "Editor and Preview", exact: true }).click();
await expect(editor).toBeVisible();
await expect(preview).toBeVisible();
await editor.click();
await page.keyboard.type("unexpected edit");
await expect(editor).not.toContainText("unexpected edit");
await expect(preview).not.toContainText("unexpected edit");
await page.getByRole("button", { name: "Editor Only", exact: true }).click();
await expect(editor).toBeVisible();
await expect(preview).toBeHidden();
});
test("follows explicit Markdown anchors before generated heading IDs", async ({ workbench: page }) => {
const source = [
"[Reference](#ref-1) and [Heading](#ref-1-heading)",
...Array.from({ length: 30 }, (_, index) => `Paragraph ${index + 1}`),
"## Ref 1",
...Array.from({ length: 30 }, (_, index) => `More text ${index + 1}`),
'<a id="ref-1"></a>',
"Reference text",
...Array.from({ length: 30 }, (_, index) => `Further text ${index + 1}`),
"## Ref 1 heading",
].join("\n\n");
await page.evaluate(async (source) => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
const path = "/dev/acme-api/references.md";
docBackend().files.set(path, source);
await editorService().openFile(path);
}, source);
await page.getByRole("button", { name: "Preview Only", exact: true }).click();
const preview = page.getByRole("document", { name: "Markdown preview" });
const referenceText = preview.getByText("Reference text", { exact: true });
const heading = preview.getByRole("heading", { name: "Ref 1 heading", exact: true });
await expect(preview.locator('[id="ref-1"]')).toHaveCount(1);
await expect(referenceText).not.toBeInViewport();
await preview.getByRole("link", { name: "Reference", exact: true }).click();
await expect(referenceText).toBeInViewport();
await expect(heading).not.toBeInViewport();
await preview.getByRole("link", { name: "Heading", exact: true }).click();
await expect(heading).toBeInViewport();
});
test("copies fenced Markdown code with hover or keyboard in both preview layouts", async ({
workbench: page,
context,
+54
Переглянути файл
@@ -51,6 +51,60 @@ test("suggests and configures a project-scoped GitHub account in Settings › Ve
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
});
test("Update failure offers project-scoped GitHub account selection", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
let configuredAccount = "";
const status = (): GhProjectAccountStatus => ({
ghInstalled: true,
accounts: [
{ login: "alice", active: true },
{ login: "alice-work", active: false },
],
configuredAccount,
effectiveAccount: configuredAccount || "alice",
suggestedAccount: configuredAccount ? null : "alice-work",
});
Object.assign(window.__ipc.handlers, {
vcs_branch_info: () => ({ head: "main", upstream: "origin/main", headCommit: "c1", operation: null }),
vcs_remote: () => {
throw {
kind: "invalid",
message: "remote: Repository not found.\nfatal: repository 'https://github.com/acme/private.git/' not found",
};
},
gh_project_account_status: () => status(),
gh_set_project_account: ({ account }: { account: string }) => {
configuredAccount = account;
return status();
},
settings_get_global: () => ({}),
window_open_settings: () => {
throw { kind: "unavailable", message: "separate settings window disabled in browser test" };
},
});
const opsModule = "/src/features/vcs/ops.ts";
const { runRemote } = await import(/* @vite-ignore */ opsModule);
await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/dev/acme-api"]);
});
await expect(page.getByText("Update failed", { exact: true })).toBeVisible();
await expect(page.getByText(/Repository not found/)).toBeVisible();
await expect(page.getByText(/alice may not have access/)).toBeVisible();
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([]);
const settingsLink = page.getByRole("button", { name: "GitHub Settings", exact: true });
await expect(settingsLink).toBeVisible();
if (process.env.CAPTURE_GH_AUTH_FAILURE) {
await page.screenshot({ path: process.env.CAPTURE_GH_AUTH_FAILURE, animations: "disabled" });
}
await settingsLink.click();
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("Automatic (alice)");
await dialog.getByRole("button", { name: "Use alice-work for this project" }).click();
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("alice-work");
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
});
test("adds a GitHub account in Settings › Version Control › GitHub with OAuth device-code banner", async ({
workbench: page,
}) => {
+18
Переглянути файл
@@ -128,6 +128,24 @@ test("Project Structure keeps every details pane usable in a compact window", as
await expect(details).toBeAttached();
expect((await details.boundingBox())!.width).toBeGreaterThan(200);
}
const root = `/external/${"long-content-root/".repeat(12)}sources`;
await page.evaluate(async (root) => {
const path = "/src/features/settings/model/staging.ts";
const { stage } = await import(/* @vite-ignore */ path);
stage("projectStructure", "project", "projectStructure.contentRoots", [root]);
}, root);
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Add Content Root");
await expect(dialog.getByRole("tab", { name: "Sources" })).toHaveAttribute("aria-selected", "true");
const path = dialog.getByRole("region", { name: "Marked folders" }).getByText(root, { exact: true });
await expect(path).toBeVisible();
expect(
await path.evaluate((element) => {
const range = document.createRange();
range.selectNodeContents(element);
return range.getClientRects().length;
}),
).toBeGreaterThan(1);
});
test("Project Structure starts with compact navigation and remembers the divider", async ({ workbench: page }) => {
+9 -14
Переглянути файл
@@ -63,14 +63,13 @@ test("Shelf keeps patch and file selection available in a narrow dock", async ({
const location = panel.getByText(directory, { exact: true });
await expect.poll(() => location.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
const divider = panel.getByRole("separator", { name: "Resize shelf panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const files = panel.getByRole("tree", { name: "Shelved files" });
await expect(files.getByRole("treeitem")).toHaveCount(2);
const pathBox = (await location.boundingBox())!;
const filesBox = (await files.boundingBox())!;
expect(pathBox.x).toBeLessThan(filesBox.x + filesBox.width - 50);
const files = patches;
await expect(patches.getByRole("treeitem").filter({ hasText: filename })).toHaveCount(1);
const row = files.getByRole("treeitem").filter({ hasText: filename });
const nameBox = (await row.getByText(filename, { exact: true }).boundingBox())!;
const pathBox = (await location.boundingBox())!;
expect(pathBox.x).toBeGreaterThan(nameBox.x + nameBox.width);
expect(Math.abs(pathBox.y + pathBox.height - nameBox.y - nameBox.height)).toBeLessThan(3);
await row.click({ position: { x: 90, y: 12 } });
await expect(row).toHaveAttribute("aria-selected", "true");
await panel.getByRole("button", { name: "Unshelve…", exact: true }).click();
@@ -81,13 +80,9 @@ test("Shelf keeps patch and file selection available in a narrow dock", async ({
await expect(dialog.getByText("README.md", { exact: true })).toHaveCount(0);
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await page.evaluate(async () => {
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 640);
});
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await expect(row).toHaveAttribute("aria-selected", "true");
await patches.getByRole("treeitem").filter({ hasText: "Update release notes" }).click();
await expect(files.getByRole("treeitem")).toHaveCount(1);
const other = patches.getByRole("treeitem").filter({ hasText: "Update release notes" });
await other.click();
if ((await other.getAttribute("aria-expanded")) === "false") await page.keyboard.press("ArrowRight");
await expect(files.getByText("CHANGELOG.md", { exact: true })).toBeVisible();
});
+2 -1
Переглянути файл
@@ -51,7 +51,8 @@ with tempfile.TemporaryDirectory() as scratch:
"##teamcity[testFailed name='fails' className='sample.SampleTest' message='org.opentest4j.AssertionFailedError: it|'s wrong ==> expected: <1> but was: <2>'",
"##teamcity[testIgnored name='disabled' className='sample.SampleTest'",
"##teamcity[testIgnored name='aborted' className='sample.SampleTest']",
"##teamcity[testFailed name='parameterized' className='sample.SampleTest'",
"##teamcity[testStarted name='parameterized' className='sample.SampleTest' invocation='|[1|] 1']",
"##teamcity[testFailed name='parameterized' className='sample.SampleTest' invocation='|[2|] 2'",
"##teamcity[testFinished name='nested' className='sample.SampleTest$Inner' duration=",
"7 tests completed, 2 failed, 2 skipped",
]
Бінарний файл не відображається.
+14 -7
Переглянути файл
@@ -153,18 +153,25 @@ final class PlatformRunner implements TestExecutionListener {
for (Output o : outputs) o.flushLines(true);
}
/** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */
/**
* `name='method' className='a.B$Nested'`, the method and class of the test or its closest source;
* an invocation of a parameterized, repeated or dynamic test adds `invocation='[1] a'`, its display name.
*/
private String id(TestIdentifier id) {
// The outermost method of the chain: the test itself, or the method container of its invocations.
TestIdentifier method = null;
for (TestIdentifier at = id; at != null; at = plan.getParent(at).orElse(null)) {
TestSource source = at.getSource().orElse(null);
if (source instanceof MethodSource) {
MethodSource m = (MethodSource) source;
return Reporter.attr("name", m.getMethodName()) + Reporter.attr("className", m.getClassName());
}
if (source instanceof ClassSource)
if (source instanceof MethodSource) method = at;
else if (method != null) break;
else if (source instanceof ClassSource)
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", ((ClassSource) source).getClassName());
}
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", id.getDisplayName());
if (method == null)
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", id.getDisplayName());
MethodSource m = (MethodSource) method.getSource().get();
String own = Reporter.attr("name", m.getMethodName()) + Reporter.attr("className", m.getClassName());
return method == id ? own : own + Reporter.attr("invocation", id.getDisplayName());
}
private Optional<String> className(TestIdentifier id) {
+10
Переглянути файл
@@ -17,6 +17,16 @@ install-hint = "npm i -g intelephense"
# Intelephense applies the PHP version only to documents it parses after reading it.
resync-on-configuration = true
[[language-servers]]
name = "phpantom"
# PHPantom 1.1.0 can cancel these operations without ending server-created progress.
ignored-progress-token-prefixes = ["find_references", "goto_implementation"]
fallback = true
command = "phpantom_lsp"
args = []
root-markers = ["composer.json", "index.php"]
install-hint = "Install PHPantom in Settings › Languages & Frameworks › Language Servers"
[[language-servers]]
name = "phpactor"
# Alternative: used only when the server above is not installed.
+4
Переглянути файл
@@ -72,6 +72,10 @@ ide-android = { path = "../crates/ide-android" }
[dev-dependencies]
tempfile.workspace = true
[[test]]
name = "background_tab_appkit"
harness = false
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6"
# Plugin secrets in the login keychain.
+4
Переглянути файл
@@ -0,0 +1,4 @@
disallowed-methods = [
{ path = "tauri::webview::WebviewWindow::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
{ path = "tauri::webview::Webview::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
]
+71
Переглянути файл
@@ -0,0 +1,71 @@
//! AppKit side of a background tab's detached web view; no tauri types, so a test can include it.
use objc2::{
Message,
rc::Retained,
runtime::{AnyClass, ProtocolObject},
};
use objc2_app_kit::{
NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowDidChangeOcclusionStateNotification,
NSWindowOcclusionState, NSWindowOrderingMode,
};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Return {
Key,
Visible,
}
pub fn web_view(native: &NSWindow) -> Option<Retained<NSView>> {
let class = AnyClass::get(c"WKWebView")?;
native.contentView()?.subviews().iter().find(|v| v.isKindOfClass(class))
}
/// At the bottom so the title bar views stay above it.
pub fn put_back(native: &NSWindow, view: &NSView) {
let Some(content) = native.contentView() else { return };
view.setFrame(content.bounds());
content.addSubview_positioned_relativeTo(view, NSWindowOrderingMode::Below, None);
native.makeFirstResponder(Some(view));
}
/// Calls `f` when the window becomes key, or visible (AppKit can bring a window back by itself,
/// e.g. when a tab it closes next to leaves the group). The observers have no queue, so `f` runs
/// synchronously inside the post. For the key notification that is inside `makeKeyWindow`, before the
/// window's first display; occlusion arrives when the window is already on screen.
pub fn on_return(
native: &NSWindow,
f: impl Fn(Return) + 'static,
) -> Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>> {
let f = std::rc::Rc::new(f);
let center = NSNotificationCenter::defaultCenter();
let key = {
let f = f.clone();
let block = block2::RcBlock::new(move |_| f(Return::Key));
unsafe {
center.addObserverForName_object_queue_usingBlock(
Some(NSWindowDidBecomeKeyNotification),
Some(native),
None,
&block,
)
}
};
let visible = {
let window: Retained<NSWindow> = native.retain();
let block = block2::RcBlock::new(move |_| {
if window.occlusionState().contains(NSWindowOcclusionState::Visible) {
f(Return::Visible);
}
});
unsafe {
center.addObserverForName_object_queue_usingBlock(
Some(NSWindowDidChangeOcclusionStateNotification),
Some(native),
None,
&block,
)
}
};
vec![key, visible]
}
+3 -3
Переглянути файл
@@ -170,9 +170,9 @@ async fn webview_processes(app: &AppHandle, state: &AppState) -> Vec<MemoryRoot>
let mut pending = Vec::new();
for (label, w) in app.webview_windows() {
let (tx, rx) = tokio::sync::oneshot::channel();
let sent = w.with_webview(move |pv| {
// SAFETY: `with_webview` runs on the main thread with the live WKWebView.
let _ = tx.send(unsafe { memory::webkit_process_ids(pv.inner()) });
let sent = crate::macos::with_web_view(&w, move |view| {
// SAFETY: runs on the main thread with the live WKWebView, detached or not.
let _ = tx.send(unsafe { memory::webkit_process_ids(view) });
});
if sent.is_ok() {
pending.push((label, rx));
+1
Переглянути файл
@@ -233,6 +233,7 @@ pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()>
#[specta::specta]
pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeResult<()> {
#[cfg(target_os = "linux")]
#[allow(clippy::disallowed_methods)]
window
.with_webview(move |platform| crate::linux_webkit::set_smooth_scrolling(&platform, enabled))
.map_err(|e| IdeError::internal(e.to_string()))?;
+3
Переглянути файл
@@ -7,6 +7,8 @@
#![recursion_limit = "512"]
mod application_focus;
#[cfg(target_os = "macos")]
mod background_tab;
mod cli;
mod commands;
#[cfg(debug_assertions)]
@@ -308,6 +310,7 @@ pub fn run() {
#[cfg(target_os = "macos")]
{
page_swipe::forget(window.label());
macos::forget_background(window.label());
titlebar::forget(window);
}
if windows::auxiliary_parent(window.label()).is_none() {
+1
Переглянути файл
@@ -91,6 +91,7 @@ pub fn smooth_scrolling_plugin() -> tauri::plugin::TauriPlugin<tauri::Wry> {
let enabled = webview
.try_state::<crate::state::AppState>()
.is_some_and(|s| s.global_settings.effective().appearance.smooth_scrolling);
#[allow(clippy::disallowed_methods)]
let _ = webview.with_webview(move |platform| set_smooth_scrolling(&platform, enabled));
})
.build()
+242 -3
Переглянути файл
@@ -1,15 +1,101 @@
//! macOS project tabs: native window tab groups behind the page's own tab bar.
use crate::background_tab::{self, Return};
use crate::windows::{Launch, WindowsState};
use ide_core::{IdeError, IdeResult};
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
use objc2::{
MainThreadMarker,
rc::Retained,
runtime::{AnyClass, AnyObject, Imp, Sel},
runtime::{AnyClass, AnyObject, Imp, ProtocolObject, Sel},
};
use objc2_app_kit::{
NSApplication, NSView, NSWindow, NSWindowOcclusionState, NSWindowOrderingMode, NSWindowStyleMask,
NSWindowUserTabbingPreference,
};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSOperationQueue};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
ffi::c_void,
time::Duration,
};
use objc2_app_kit::{NSWindow, NSWindowUserTabbingPreference};
use tauri::{AppHandle, Manager, WebviewWindow};
/// WebKit frees a page's graphics 10 s and its caches 2 min after the page leaves its window.
const DETACH_BACKGROUND_TAB_AFTER: Duration = Duration::from_secs(30);
enum Background<V> {
Pending(u64),
Detached(V),
}
struct BackgroundTabs<V> {
next: u64,
tabs: HashMap<String, Background<V>>,
}
impl<V> Default for BackgroundTabs<V> {
fn default() -> Self {
Self { next: 0, tabs: HashMap::new() }
}
}
impl<V> BackgroundTabs<V> {
/// None when the label already has an entry: a repeated select must not restart the clock.
fn schedule(&mut self, label: &str) -> Option<u64> {
if self.tabs.contains_key(label) {
return None;
}
self.next += 1;
self.tabs.insert(label.to_string(), Background::Pending(self.next));
Some(self.next)
}
fn due(&self, label: &str, generation: u64) -> bool {
matches!(self.tabs.get(label), Some(Background::Pending(g)) if *g == generation)
}
fn detached(&mut self, label: &str, view: V) {
self.tabs.insert(label.to_string(), Background::Detached(view));
}
fn cancel(&mut self, label: &str) {
self.tabs.remove(label);
}
fn view(&self, label: &str) -> Option<&V> {
match self.tabs.get(label) {
Some(Background::Detached(view)) => Some(view),
_ => None,
}
}
/// Also cancels a pending detach.
fn attach(&mut self, label: &str) -> Option<V> {
match self.tabs.remove(label) {
Some(Background::Detached(view)) => Some(view),
_ => None,
}
}
}
struct DetachedView {
view: Retained<NSView>,
observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
}
impl Drop for DetachedView {
fn drop(&mut self) {
for observer in &self.observers {
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
}
}
}
thread_local! {
static BACKGROUND: RefCell<BackgroundTabs<DetachedView>> = RefCell::new(BackgroundTabs::default());
}
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
fn read(mtm: MainThreadMarker) -> TabbingPreference {
match NSWindow::userTabbingPreference(mtm) {
@@ -83,6 +169,101 @@ fn same_group(a: &NSWindow, b: &NSWindow) -> bool {
}
}
fn schedule_detach(window: &WebviewWindow) {
// The debug-only MCP bridge calls `with_webview` directly, which panics on a detached view.
if cfg!(debug_assertions) {
return;
}
let Some(generation) = BACKGROUND.with_borrow_mut(|tabs| tabs.schedule(window.label())) else { return };
let target = window.clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(DETACH_BACKGROUND_TAB_AFTER).await;
let window = target.clone();
let _ = window.run_on_main_thread(move || detach_if_background(&target, generation));
});
}
fn detach_if_background(window: &WebviewWindow, generation: u64) {
if !BACKGROUND.with_borrow(|tabs| tabs.due(window.label(), generation)) {
return;
}
let Some(native) = native(window) else { return };
// A visible window is never a background tab.
if native.occlusionState().contains(NSWindowOcclusionState::Visible) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
return;
}
// An inactive app's full-screen group can be mid-transition, where AppKit has crashed (#6937): wait for activation.
let inactive = MainThreadMarker::new().is_some_and(|mtm| !NSApplication::sharedApplication(mtm).isActive());
if inactive && native.styleMask().contains(NSWindowStyleMask::FullScreen) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
schedule_detach(window);
return;
}
let view = (|| {
let group = native.tabGroup()?;
let selected = group.selectedWindow()?;
let background = group.windows().count() > 1
&& !std::ptr::eq(Retained::as_ptr(&selected), native)
&& native.attachedSheet().is_none();
background.then(|| background_tab::web_view(native)).flatten()
})();
let Some(view) = view else {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
return;
};
view.removeFromSuperview();
let target = window.clone();
let observers = background_tab::on_return(native, move |why| {
attach_for(&target, if why == Return::Key { "key" } else { "visible" }, true)
});
BACKGROUND.with_borrow_mut(|tabs| tabs.detached(window.label(), DetachedView { view, observers }));
}
/// Puts a detached web view back and cancels a pending detach.
pub fn attach(window: &WebviewWindow) {
attach_for(window, "select", false);
}
fn attach_for(window: &WebviewWindow, reason: &str, from_observer: bool) {
let Some(detached) = BACKGROUND.with_borrow_mut(|tabs| tabs.attach(window.label())) else {
return;
};
if let Some(native) = native(window) {
background_tab::put_back(native, &detached.view);
tracing::debug!(label = window.label(), reason, "re-attached background tab web view");
}
if from_observer {
// Dropping removes the observer whose block is running; wait until the post returns.
let detached = Cell::new(Some(detached));
let block = block2::RcBlock::new(move || drop(detached.take()));
unsafe { NSOperationQueue::mainQueue().addOperationWithBlock(&block) };
}
}
/// Calls `f` on the main thread with the window's `WKWebView`, attached or not.
/// tauri's webview size/position APIs (`core:webview:default` grants `webview_size`/`webview_position`) unwrap
/// `superview()` in wry and are not safe while a tab is detached.
pub fn with_web_view(window: &WebviewWindow, f: impl FnOnce(*mut c_void) + Send + 'static) -> tauri::Result<()> {
let target = window.clone();
window.run_on_main_thread(move || {
// On the main thread tauri handles with_webview synchronously, so the tab cannot be detached between
// the check and the call; wry's with_webview panics on a windowless view.
let detached = BACKGROUND.with_borrow(|tabs| tabs.view(target.label()).map(|d| Retained::as_ptr(&d.view)));
match detached {
Some(view) => f(view as *mut c_void),
None => {
#[allow(clippy::disallowed_methods)]
let _ = target.with_webview(move |w| f(w.inner()));
}
}
})
}
pub fn forget_background(label: &str) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(label));
}
/// Adds `members` to the existing anchor's native tab group and shows `selected`.
pub fn sync_tab_group(
members: Vec<WebviewWindow>,
@@ -99,14 +280,18 @@ pub fn sync_tab_group(
if let Some(window) = native(member)
&& !same_group(anchor_window, window)
{
anchor_window.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
anchor_window.addTabbedWindow_ordered(window, NSWindowOrderingMode::Above);
}
}
attach(&target);
if let Some(group) = shown.tabGroup() {
group.setSelectedWindow(Some(shown));
}
shown.makeKeyAndOrderFront(None);
for member in &members {
if member.label() != target.label() {
schedule_detach(member);
}
if let Some(window) = native(member) {
hide_tab_bar(window);
}
@@ -129,6 +314,7 @@ pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
let target = window.clone();
on_main(window, move || {
let Some(native) = native(&target) else { return };
attach(&target);
if native.tabbedWindows().is_some_and(|tabs| tabs.count() > 1) {
native.moveTabToNewWindow(None);
}
@@ -226,3 +412,56 @@ pub fn native_modal_open() -> bool {
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
application.modalWindow().is_some() || application.windows().iter().any(|window| window.attachedSheet().is_some())
}
#[cfg(test)]
mod tests {
use super::BackgroundTabs;
#[test]
fn repeated_schedule_keeps_the_first_generation() {
let mut tabs = BackgroundTabs::<u32>::default();
let first = tabs.schedule("a").unwrap();
assert_eq!(tabs.schedule("a"), None);
assert!(tabs.due("a", first));
}
#[test]
fn attach_cancels_a_pending_detach() {
let mut tabs = BackgroundTabs::<u32>::default();
let generation = tabs.schedule("a").unwrap();
assert_eq!(tabs.attach("a"), None);
assert!(!tabs.due("a", generation));
}
#[test]
fn stale_generation_is_not_due_after_reschedule() {
let mut tabs = BackgroundTabs::<u32>::default();
let stale = tabs.schedule("a").unwrap();
tabs.attach("a");
let fresh = tabs.schedule("a").unwrap();
assert_ne!(stale, fresh);
assert!(!tabs.due("a", stale));
assert!(tabs.due("a", fresh));
}
#[test]
fn view_is_only_there_while_detached() {
let mut tabs = BackgroundTabs::<&'static str>::default();
tabs.schedule("a").unwrap();
assert_eq!(tabs.view("a"), None);
tabs.detached("a", "view");
assert_eq!(tabs.view("a"), Some(&"view"));
tabs.attach("a");
assert_eq!(tabs.view("a"), None);
}
#[test]
fn attach_returns_the_detached_view_once() {
let mut tabs = BackgroundTabs::<&'static str>::default();
let generation = tabs.schedule("a").unwrap();
tabs.detached("a", "view");
assert!(!tabs.due("a", generation));
assert_eq!(tabs.attach("a"), Some("view"));
assert_eq!(tabs.attach("a"), None);
}
}
+4 -3
Переглянути файл
@@ -33,9 +33,10 @@ fn stroke(window: &WebviewWindow, right: bool) {
pub fn install(window: &WebviewWindow) {
let target = window.clone();
let _ = window.with_webview(move |webview| {
let view = unsafe { Retained::retain(webview.inner().cast::<NSView>()).unwrap() };
let native = webview.ns_window() as usize;
let _ = crate::macos::with_web_view(window, move |webview| {
let view = unsafe { Retained::retain(webview.cast::<NSView>()).unwrap() };
let Ok(native) = target.ns_window() else { return };
let native = native as usize;
let window = target.clone();
let block = block2::RcBlock::new(move |event: NonNull<NSEvent>| {
let event = unsafe { event.as_ref() };
+5 -3
Переглянути файл
@@ -458,10 +458,12 @@ fn track(window: &NSWindow, app: &tauri::AppHandle) -> Tracked {
pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<()> {
let label = window.label().to_owned();
let app = window.app_handle().clone();
// with_webview runs on the AppKit thread.
window.with_webview(move |webview| unsafe {
let target = window.clone();
// The window's own handle works while a background tab's web view is detached.
window.run_on_main_thread(move || unsafe {
let Some(mtm) = MainThreadMarker::new() else { return };
let native = &*webview.ns_window().cast::<NSWindow>();
let Ok(native) = target.ns_window() else { return };
let native = &*native.cast::<NSWindow>();
let (state, buttons, strip) = WINDOWS.with_borrow_mut(|windows| {
let tracked = windows.entry(label).or_insert_with(|| track(native, &app));
tracked.height.set(height);
+2 -2
Переглянути файл
@@ -2764,8 +2764,8 @@ fn disable_macos_text_input_selection_updates(preferences: &objc2_web_kit::WKPre
/// suppresses the affordance even if `NSTextInputContext` queries the view directly.
#[cfg(target_os = "macos")]
fn suppress_window_writing_tools_affordance(window: &WebviewWindow) {
let _ = window.with_webview(|webview| unsafe {
let ptr = webview.inner().cast::<objc2::runtime::AnyObject>();
let _ = crate::macos::with_web_view(window, |webview| unsafe {
let ptr = webview.cast::<objc2::runtime::AnyObject>();
if !ptr.is_null() {
let cls = (*ptr).class();
suppress_webview_class_writing_tools_affordance(cls);
+1
Переглянути файл
@@ -11,6 +11,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
plugin::Builder::new("webview-keys").on_webview_ready(disable_browser_keys).build()
}
#[allow(clippy::disallowed_methods)]
fn disable_browser_keys(webview: Webview) {
let label = webview.label().to_owned();
if let Err(error) = webview.with_webview(move |platform| {
+1
Переглянути файл
@@ -50,6 +50,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
.build()
}
#[allow(clippy::disallowed_methods)]
fn install(webview: Webview) {
let app = webview.app_handle().clone();
let label = webview.label().to_owned();
+70
Переглянути файл
@@ -0,0 +1,70 @@
#[cfg(not(target_os = "macos"))]
fn main() {}
#[cfg(target_os = "macos")]
#[path = "../src/background_tab.rs"]
mod background_tab;
#[cfg(target_os = "macos")]
#[link(name = "WebKit", kind = "framework")]
unsafe extern "C" {}
#[cfg(target_os = "macos")]
fn main() {
// nextest runs a harness-less binary as `--list --format terse [--ignored]`, then `<name> --exact --nocapture`.
let args: Vec<String> = std::env::args().collect();
if args.iter().any(|a| a == "--list") {
if !args.iter().any(|a| a == "--ignored") {
println!("background_tab_appkit: test");
}
return;
}
use background_tab::Return;
use objc2::{MainThreadMarker, msg_send, rc::Retained, runtime::AnyClass};
use objc2_app_kit::{
NSApplication, NSBackingStoreType, NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowStyleMask,
};
use objc2_foundation::{NSNotificationCenter, NSPoint, NSRect, NSSize};
use std::{cell::Cell, rc::Rc};
let mtm = MainThreadMarker::new().expect("main thread");
let _app = NSApplication::sharedApplication(mtm);
let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(400.0, 300.0));
let window = unsafe {
NSWindow::initWithContentRect_styleMask_backing_defer(
mtm.alloc(),
rect,
NSWindowStyleMask::Titled,
NSBackingStoreType::Buffered,
false,
)
};
let class = AnyClass::get(c"WKWebView").expect("WebKit is linked");
let web: Retained<NSView> = unsafe { msg_send![msg_send![class, alloc], initWithFrame: rect] };
window.contentView().unwrap().addSubview(&web);
let view = background_tab::web_view(&window).expect("web view in content view");
view.removeFromSuperview();
assert!(view.window().is_none());
// Not asked for its process ids: on a web view that never loaded a page, WebKit asserts in
// `_networkProcessIdentifier` (macOS 15), which a real tab never is.
let reason = Rc::new(Cell::new(None));
let observers = {
let (reason, window, view) = (reason.clone(), window.clone(), view.clone());
background_tab::on_return(&window.clone(), move |why| {
background_tab::put_back(&window, &view);
reason.set(Some(why));
})
};
unsafe {
NSNotificationCenter::defaultCenter()
.postNotificationName_object(NSWindowDidBecomeKeyNotification, Some(&window));
}
assert_eq!(reason.get(), Some(Return::Key));
assert!(view.window().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)));
for observer in &observers {
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
}
println!("ok: re-attached synchronously inside the key notification");
}
+2 -1
Переглянути файл
@@ -693,7 +693,7 @@ scaffold_options always project_host bin
scaffold_requirements always project_host bindings async
scaffold_target_taken always project_host bindings async
scope_files always project_host bindings async
sdk_container_python trusted project_host bindings sync
sdk_container_python trusted project_host bindings async
sdk_container_python_refresh trusted project_host bindings async
sdk_detect outside_restricted project_host bindings async
sdk_flutter_at trusted project_host bindings async
@@ -714,6 +714,7 @@ sdk_python_pip outside_restricted project_host bin
sdk_python_project_interpreters outside_restricted project_host bindings async
sdk_python_sys_path outside_restricted project_host bindings async
sdk_python_user_path_problems outside_restricted project_host bindings async
sdk_wsl_pythons trusted project_host bindings async
search_start always project_host bindings async
search_validate always project_host bindings sync
set_recent_project_groups always desktop bindings sync
+46 -6
Переглянути файл
@@ -1981,7 +1981,10 @@ export const commands = {
*/
scaffoldTargetTaken: (location: string, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("scaffold_target_taken", { location, name })),
scopeFiles: (pattern: string, limit: number) => typedError<ScopeFiles, IdeError>(__TAURI_INVOKE("scope_files", { pattern, limit })),
/** The project interpreter when it is a Docker or Compose run target's, with its snapshot. */
/**
* The project interpreter when it is a Docker or Compose run target's, with its snapshot.
* Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
*/
sdkContainerPython: () => typedError<{
/** The run target's id. */
target: string,
@@ -1989,8 +1992,10 @@ export const commands = {
name: string,
/** The Python version of the snapshot in use; `None`: no snapshot yet. */
version: string | null,
/** The image the snapshot was copied from. */
/** The image the snapshot was copied from; `None` for WSL. */
image: string | null,
/** The interpreter's path in the container or distribution. */
executable: string | null,
/** The copied library folders on this machine. */
folders: IpcPath[],
/** Packages of the snapshot (read-only). */
@@ -2006,8 +2011,10 @@ export const commands = {
name: string,
/** The Python version of the snapshot in use; `None`: no snapshot yet. */
version: string | null,
/** The image the snapshot was copied from. */
/** The image the snapshot was copied from; `None` for WSL. */
image: string | null,
/** The interpreter's path in the container or distribution. */
executable: string | null,
/** The copied library folders on this machine. */
folders: IpcPath[],
/** Packages of the snapshot (read-only). */
@@ -2116,6 +2123,11 @@ export const commands = {
* (`None`: it is used). The folders may not be saved yet.
*/
sdkPythonUserPathProblems: (paths: string[]) => typedError<(UserPathProblem | null)[], IdeError>(__TAURI_INVOKE("sdk_python_user_path_problems", { paths })),
/**
* The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
* `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
*/
sdkWslPythons: (distro: string) => typedError<string[], IdeError>(__TAURI_INVOKE("sdk_wsl_pythons", { distro })),
/**
* Find in Files. Results stream through `on_event`; ends with `Done`.
* Cancel with `cancel_request(request)`.
@@ -5782,8 +5794,10 @@ export type ContainerPython = {
name: string,
/** The Python version of the snapshot in use; `None`: no snapshot yet. */
version: string | null,
/** The image the snapshot was copied from. */
/** The image the snapshot was copied from; `None` for WSL. */
image: string | null,
/** The interpreter's path in the container or distribution. */
executable: string | null,
/** The copied library folders on this machine. */
folders: IpcPath[],
/** Packages of the snapshot (read-only). */
@@ -5975,6 +5989,20 @@ export type CustomKeymap = {
overrides?: { [key in string]: string[] },
};
/** Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through. */
export type CycleCaseSettings = {
/** `snake_case` */
snake?: boolean,
/** `SCREAMING_SNAKE_CASE` */
screaming?: boolean,
/** `kebab-case` */
kebab?: boolean,
/** `camelCase` */
camel?: boolean,
/** `PascalCase` */
pascal?: boolean,
};
/**
* A field watchpoint (DAP data breakpoint) on a `dataId` from [`DebugManager::data_breakpoint_info`]
* (java-debug ids, `Class#field`, stay valid across sessions).
@@ -14392,7 +14420,10 @@ export type RunTarget = {
name?: string,
/** [`SshConfiguration::id`] (SSH). */
sshConfig?: string,
/** Remote folder the project is synchronised to and run from (SSH). */
/**
* Remote folder the project is synchronised to and run from (SSH); the project's Linux
* path, empty = its `/mnt/<drive>` path (WSL).
*/
projectRoot?: string,
/** Upload changed project files before each run (SSH). */
syncBeforeRun?: boolean,
@@ -14422,6 +14453,8 @@ export type RunTarget = {
runOptions?: string,
/** Run as the image's user instead of the project folder's owner (Linux). */
imageUser?: boolean,
/** Distribution name, as `wsl.exe -l -q` lists it (WSL). */
distro?: string,
};
/** Where a run target runs configurations. */
@@ -14431,7 +14464,12 @@ export type RunTargetKind =
/** A new container of an image (`docker run --rm`), the project bind-mounted. */
"docker" |
/** A new container of a Compose service (`docker compose run --rm`). */
"compose";
"compose" |
/**
* A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
* through `/mnt/<drive>`.
*/
"wsl";
export type RustSettings = {
/** Directory holding `cargo` / `rustc`; empty = `PATH` / rustup default. */
@@ -15073,6 +15111,8 @@ export type SmartKeysSettings = {
insertDocStub?: boolean,
/** Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`. */
backspaceUnindent?: string,
/** The styles Cycle Identifier Case goes through. */
cycleCase?: CycleCaseSettings,
};
export type SourceFolder = {
+25 -1
Переглянути файл
@@ -1140,6 +1140,30 @@ export function registerEditorActions(): () => void {
activeSlot()?.model.toggleRenderedDocs();
},
},
{
id: "editor.toggleRenderedDocsForAll",
title: "Render All Doc Comments",
category: "View",
keywords: ["render documentation comments", "javadoc", "rendered doc", "comments", "all editors"],
toggled: () => editorPrefs().appearance.renderDocComments,
run: async () => {
const on = !editorPrefs().appearance.renderDocComments;
try {
useProject.setState({
settings: await call(
commands.settingsSet("global", "editor.appearance.renderDocComments", JSON.stringify(on)),
),
});
editorController().manager.resetRenderedDocs();
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot change the setting",
body: e instanceof Error ? e.message : String(e),
});
}
},
},
text("editor.toggleRenderedView", "Toggle Rendered View", (v) => toggleRenderedViewAtCaret(v), {
category: "View",
keywords: ["reader mode", "render documentation comment", "javadoc", "edit comment"],
@@ -1348,7 +1372,7 @@ export function registerEditorActions(): () => void {
edit("code.joinLines", "Join Lines", (v) => joinLines(v)),
edit("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
edit("code.transpose", "Transpose", (v) => transpose(v), { category: "Editor Actions" }),
edit("code.cycleCase", "Cycle Identifier Case", (v) => cycleCase(v), {
edit("code.cycleCase", "Cycle Identifier Case", (v) => cycleCase(v, editorPrefs().smartKeys.cycleCase), {
keywords: ["camel", "snake", "kebab", "pascal", "screaming"],
}),
caret("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), {
+35 -1
Переглянути файл
@@ -4,9 +4,10 @@ import type { EditorSlot as EditorSlotType } from "./model/slot";
import type { DocModel } from "./model/document";
let activeSlot: Partial<EditorSlotType> | null = null;
let activeManager: { resetRenderedDocs(): void } | null = null;
vi.mock("./controller", async (importOriginal) => ({
...(await importOriginal<object>()),
editorController: () => ({ activeSlot }),
editorController: () => ({ activeSlot, manager: activeManager }),
}));
/** Writes the dotted key into the current settings, as the host does. */
@@ -35,6 +36,7 @@ const { createMemoryBackend } = await import("./backend");
const { DocumentManager } = await import("./model/document");
const { EditorSlot } = await import("./model/slot");
const { gutterIconsOn, localAppearanceField } = await import("./cm/prefs");
const { renderDocComments } = await import("./cm/renderedDocs");
const { DEFAULT_SETTINGS } = await import("@/features/settings/model/schema");
const { resetDistractionFree } = await import("@/workbench/distractionFree");
const { clearBreadcrumbOverrides, pruneBreadcrumbOverrides, useBreadcrumbOverrides } = await import("./breadcrumbs");
@@ -46,6 +48,7 @@ beforeAll(() => {
afterAll(() => dispose());
afterEach(() => {
activeSlot = null;
activeManager = null;
clearBreadcrumbOverrides();
useProject.setState({ settings: null });
useContextKeys.setState({}, true);
@@ -172,6 +175,7 @@ describe("active editor appearance toggles", () => {
settings: () => useProject.getState().settings,
notify: vi.fn(),
});
activeManager = manager;
const model = await manager.acquire(file);
models.add(model);
const slot = new EditorSlot(model, `${file}-${slots.size}`, {
@@ -257,6 +261,36 @@ describe("active editor appearance toggles", () => {
for (const control of controls) expect(actionToggled(getAction(control.id))).toBe(local[control.key]);
});
it("toggles rendered doc comments globally and clears every open document's override", async () => {
const first = await openSlot();
const second = await openSlot(otherPath);
activeSlot = first;
first.model.toggleRenderedDocs();
second.model.toggleRenderedDocs();
second.model.toggleRenderedDocs();
expect(first.model.renderedDocsOn()).toBe(true);
expect(second.model.renderedDocsOn()).toBe(false);
const action = getAction("editor.toggleRenderedDocsForAll");
expect(action).toMatchObject({ title: "Render All Doc Comments", category: "View" });
expect(resolveActionId("ToggleRenderedDocPresentationForAll")).toBe("editor.toggleRenderedDocsForAll");
expect(actionToggled(action)).toBe(false);
expect(await executeAction("editor.toggleRenderedDocsForAll")).toBe(true);
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.appearance.renderDocComments", "true");
expect(actionToggled(action)).toBe(true);
expect(first.model.renderedDocsOverride).toBeNull();
expect(second.model.renderedDocsOverride).toBeNull();
expect(first.currentState().facet(renderDocComments)).toBe(true);
expect(second.currentState().facet(renderDocComments)).toBe(true);
expect(await executeAction("editor.toggleRenderedDocsForAll")).toBe(true);
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.appearance.renderDocComments", "false");
expect(actionToggled(action)).toBe(false);
expect(first.currentState().facet(renderDocComments)).toBe(false);
expect(second.currentState().facet(renderDocComments)).toBe(false);
});
it("lets a local Gutter Icons override enable providers while the global setting is off", async () => {
setGlobalAppearance({ lineNumbers: true, whitespaces: false, gutterIcons: false, indentGuides: true });
const first = await openSlot();
+6 -3
Переглянути файл
@@ -36,7 +36,7 @@ import {
} from "@codemirror/commands";
import { SearchCursor } from "@codemirror/search";
import { humpLeft, humpRight, wordStartLeft } from "../model/camelHumps";
import { cycleIdentifierCase, wordSpan } from "../model/identifierCase";
import { cycleIdentifierCase, wordSpan, type IdentifierCase } from "../model/identifierCase";
import { restartSticky } from "./stickySelection";
type Node = ReturnType<ReturnType<typeof syntaxTree>["resolveInner"]>;
@@ -1087,7 +1087,10 @@ const NAME_CHAR = /[\p{L}\p{N}_$-]/u;
* or of each selection, from the style it is written in: snake_case →
* SCREAMING_SNAKE_CASE → kebab-case → camelCase → PascalCase.
*/
export const cycleCase: Command = (view) => {
export const cycleCase = (
view: EditorView,
enabled: Readonly<Partial<Record<IdentifierCase, boolean>>> = {},
): boolean => {
const { state } = view;
if (state.readOnly) return false;
/** The `-`-joined name at or right before `pos`. */
@@ -1107,7 +1110,7 @@ export const cycleCase: Command = (view) => {
const span = wordSpan(state.sliceDoc(name.from, name.to));
if (!span) return { range: r };
const from = name.from + span.from;
const insert = cycleIdentifierCase(state.sliceDoc(from, name.from + span.to));
const insert = cycleIdentifierCase(state.sliceDoc(from, name.from + span.to), enabled);
if (insert === null) return { range: r };
changed = true;
const set = state.changes({ from, to: name.from + span.to, insert });
+7
Переглянути файл
@@ -1099,6 +1099,13 @@ export class DocumentManager {
for (const m of this.byPath.values()) m.applySettings();
}
resetRenderedDocs() {
for (const model of this.byPath.values()) {
model.renderedDocsOverride = null;
model.applySettings();
}
}
/** Saves dirty documents; failures are notified, and an explicit Save All also rejects with them. */
async saveAll(reason: "explicit" | "auto", skipUntitled = false) {
const errors: unknown[] = [];
+15
Переглянути файл
@@ -39,6 +39,21 @@ describe("cycle identifier case", () => {
expect(cycleIdentifierCase("MyVarName")).toBe("my_var_name");
});
it("goes only through the styles turned on, starting from the one the name is written in", () => {
const camelSnake = { screaming: false, kebab: false, pascal: false };
expect(cycleIdentifierCase("myVarName", camelSnake)).toBe("my_var_name");
expect(cycleIdentifierCase("my_var_name", camelSnake)).toBe("myVarName");
// A name in a style that is turned off still moves on to the next one that is on.
expect(cycleIdentifierCase("my-var-name", camelSnake)).toBe("myVarName");
expect(cycleIdentifierCase("MyVarName", camelSnake)).toBe("my_var_name");
// Only the name's own style on: nothing else to go to.
expect(
cycleIdentifierCase("myVarName", { snake: false, screaming: false, kebab: false, pascal: false }),
).toBeNull();
// One word in snake_case is written as in camelCase, so with Name and NAME off it stays.
expect(cycleIdentifierCase("name", { pascal: false, screaming: false })).toBeNull();
});
it("gives one word its three spellings: name → Name → NAME", () => {
expect(cycleIdentifierCase("name")).toBe("Name");
expect(cycleIdentifierCase("Name")).toBe("NAME");
+9 -3
Переглянути файл
@@ -81,14 +81,20 @@ export function toIdentifierCase(text: string, style: IdentifierCase): string {
/**
* `text` in the next style of the cycle, skipping the styles that write it the
* same way; null when none writes it differently.
* same way and those `enabled` turns off (Settings › Editor › General › Smart
* Keys); null when none writes it differently.
*/
export function cycleIdentifierCase(text: string): string | null {
export function cycleIdentifierCase(
text: string,
enabled: Readonly<Partial<Record<IdentifierCase, boolean>>> = {},
): string | null {
const current = identifierCase(text);
if (!current) return null;
// One word has three spellings, not five: name → Name → NAME.
const single = identifierWords(text).length === 1 && !SEPARATOR.test(text);
const order: readonly IdentifierCase[] = single ? ["camel", "pascal", "screaming", "snake"] : identifierCases;
const all: readonly IdentifierCase[] = single ? ["camel", "pascal", "screaming", "snake"] : identifierCases;
// The style the name is written in stays the starting point even when it is turned off.
const order = all.filter((style) => style === current || enabled[style] !== false);
const start = Math.max(0, order.indexOf(current));
for (let step = 1; step <= order.length; step++) {
const next = toIdentifierCase(text, order[(start + step) % order.length]!);
+9 -11
Переглянути файл
@@ -530,7 +530,7 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
const wrappers = useTextEditorWrappers((s) => s.wrappers);
if (isTextInput(tab.input)) {
const virtual = tab.input.kind === "virtual" ? virtualData(tab.input) : undefined;
const wrapper = tab.input.kind === "file" ? textEditorWrapperFor(wrappers, tab.input.path) : undefined;
const wrapper = wrapperForInput(wrappers, tab.input);
const host = shown && <TextEditorHost key={tab.id} tabId={tab.id} />;
return (
<>
@@ -593,12 +593,7 @@ function keptTabs(
const recent = mru
.map((id) => tabs.find((t) => t.id === id))
.filter(
(t): t is Tab =>
!!t &&
(!!kinds.get(t.input.kind)?.keepAlive ||
(t.input.kind === "file" &&
t.input.path !== undefined &&
!!textEditorWrapperFor(wrappers, t.input.path)?.keepAlive)),
(t): t is Tab => !!t && (!!kinds.get(t.input.kind)?.keepAlive || !!wrapperForInput(wrappers, t.input)?.keepAlive),
)
.slice(0, KEPT_TABS);
// In tab order, so switching tabs doesn't move their DOM (which would lose scroll offsets).
@@ -664,10 +659,7 @@ function KindEditor({ tab }: { tab: Tab }) {
function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
const ctrl = editorController();
const wrappers = useTextEditorWrappers((s) => s.wrappers);
const LayoutActions =
tab.input.kind === "file" && tab.input.path
? textEditorWrapperFor(wrappers, tab.input.path)?.tabActions
: undefined;
const LayoutActions = wrapperForInput(wrappers, tab.input)?.tabActions;
const [open, setOpen] = useState(false);
const moreRef = useRef<HTMLButtonElement>(null);
return (
@@ -704,3 +696,9 @@ function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
</div>
);
}
function wrapperForInput(wrappers: ReadonlyMap<string, TextEditorWrapperContribution>, input: EditorInput) {
if (input.path && (input.kind === "file" || input.kind === "virtual")) {
return textEditorWrapperFor(wrappers, input.path, input.kind === "virtual");
}
}
+20 -1
Переглянути файл
@@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Diagnostic, FileProblems } from "@/bindings";
const state = vi.hoisted(() => ({
trusted: true as boolean | undefined,
projectChanged: () => {},
trustChanged: () => {},
remoteChanged: () => {},
report: vi.fn(),
}));
@@ -20,9 +22,11 @@ vi.mock("@/platform/ipc", async (importOriginal) => ({
vi.mock("@/platform/project", () => ({
useProject: {
getState: () => ({ project: { root: "/p" } }),
getState: () => ({ project: { root: "/p", trusted: state.trusted } }),
subscribe: (fn: (s: unknown, prev: unknown) => void) => {
state.projectChanged = () => fn({ project: { root: "/p" } }, { project: null });
state.trustChanged = () =>
fn({ project: { root: "/p", trusted: true } }, { project: { root: "/p", trusted: false } });
return () => {};
},
},
@@ -58,6 +62,7 @@ describe("reportProblems", () => {
clearProblems();
reports.length = 0;
state.report.mockReset();
state.trusted = true;
applyDiagnosticsEvent("/p/a.rs", "ra", [d(1), d(2)]);
stop = reportProblems();
});
@@ -76,6 +81,20 @@ describe("reportProblems", () => {
]);
});
it("reports nothing without a retry timer in a restricted project, then once when trusted", async () => {
stop();
state.trusted = false;
reports.length = 0;
stop = reportProblems();
await vi.advanceTimersByTimeAsync(5000);
expect(reports).toHaveLength(0);
expect(vi.getTimerCount()).toBe(0);
state.trusted = true;
state.trustChanged();
await vi.advanceTimersByTimeAsync(1000);
expect(summary()).toEqual([[true, [["/p/a.rs", 2]]]]);
});
it("retries a failed delta with the full snapshot", async () => {
await vi.advanceTimersByTimeAsync(1000);
state.report.mockRejectedValueOnce(new Error("disconnected"));
+4 -2
Переглянути файл
@@ -13,7 +13,9 @@ export function reportProblems(): () => void {
let timer: ReturnType<typeof setTimeout> | null = null;
const flush = () => {
timer = null;
if (!useProject.getState().project) return;
const project = useProject.getState().project;
// Restricted Mode refuses this command; the trust change below resets and reschedules.
if (!project || project.trusted === false) return;
const map = useProblems.getState().map;
const files: FileProblems[] = [];
for (const [path, sources] of map)
@@ -37,7 +39,7 @@ export function reportProblems(): () => void {
if (s.map !== prev.map) schedule();
});
const offProject = useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) {
if (s.project?.root !== prev.project?.root || s.project?.trusted !== prev.project?.trusted) {
reset = true;
reported = new Map();
schedule();
+2 -2
Переглянути файл
@@ -439,7 +439,7 @@ export function DiagramView({ data, onJump }: { data: DiagramData; onJump?: () =
</marker>
</defs>
{arrangement &&
edges.map((e, i) => {
edges.map((e) => {
const [from, to] = [nodes[e.from]!, nodes[e.to]!];
const [a, b] = [boxOf(from.key), boxOf(to.key)];
if (!a || !b || arrangement.hidden.has(from.key) || arrangement.hidden.has(to.key)) return null;
@@ -447,7 +447,7 @@ export function DiagramView({ data, onJump }: { data: DiagramData; onJump?: () =
const toY = rowCenter(to, b, arrangement.collapsed.has(to.key), e.toColumns[0]);
return (
<path
key={i}
key={`${from.key}:${e.fromColumns.join(",")}→${to.key}:${e.toColumns.join(",")}`}
className={clsx(styles.link, e.optional && styles.optional)}
d={linkPath(a, fromY, b, toY)}
markerEnd={`url(#${markerId})`}
+9 -1
Переглянути файл
@@ -1495,7 +1495,15 @@ function QuickDoc({ node, anchor }: { node: DbNode; anchor: { x: number; y: numb
);
}
function SourceFolderDialog({ folder, sources = [] }: { folder: DbSourceFolder | null; sources?: string[] }) {
const NO_SOURCES: readonly string[] = [];
function SourceFolderDialog({
folder,
sources = NO_SOURCES,
}: {
folder: DbSourceFolder | null;
sources?: readonly string[];
}) {
const [name, setName] = useState(folder?.name ?? "");
const [busy, setBusy] = useState(false);
const submit = async () => {
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff. Show more