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

...
Автор SHA1 Повідомлення Дата
l0ng-ai a4eeefa10d fix(lsp): wait through planned server restarts 2026-11-09 17:38:43 +08:00
l0ng-ai 2955cdcf9c fix(editor): restore an evicted tab's exact scroll offset (#2324) 2026-11-09 17:26:35 +08:00
l0ng-ai 5a48beab07 feat(dotnet): add workspace, NuGet and test workflows (#2303)
* feat(run): show .NET test results and rerun failed methods

* feat(dotnet): add workspace, NuGet and editor test workflows

* fix(dotnet): discard cancelled queries and scan test targets linearly
2026-11-09 17:17:27 +08:00
Zhu Minhaoтаzmh69695328 dfa610beb0 fix(gradle): read dependencies from scripts a build applies (#2277)
Dependencies declared in a script pulled in with `apply from:` never reached External Libraries, and `"g🅰️${v}"` versions were dropped because statement splitting at `{` cut them in half. The scan now follows `apply from` recursively (Groovy and Kotlin DSL; `$rootDir`, `$projectDir`, `rootProject.projectDir`; relative paths from the project directory, then beside the applying script; URLs and missing files skipped; cycles and aliases cut by canonical path, bounded at 256 scripts and 32 levels). It fills `ext`/`extra` values (`ext.x`, `ext { }`, `ext["x"]`, `extra["x"]`, `val x by extra(...)`) into `${...}` versions with gradle.properties taking precedence, and counts applied scripts as build inputs, so editing one invalidates the cached model and refreshes the Build tool window and External Libraries.

Co-authored-by: zmh69695328 <[email protected]>
2026-11-09 17:05:20 +08:00
ovra e86134ce83 feat(vcs): soft-wrap long lines in the diff viewer (#2286)
The diff viewer never soft-wrapped, so a long changed line ran off the right edge. Diff panes now follow Settings › Editor › General › Soft-wrap files for the file, and the viewer's settings menu has a Use Soft Wraps checkbox that overrides it for all diffs and is remembered with the other viewer options. View › Active Editor › Soft-Wrap (editor.toggleSoftWrap) also toggles it when a diff pane has focus. Toggling reconfigures both panes in place, keeping the selection and the scroll position, including aligned split diffs.

Closes #2263

Co-authored-by: atlas-u <[email protected]>
2026-11-09 17:03:21 +08:00
Deng Liuтаl0ng-ai 4bc08a1084 fix(windows): open loose external files in the focused project window (#923)
* fix(windows): route loose external files to active project window

* fix(windows): open loose files in the focused window only

Loose files join the focused window when it holds a local project or
LightEdit. A Welcome or remote window, or a project window in the
background, keeps the previous routing: the LightEdit window, else a
free window, else a new one.

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-11-09 16:27:45 +08:00
arookieofc cb2f249db5 fix(java): pass m2e an effective settings file carrying the configured local repository (#1739) (#2301)
m2e resolves the local repository from the Maven settings XML, never from
-Dmaven.repo.local, so JDTLS imports kept downloading into ~/.m2/repository
even when the IDE's own mvn runs honored the configured path. When a local
repository is configured but the user settings lack <localRepository>, derive
an effective settings file under <root>/.openidea/ and pass it as
java.configuration.maven.userSettings. Settings that already declare
<localRepository> are passed through untouched.
2026-11-09 16:16:38 +08:00
Hacbit 2dd57d095f feat(unity): open scripts from external editor arguments (#2296)
* feat(app): support Unity external editor navigation

* docs(unity): explain manual external editor setup
2026-11-09 16:03:37 +08:00
Clarence 5ab5c8c677 fix(run): read JetBrains path options written as file: URLs (#2287)
IDEA writes path options as URLs (`WORKING_DIRECTORY = file://$PROJECT_DIR$`). The run configuration importer expanded the macros but never stripped the `file:` scheme, so on Windows `file://C:/project` became the drive-relative `C:project` and was joined onto the project directory, and imported configurations failed to launch. Every path-valued option the importer reads (working directories, SDK home, script and settings files, pytest targets, env files including EnvFile entries, package.json, package manager, node interpreter, config file, test directory/file, JS file, interpreter path, path arguments) now goes through one conversion: drive letters in the authority position, `localhost` as a local authority, UNC for a real host, and IDEA's unencoded paths kept verbatim. Env-file lists no longer split at a URL's scheme colon on Unix.

Co-authored-by: Clarence404 <[email protected]>
2026-11-09 15:48:31 +08:00
Deng Liuтаdengliu 14aa612038 fix(markdown): keep Mermaid styles scoped after rewriting diagram ids (#2288)
reid() made cached Mermaid diagrams' ids unique by suffixing every id, but only rewrote references followed by `"` or `)`. The root svg id changed while the selectors in the SVG's own <style> (`#id{`, `#id .cluster rect`, `#id>`…) did not, so none of Mermaid's rules matched and clusters, nodes and edges rendered solid black; the suffix also broke selectors that match marker ids by suffix. Ids now get a per-application prefix, rewritten consistently in id, href/xlink:href, aria-labelledby/describedby, url(#…) in presentation attributes (quoted or not) and the ID selectors of <style> rules, leaving declarations (hex colours), labels and unknown references untouched; an id that is a prefix of another (`-1` vs `-10`) stays distinct.

Co-authored-by: dengliu <[email protected]>
2026-11-09 15:29:11 +08:00
l0ng-ai ab5f71b442 fix(installer): preserve legacy Windows installation scope (#2225) 2026-11-09 15:26:21 +08:00
Deng Liu c5124b809d feat(docker): add Services dashboards, layers, processes, view filters and log editor tabs (#2246) 2026-11-09 15:24:52 +08:00
ppxbтаppxb a206ac0ca5 fix(vim): accept special-key names in any case in rc mappings (#2291)
codemirror-vim matches special keys only in their exact canonical spelling, so rc mappings written for Vim/IdeaVim such as `inoremap jk <esc>` never fired. The rc parser now canonicalizes `<...>` key names on both sides of a mapping: any case and the usual aliases (Esc, CR/Enter/Return, BS, Del, Ins, Space, Tab, Bar, Bslash, arrows, Home/End, PageUp/PageDown, F1-F12), modifier prefixes in any case and order (C-/S-/A-/M-, D- as Command), `<lt>` kept literal on the right-hand side, Ex mappings ending in <Enter>/<Return>, and leader values containing `$&`. Unknown tokens are left untouched.

Closes #2281

Co-authored-by: ppxb <[email protected]>
2026-11-09 15:23:41 +08:00
arookieofc b12fabd472 fix(lightedit): merge the saved session with launched tabs instead of replacing them (#2229) (#2290) 2026-11-09 15:22:18 +08:00
e77ee39047 fix(editor): keep the corner overlay from covering line ends (#2289)
The inspection widget and the Review Mode group float in `.cm-editor`,
outside `.cm-scroller`: they neither scroll with the text nor count in
`scrollWidth`, so at full horizontal scroll the last characters of a line
landed under them.

Reserve the corner's measured width in the lines' right padding, next to
the room the fixed padding already keeps for the overview lane.

Co-authored-by: yhqian <[email protected]>
Co-authored-by: Claude Code <[email protected]>
2026-11-09 15:20:49 +08:00
l0ng-ai 1a008fd17e perf(java): reuse usage search results and skip covered folders when widening (#2278)
Find Usages and usage counts searched again on every request: about two
seconds each for a common type such as String.

- The Java usages extension (1.12.0) keeps answers by search target until a
  Java element, the classpath or an unsaved edit changes, and requests for
  the same target share one search.
- Widening checks up to 5000 candidates against the server's analysis scope
  before applying the 300-file limit, so names mentioned in many covered
  files no longer report "too many files".
- Candidate scans skip the source folders the server covers fully
  (openidea.workspace.coveredRoots) instead of reading every file.
- Commands a server registers after initializing are added to its commands.
2026-11-09 14:44:48 +08:00
ppxb d2603facdf feat(tomcat): skip the before-launch build when the WAR is up to date (#2276)
* feat(tomcat): skip the before-launch build when the WAR is up to date

* fix(i18n): remove obsolete Tomcat WAR build messages from catalogs
2026-11-09 14:42:47 +08:00
l0ng-ai 89c7ae7d4c perf(java): count usage lenses in the project sources only (#2244)
* perf(java): count usage lenses in the project sources only

Usage lenses asked JDT LS for a full references search per declaration,
which also scans every dependency jar and the JDK. In a library class such
as java.lang.String that kept JDT LS busy for tens of seconds per pass,
and failed counts were asked again on every scroll.

- Scoped Java searches without libraries pass the "sources" scope.
- Lenses count declarations near the viewport (10 lines instead of 60).
- Incomplete counts are remembered per document version and asked again
  once the server settles, instead of on every pass.

* perf(java): turn off the language server's own reference lenses

JDT LS shows a references lens above each declaration by default and the
editor resolved them all at once, a references search per declaration on
every open and edit. The editor's usage lenses already count usages.

* style(editor): keep the usage lens's unrelated lines as they were
2026-11-09 14:34:05 +08:00
misswell 89b178f9aa feat(run): a Find entry on every console, not just the Run toolbar (#1764)
Console search exists (⌘F, the magnifier in a Run tab's toolbar), but a console without a
toolbar of its own — a stack-trace tab, say — offered no visible way in: the shortcut only
worked once the output had focus, and nothing said so.

Every uncontrolled ConsoleView now shows a small Find button over the output's top-right
corner, opening the same find bar (query, match count, Enter/Shift+Enter, case and regex
options). Consoles whose find bar a toolbar drives keep exactly one entry: the toolbar's.

How it was verified:
- pnpm vitest run src/features/run/findBar.test.tsx: 9 passed, including a new test that
  the button opens the find bar and focuses its input.
- pnpm typecheck.
2026-11-09 14:29:23 +08:00
Bruno BelloniтаClaude Opus 5.5 c5c5930a75 perf(terminal): skip DOM work for rows whose markup did not change (#2239)
xterm's DOM renderer rebuilds every dirty row with replaceChildren even when
the new spans are identical. Full-screen TUIs (Grok, Claude Code) redraw the
whole screen on each spinner tick, so WebKitGTK restyles, lays out and paints
all rows several times a second and keystrokes queue behind it.

Install a row cache on xterm 6's DomRenderer: rows are still built, but a row
whose markup matches what is already shown is left in place. clear() and link
underlines rebuild rows outside renderRows, so they reset the cache. The
install is a no-op when xterm's renderer no longer has the expected shape.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-09 14:23:32 +08:00
l0ng-ai 40be4e4c17 fix(agents): leave a conversation's end for scrolls no layout caused (#2283)
Following the end snapped back any scroll away from it that didn't follow a
wheel, touch, key or pointer press. A scroll without one, like dragging the
scrollbar thumb where no pointer event reaches the page or a programmatic
jump, was undone. The offset WebKit moves back on its own comes with a change
of the content height while rows lay out; only such a scroll keeps following
now, any other leaves the end.
2026-11-09 14:19:47 +08:00
l0ng-ai 502cc348ba perf(editor): keep recently used editor views across tab switches (#2282)
Switching between file tabs destroyed the hidden tab's CodeMirror view and
built a new one on return: every switch re-ran the view's plugins, re-measured
the height map (the scrollbar jumped) and re-requested inlay hints, usages and
diagnostics, which popped in and shifted the text up to a second later.

The eight most recently hidden views are now kept detached and re-attached on
return, with their decorations, height map and plugin state. Edits while hidden
go to the kept view; plugins that skip work while their view is detached catch
up when it is shown again (`viewShown`).

Switching also forces fewer layouts: the Switcher no longer gives focus back to
the editor left behind when it opens another tab, the tab strip only measures
the active tab when it isn't known to be in view, and focus moving between
editors no longer drops the old editor's DOM caret.

The tabs perf scenario counts views rebuilt when switching back (budget 0).
2026-11-09 14:16:21 +08:00
181 змінених файлів з 11887 додано та 658 видалено

No files matched your search

+641 -9
Переглянути файл
@@ -109,11 +109,11 @@ fn strip_comments(text: &str) -> String {
/// Quoted string literals in `s`.
fn literals(s: &str) -> Vec<String> {
let mut out = Vec::new();
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '"' || c == '\'' {
out.push(chars.by_ref().take_while(|&n| n != c).collect());
}
let mut rest = s;
while let Some(start) = rest.find(['"', '\'']) {
let Some((value, used)) = literal(&rest[start..]) else { break };
out.push(value);
rest = &rest[start + used..];
}
out
}
@@ -565,11 +565,12 @@ fn is_dependency_configuration(name: &str) -> bool {
/// `(group, artifact, version)` of the external dependencies a build script declares:
/// `implementation 'g:a:v'`, `api("g:a:v:classifier@jar")`, and the map notation
/// `implementation group: 'g', name: 'a', version: 'v'` (Groovy) / `group = "g", …` (Kotlin).
/// Versions with interpolations, ranges and catalog aliases (`libs.x`) are skipped.
pub fn script_dependencies(text: &str) -> Vec<(String, String, String)> {
/// Versions written as `${gsonVersion}` are filled in from `properties` (`ext` values, see
/// [`script_properties`]); ranges, unknown names and catalog aliases (`libs.x`) are skipped.
pub fn script_dependencies(text: &str, properties: &BTreeMap<String, String>) -> Vec<(String, String, String)> {
let text = strip_comments(text);
let mut out = Vec::new();
for line in text.lines().flat_map(|l| l.split(['{', ';'])) {
for line in text.lines().flat_map(statements) {
let line = line.trim_start();
let name: String = line.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
if name.is_empty() || !is_dependency_configuration(&name) {
@@ -591,6 +592,7 @@ pub fn script_dependencies(text: &str) -> Vec<(String, String, String)> {
}),
};
if let Some((g, a, v)) = coordinate {
let v = interpolate(&v, properties);
let plain = |s: &str| {
!s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+'))
};
@@ -602,11 +604,354 @@ pub fn script_dependencies(text: &str) -> Vec<(String, String, String)> {
out
}
/// `line` split at `{` and `;` outside quoted strings, so a `${version}` stays in one piece.
fn statements(line: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut start = 0;
let mut index = 0;
while index < line.len() {
let c = line[index..].chars().next().unwrap();
if c == '"' || c == '\'' {
index += literal(&line[index..]).map_or(line.len() - index, |(_, used)| used);
continue;
}
if matches!(c, '{' | '}' | ';' | '\n') {
out.push(&line[start..index]);
start = index + c.len_utf8();
}
index += c.len_utf8();
}
out.push(&line[start..]);
out
}
/// `apply from: 'x.gradle'` (Groovy) and `apply(from = "x.gradle.kts")` (Kotlin DSL)
/// targets, as written in the script.
pub fn applied_scripts(text: &str) -> Vec<String> {
let text = strip_comments(text);
let mut out = Vec::new();
for (index, word) in code_words(&text) {
if word != "apply" || !starts_word(&text, index) {
continue;
}
let mut rest = text[index + "apply".len()..].trim_start();
if let Some(inner) = rest.strip_prefix('(') {
rest = inner.trim_start();
}
let Some(rest) = rest.strip_prefix("from") else { continue };
let Some(rest) = rest.trim_start().strip_prefix(':').or_else(|| rest.trim_start().strip_prefix('=')) else {
continue;
};
let mut rest = rest.trim_start();
if let Some(inner) = rest.strip_prefix("file") {
let inner = inner.trim_start();
if let Some(inner) = inner.strip_prefix('(') {
rest = inner.trim_start();
}
}
if let Some((path, _)) = literal(rest) {
out.push(path);
}
}
out
}
/// Literal extra properties declared by Groovy's `ext` or Kotlin's `extra`.
pub fn script_properties(text: &str) -> BTreeMap<String, String> {
let text = strip_comments(text);
let mut out = BTreeMap::new();
for (index, word) in code_words(&text) {
if !starts_word(&text, index) {
continue;
}
let rest = text[index + word.len()..].trim_start();
if word == "val" || word == "var" {
let (name, rest) = identifier(rest);
let Some(rest) = rest.trim_start().strip_prefix("by").map(str::trim_start) else { continue };
let Some(rest) = rest.strip_prefix("extra").map(str::trim_start) else { continue };
if let Some(rest) = rest.strip_prefix('(')
&& let Some((value, used)) = literal(rest.trim_start())
&& rest.trim_start()[used..].trim_start().starts_with(')')
&& !name.is_empty()
{
out.insert(name.to_owned(), value);
}
continue;
}
if word != "ext" && word != "extra" {
continue;
}
if let Some(block) = rest.strip_prefix('{') {
if let Some(end) = matching_brace(block) {
out.extend(assignments(&block[..end]));
}
} else if let Some(rest) = rest.strip_prefix('.') {
let (name, rest) = identifier(rest);
if let Some(value) = assigned_literal(rest)
&& !name.is_empty()
{
out.insert(name.to_owned(), value);
}
} else if let Some(rest) = rest.strip_prefix('[')
&& let Some((name, used)) = literal(rest.trim_start())
&& let Some(rest) = rest.trim_start()[used..].trim_start().strip_prefix(']')
&& let Some(value) = assigned_literal(rest)
{
out.insert(name, value);
}
}
out
}
pub(crate) fn file_properties(build_dir: &Path) -> BTreeMap<String, String> {
let text = std::fs::read_to_string(build_dir.join("gradle.properties")).unwrap_or_default();
text.lines()
.filter_map(|line| {
let line = line.trim();
if line.starts_with(['#', '!']) {
return None;
}
let separator = line.find(|c: char| c == '=' || c == ':' || c.is_whitespace())?;
let (key, rest) = line.split_at(separator);
let value = rest.trim_start().trim_start_matches(['=', ':']).trim_start();
(!key.is_empty()).then(|| (key.to_owned(), value.to_owned()))
})
.collect()
}
/// The build script of a project and, recursively, the scripts it applies with `apply from`,
/// read from disk: absolute path and text. Targets that do not exist are skipped.
pub fn scripts_of(root: &Path, project_dir: &Path, build_dir: &Path, build_file: &Path) -> Vec<(PathBuf, String)> {
const MAX_SCRIPTS: usize = 256;
const MAX_DEPTH: usize = 32;
let mut out = Vec::new();
let mut seen = std::collections::HashSet::new();
let first = normalize(&root.join(build_file));
let Ok(identity) = dunce::canonicalize(&first) else { return out };
seen.insert(identity);
let mut stack = vec![(first, 0)];
while let Some((path, depth)) = stack.pop() {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
if depth < MAX_DEPTH {
let mut targets = Vec::new();
for spec in applied_scripts(&text) {
if seen.len() >= MAX_SCRIPTS {
break;
}
if let Some(target) = resolve_script(&spec, &path, project_dir, build_dir)
&& let Ok(identity) = dunce::canonicalize(&target)
&& seen.insert(identity)
{
targets.push((target, depth + 1));
}
}
stack.extend(targets.into_iter().rev());
}
out.push((path, text));
}
out
}
/// Relative targets are project-scoped, with a lenient fallback beside the applying script.
fn resolve_script(spec: &str, script: &Path, project_dir: &Path, build_dir: &Path) -> Option<PathBuf> {
let spec = spec.trim();
if spec.contains("://") {
return None;
}
let properties = BTreeMap::from([
("rootDir".into(), build_dir.to_string_lossy().into_owned()),
("rootProject.projectDir".into(), build_dir.to_string_lossy().into_owned()),
("projectDir".into(), project_dir.to_string_lossy().into_owned()),
]);
let spec = interpolate(spec, &properties);
if spec.contains('$') {
return None;
}
let path = Path::new(&spec);
if path.is_absolute() {
return path.is_file().then(|| normalize(path));
}
let project_path = normalize(&project_dir.join(path));
if project_path.is_file() {
return Some(project_path);
}
let path = normalize(&script.parent()?.join(path));
path.is_file().then_some(path)
}
pub(crate) fn project_build_dir(root: &Path, model: &GradleModel, project: &GradleProject) -> PathBuf {
let dir = project.build.as_ref().and_then(|build| model.projects.iter().find(|p| &p.path == build));
root.join(dir.map_or(&model.dir, |p| &p.dir))
}
/// `2.8.9` for `${gsonVersion}` / `$gsonVersion` / `${ext.gsonVersion}`; unknown names and
/// expressions are left as written, so ranges and catalogs stay skipped.
fn interpolate(value: &str, properties: &BTreeMap<String, String>) -> String {
if !value.contains('$') {
return value.to_owned();
}
let mut out = String::with_capacity(value.len());
let mut chars = value.chars().peekable();
while let Some(c) = chars.next() {
if c != '$' {
out.push(c);
continue;
}
let braced = chars.peek() == Some(&'{');
if braced {
chars.next();
}
let mut name = String::new();
if braced {
for n in chars.by_ref() {
if n == '}' {
break;
}
name.push(n);
}
} else {
while let Some(&n) = chars.peek() {
if n.is_alphanumeric() || n == '_' || n == '.' {
name.push(n);
chars.next();
} else {
break;
}
}
}
let key = name.strip_prefix("ext.").or_else(|| name.strip_prefix("extra.")).unwrap_or(&name);
let bracket = name.strip_prefix("ext[").or_else(|| name.strip_prefix("extra[")).and_then(|rest| {
let (key, used) = literal(rest.trim_start())?;
(rest.trim_start()[used..].trim() == "]").then_some(key)
});
match properties.get(bracket.as_deref().unwrap_or(key)) {
Some(v) if !name.is_empty() => out.push_str(v),
_ => {
out.push('$');
if braced {
out.push('{');
}
out.push_str(&name);
if braced {
out.push('}');
}
}
}
}
out
}
/// Whether `index` starts a whole word in `text` (not `reapply`, `my.apply`).
fn starts_word(text: &str, index: usize) -> bool {
text[..index].chars().next_back().is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '.'))
}
/// Identifiers outside quoted strings, with their byte positions.
fn code_words(text: &str) -> Vec<(usize, &str)> {
let mut out = Vec::new();
let mut index = 0;
while index < text.len() {
let c = text[index..].chars().next().unwrap();
if c == '"' || c == '\'' {
index += literal(&text[index..]).map_or(text.len() - index, |(_, used)| used);
} else if c.is_alphabetic() || c == '_' {
let (word, _) = identifier(&text[index..]);
out.push((index, word));
index += word.len();
} else {
index += c.len_utf8();
}
}
out
}
fn identifier(text: &str) -> (&str, &str) {
let end = text.find(|c: char| !(c.is_alphanumeric() || c == '_')).unwrap_or(text.len());
text.split_at(end)
}
fn assigned_literal(text: &str) -> Option<String> {
let rest = text.trim_start().strip_prefix('=')?.trim_start();
let (value, used) = literal(rest)?;
// Do not turn a computed value (`'1.' + suffix`) into a concrete version.
let tail = rest[used..].trim_start_matches([' ', '\t', '\r']);
(tail.is_empty() || tail.starts_with(['\n', ';', '}'])).then_some(value)
}
/// The quoted string at the start of `s`, and how many bytes it spans.
fn literal(s: &str) -> Option<(String, usize)> {
let quote = s.chars().next().filter(|c| *c == '"' || *c == '\'')?;
let rest = &s[quote.len_utf8()..];
let mut index = 0;
while index < rest.len() {
let c = rest[index..].chars().next()?;
if c == quote {
return Some((rest[..index].to_owned(), quote.len_utf8() + index + c.len_utf8()));
}
if c == '\\' {
index += c.len_utf8();
index += rest[index..].chars().next()?.len_utf8();
} else if quote == '"' && rest[index..].starts_with("${") {
index += 2;
index += matching_brace(&rest[index..])? + 1;
} else {
index += c.len_utf8();
}
}
None
}
/// Byte index of the `}` closing a `{` that was already consumed, ignoring quoted text.
fn matching_brace(text: &str) -> Option<usize> {
let mut depth = 1usize;
let mut index = 0;
while index < text.len() {
let c = text[index..].chars().next()?;
if c == '"' || c == '\'' {
index += literal(&text[index..])?.1;
continue;
}
if c == '{' {
depth += 1;
} else if c == '}' {
depth -= 1;
if depth == 0 {
return Some(index);
}
}
index += c.len_utf8();
}
None
}
/// `name = 'value'` pairs in `text`.
fn assignments(text: &str) -> Vec<(String, String)> {
statements(text)
.into_iter()
.filter_map(|statement| {
let (name, rest) = identifier(statement.trim_start());
let value = assigned_literal(rest)?;
(!name.is_empty()).then(|| (name.to_owned(), value))
})
.collect()
}
/// Every settings and build script of the model (for change detection).
pub fn build_files(root: &Path, model: &GradleModel) -> Vec<PathBuf> {
let dir = root.join(&model.dir);
let mut out: Vec<PathBuf> = SETTINGS_FILES.iter().map(|f| dir.join(f)).filter(|p| p.is_file()).collect();
out.extend(model.projects.iter().filter_map(|p| p.build_file.as_ref().map(|f| root.join(f))));
// Scripts a build script applies are build files too: editing one can change the model.
for project in &model.projects {
let Some(file) = project.build_file.as_deref() else { continue };
let build_dir = project_build_dir(root, model, project);
let properties = build_dir.join("gradle.properties");
if properties.is_file() {
out.push(properties);
}
let applied = scripts_of(root, &root.join(&project.dir), &build_dir, Path::new(file));
out.extend(applied.into_iter().skip(1).map(|(path, _)| path));
}
// The settings of each nested build (its root project's folder).
for p in model.projects.iter().filter(|p| p.build.as_deref() == Some(p.path.as_str())) {
let nested = root.join(&p.dir);
@@ -624,6 +969,8 @@ pub fn build_files(root: &Path, model: &GradleModel) -> Vec<PathBuf> {
catalogs.sort();
out.extend(catalogs);
}
out.sort();
out.dedup();
out
}
@@ -808,7 +1155,7 @@ dependencies {
classpath 'not:a:library'
}
"#;
let deps = script_dependencies(script);
let deps = script_dependencies(script, &BTreeMap::new());
let names: Vec<String> = deps.iter().map(|(g, a, v)| format!("{g}:{a}:{v}")).collect();
assert_eq!(
names,
@@ -822,6 +1169,291 @@ dependencies {
);
}
#[test]
fn applied_scripts_read_groovy_and_kotlin_forms() {
let script = r#"
apply plugin: 'java'
apply from: 'gradle/dependencies.gradle'
apply from: file('gradle/extra.gradle')
apply(from = "gradle/kotlin.gradle.kts")
apply(from = file("gradle/kotlin-file.gradle.kts"))
// apply from: 'commented.gradle'
reapply from: 'not-a-call.gradle'
"#;
assert_eq!(
applied_scripts(script),
[
"gradle/dependencies.gradle",
"gradle/extra.gradle",
"gradle/kotlin.gradle.kts",
"gradle/kotlin-file.gradle.kts"
]
);
}
#[test]
fn ext_values_fill_in_dependency_versions() {
let script = r#"
ext {
gsonVersion = '2.8.9'
junit = "4.13.2"
}
ext.logback = '1.4.14'
dependencies {
implementation "com.google.code.gson:gson:${gsonVersion}"
testImplementation "junit:junit:$junit"
implementation "ch.qos.logback:logback-classic:${ext.logback}"
implementation 'org.plain:literal:1.0'
implementation "org.x:unknown:${missing}"
}
"#;
let names: Vec<String> = script_dependencies(script, &script_properties(script))
.into_iter()
.map(|(g, a, v)| format!("{g}:{a}:{v}"))
.collect();
assert_eq!(
names,
[
"com.google.code.gson:gson:2.8.9",
"junit:junit:4.13.2",
"ch.qos.logback:logback-classic:1.4.14",
"org.plain:literal:1.0",
]
);
}
#[test]
fn extra_properties_support_brackets_and_kotlin_delegates() {
for declaration in [
"ext.x = '1.2'",
"ext { x = '1.2' }",
"ext[\"x\"] = '1.2'",
"extra[\"x\"] = \"1.2\"",
"val x by extra(\"1.2\")",
] {
let script = format!("{declaration}\ndependencies {{ implementation \"g:a:${{x}}\" }}");
assert_eq!(
script_dependencies(&script, &script_properties(&script)),
[("g".into(), "a".into(), "1.2".into())],
"{declaration}"
);
}
}
#[test]
fn parsers_ignore_apply_and_ext_inside_strings() {
let script = r#"
println "apply from: 'fake.gradle'"
println "ext.x = 'bogus'"
ext.real = '1'
"#;
assert!(applied_scripts(script).is_empty());
assert_eq!(script_properties(script), BTreeMap::from([("real".into(), "1".into())]));
}
#[test]
fn dependency_statements_preserve_interpolation_and_escaped_quotes() {
let script = r#"dependencies { implementation "g:a:${v}"; api(group = "g", name = "b", version = "${v}-RC1") }; dependencies { runtimeOnly 'g:c:2' }"#;
let properties = BTreeMap::from([("v".into(), "1.2".into())]);
assert_eq!(
script_dependencies(script, &properties),
[
("g".into(), "a".into(), "1.2".into()),
("g".into(), "b".into(), "1.2-RC1".into()),
("g".into(), "c".into(), "2".into())
]
);
assert_eq!(
statements(r#"println "escaped\"; {still quoted}"; implementation 'g:a:1'"#),
[r#"println "escaped\"; {still quoted}""#, " implementation 'g:a:1'"]
);
}
#[test]
fn dependency_versions_skip_unresolved_names_and_expressions() {
let script = r#"dependencies {
implementation "g:missing:${unknown}"
implementation "g:expression:${1 + 2}"
implementation "g:cyclic:${cycle}"
implementation 'g:range:[1,2)'
implementation 'g:dynamic:1.+'
}"#;
let properties = BTreeMap::from([("cycle".into(), "${cycle}".into())]);
assert!(script_dependencies(script, &properties).is_empty());
}
#[test]
fn extra_property_references_support_qualified_and_bracket_access() {
let script = r#"dependencies {
implementation "g:a:${ext.x}"
implementation "g:b:${extra.x}"
implementation "g:c:${ext['x']}"
implementation "g:d:${extra["x"]}"
}"#;
let properties = BTreeMap::from([("x".into(), "1".into())]);
assert_eq!(script_dependencies(script, &properties).len(), 4);
}
#[test]
fn applied_scripts_are_read_recursively_and_survive_cycles() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("gradle")).unwrap();
std::fs::write(root.join("build.gradle"), "apply from: 'gradle/deps.gradle'\n").unwrap();
std::fs::write(root.join("gradle/deps.gradle"), "apply from: '$rootDir/gradle/more.gradle'\n").unwrap();
std::fs::write(root.join("gradle/more.gradle"), "apply from: 'deps.gradle'\n").unwrap();
let scripts: Vec<String> = scripts_of(root, root, root, Path::new("build.gradle"))
.into_iter()
.map(|(path, _)| path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"))
.collect();
assert_eq!(scripts, ["build.gradle", "gradle/deps.gradle", "gradle/more.gradle"]);
assert_eq!(build_files(root, &load(root).unwrap()).len(), 3);
}
#[test]
fn applied_paths_prefer_the_project_directory() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("gradle")).unwrap();
std::fs::write(root.join("build.gradle"), "apply from: 'gradle/deps.gradle'").unwrap();
std::fs::write(root.join("gradle/deps.gradle"), "apply from: 'versions.gradle'").unwrap();
std::fs::write(root.join("versions.gradle"), "right").unwrap();
std::fs::write(root.join("gradle/versions.gradle"), "wrong").unwrap();
let scripts = scripts_of(root, root, root, Path::new("build.gradle"));
assert_eq!(scripts.len(), 3);
assert_eq!(scripts[2].1, "right");
}
#[test]
fn nested_applied_paths_are_relative_to_the_project_directory() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("gradle")).unwrap();
std::fs::write(root.join("build.gradle"), "apply from: 'gradle/a.gradle'").unwrap();
std::fs::write(root.join("gradle/a.gradle"), "apply from: 'gradle/b.gradle'").unwrap();
std::fs::write(root.join("gradle/b.gradle"), "").unwrap();
let scripts = scripts_of(root, root, root, Path::new("build.gradle"));
assert_eq!(scripts.len(), 3);
assert_eq!(scripts[2].0, root.join("gradle/b.gradle"));
}
#[test]
fn applied_paths_fall_back_to_the_applying_script_directory() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("gradle")).unwrap();
std::fs::write(root.join("build.gradle"), "apply from: 'gradle/a.gradle'").unwrap();
std::fs::write(root.join("gradle/a.gradle"), "apply from: 'c.gradle'").unwrap();
std::fs::write(root.join("gradle/c.gradle"), "").unwrap();
let scripts = scripts_of(root, root, root, Path::new("build.gradle"));
assert_eq!(scripts.len(), 3);
assert_eq!(scripts[2].0, root.join("gradle/c.gradle"));
}
#[test]
fn applied_paths_resolve_gradle_directory_variables() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let project = root.join("app");
let script = project.join("gradle/deps.gradle");
std::fs::create_dir_all(script.parent().unwrap()).unwrap();
std::fs::write(root.join("shared.gradle"), "").unwrap();
std::fs::write(project.join("local.gradle"), "").unwrap();
for prefix in ["$rootDir", "${rootDir}", "$rootProject.projectDir", "${rootProject.projectDir}"] {
assert_eq!(
resolve_script(&format!("{prefix}/shared.gradle"), &script, &project, root),
Some(root.join("shared.gradle")),
"{prefix}"
);
}
for prefix in ["$projectDir", "${projectDir}"] {
assert_eq!(
resolve_script(&format!("{prefix}/local.gradle"), &script, &project, root),
Some(project.join("local.gradle")),
"{prefix}"
);
}
assert_eq!(
resolve_script(root.join("shared.gradle").to_str().unwrap(), &script, &project, root),
Some(root.join("shared.gradle"))
);
}
#[test]
fn applied_scripts_skip_urls_and_missing_files() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
// Even a local path resembling a URL must not be read.
if !cfg!(windows) {
for scheme in ["http", "https"] {
let local = root.join(format!("{scheme}:/example.com/deps.gradle"));
std::fs::create_dir_all(local.parent().unwrap()).unwrap();
std::fs::write(local, "implementation 'g:remote:1'").unwrap();
}
}
std::fs::write(root.join("build.gradle"), "apply from: 'http://example.com/deps.gradle'\napply(from = \"https://example.com/deps.gradle\")\napply from: 'missing.gradle'").unwrap();
assert_eq!(scripts_of(root, root, root, Path::new("build.gradle")).len(), 1);
}
#[test]
fn applied_scripts_deduplicate_self_application_and_path_aliases() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("gradle")).unwrap();
std::fs::write(
root.join("build.gradle"),
"apply from: 'build.gradle'\napply from: 'gradle/../build.gradle'\napply from: 'gradle/a.gradle'",
)
.unwrap();
std::fs::write(root.join("gradle/a.gradle"), "apply from: '../build.gradle'").unwrap();
assert_eq!(scripts_of(root, root, root, Path::new("build.gradle")).len(), 2);
}
#[cfg(unix)]
#[test]
fn applied_scripts_deduplicate_symlink_cycles() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join("build.gradle"), "apply from: 'alias/build.gradle'").unwrap();
std::os::unix::fs::symlink(root, root.join("alias")).unwrap();
assert_eq!(scripts_of(root, root, root, Path::new("build.gradle")).len(), 1);
}
#[test]
fn applied_script_traversal_bounds_depth_and_total_files() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for i in 0..300 {
std::fs::write(root.join(format!("{i}.gradle")), format!("apply from: '{}.gradle'", i + 1)).unwrap();
}
let chain = scripts_of(root, root, root, Path::new("0.gradle"));
assert_eq!(chain.len(), 33);
let fanout: String = (0..300).map(|i| format!("apply from: '{i}.gradle'\n")).collect();
std::fs::write(root.join("build.gradle"), fanout).unwrap();
assert_eq!(scripts_of(root, root, root, Path::new("build.gradle")).len(), 256);
}
#[test]
fn applied_scripts_use_their_composite_build_root() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("included/app")).unwrap();
std::fs::write(root.join("build.gradle"), "").unwrap();
std::fs::write(root.join("included/build.gradle"), "").unwrap();
std::fs::write(root.join("included/app/build.gradle"), "apply from: \"${rootDir}/deps.gradle\"").unwrap();
std::fs::write(root.join("included/deps.gradle"), "implementation 'g:included:1'").unwrap();
let mut model = load(root).unwrap();
for (path, dir) in [(":included", "included"), (":included:app", "included/app")] {
let mut project = project_at(root, path.into(), path.into(), &root.join(dir));
project.build = Some(":included".into());
model.projects.push(project);
}
assert!(build_files(root, &model).contains(&root.join("included/deps.gradle")));
let model = crate::BuildModel { maven: None, gradle: vec![model] };
assert_eq!(crate::dependency_coordinates(root, &model)[0].artifact_id, "included");
}
use super::*;
#[test]
+57 -6
Переглянути файл
@@ -147,7 +147,8 @@ pub struct DependencyCoordinate {
/// The external libraries of `model`, sorted and deduplicated: Maven dependencies
/// (with the transitive ones the last sync read), except the build's own modules,
/// `pom` imports and `system` scope; dependencies declared in the Gradle build scripts.
/// `pom` imports and `system` scope; dependencies declared in the Gradle build scripts,
/// including the scripts they pull in with `apply from`.
pub fn dependency_coordinates(root: &Path, model: &BuildModel) -> Vec<DependencyCoordinate> {
let mut out = Vec::new();
if let Some(m) = &model.maven {
@@ -177,11 +178,26 @@ pub fn dependency_coordinates(root: &Path, model: &BuildModel) -> Vec<Dependency
}
}
for g in &model.gradle {
for script in g.projects.iter().filter_map(|p| p.build_file.as_ref()) {
let Ok(text) = std::fs::read_to_string(root.join(script)) else { continue };
out.extend(gradle::script_dependencies(&text).into_iter().map(|(group_id, artifact_id, version)| {
DependencyCoordinate { gradle: true, group_id, artifact_id, version }
}));
for p in &g.projects {
let Some(build_file) = p.build_file.as_deref() else { continue };
let build_dir = gradle::project_build_dir(root, g, p);
let scripts = gradle::scripts_of(root, &root.join(&p.dir), &build_dir, Path::new(build_file));
// The script's own `ext` values win over the scripts it applies.
let mut properties = std::collections::BTreeMap::new();
for (_, text) in scripts.iter().rev() {
properties.extend(gradle::script_properties(text));
}
properties.extend(gradle::file_properties(&build_dir));
for (_, text) in &scripts {
out.extend(gradle::script_dependencies(text, &properties).into_iter().map(
|(group_id, artifact_id, version)| DependencyCoordinate {
gradle: true,
group_id,
artifact_id,
version,
},
));
}
}
}
out.sort();
@@ -312,4 +328,39 @@ mod tests {
.collect();
assert_eq!(names, ["M org.b:y:2", "M org.c:z:3", "G org.a:x:1.0"]);
}
#[test]
fn dependency_coordinates_read_scripts_brought_in_by_apply_from() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("gradle")).unwrap();
std::fs::write(root.join("build.gradle"), "apply from: 'gradle/dependencies.gradle'\n").unwrap();
std::fs::write(
root.join("gradle/dependencies.gradle"),
"ext { gson = '2.8.9' }\ndependencies { implementation \"com.google.code.gson:gson:${gson}\" }\n",
)
.unwrap();
let model = BuildModel { maven: None, gradle: gradle::load(root).into_iter().collect() };
let names: Vec<String> = dependency_coordinates(root, &model)
.into_iter()
.map(|c| format!("{}:{}:{}", c.group_id, c.artifact_id, c.version))
.collect();
assert_eq!(names, ["com.google.code.gson:gson:2.8.9"]);
}
#[test]
fn gradle_properties_override_script_extra_values() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join("build.gradle"), "ext.v = 'wrong'\napply from: 'deps.gradle'").unwrap();
std::fs::write(
root.join("deps.gradle"),
"ext.v = 'alsoWrong'\nimplementation \"g:a:${v}\"\nimplementation \"g:b:${onlyInProperties}\"",
)
.unwrap();
std::fs::write(root.join("gradle.properties"), "# versions\nv = 1.2\nonlyInProperties: 2.3\n").unwrap();
let model = BuildModel { maven: None, gradle: gradle::load(root).into_iter().collect() };
let versions: Vec<_> = dependency_coordinates(root, &model).into_iter().map(|c| c.version).collect();
assert_eq!(versions, ["1.2", "2.3"]);
}
}
+34
Переглянути файл
@@ -818,6 +818,40 @@ mod tests {
assert!(m.stale, "gradle.properties is watched");
}
#[test]
fn applied_script_edits_invalidate_the_cached_gradle_model() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let cache_dir = tmp.path().join("cache");
std::fs::create_dir_all(root.join("gradle")).unwrap();
std::fs::write(root.join("build.gradle"), "apply from: 'gradle/dependencies.gradle'").unwrap();
let applied = root.join("gradle/dependencies.gradle");
std::fs::write(&applied, "implementation 'g:a:1'").unwrap();
let model = gradle::load(&root).unwrap();
let cache = GradleCache {
hash: hash_gradle_files(&gradle::build_files(&root, &model)),
projects: vec![ReportedProject {
path: ":".into(),
dir: root.to_string_lossy().into_owned(),
..Default::default()
}],
..Default::default()
};
write_cache(&cache_dir, GRADLE_CACHE, &cache).unwrap();
let stale = || {
let mut model = gradle::load(&root).unwrap();
apply_gradle_cache(&root, &cache_dir, &mut model);
model.stale
};
assert!(!stale());
std::fs::write(&applied, "// comment\nimplementation 'g:a:1'\n").unwrap();
assert!(!stale());
std::fs::write(&applied, "implementation 'g:a:2'").unwrap();
assert!(stale());
std::fs::remove_file(&applied).unwrap();
assert!(stale());
}
#[test]
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline() {
let online = maven_sync_goals(Path::new("e.xml"), false);
+26
Переглянути файл
@@ -253,6 +253,32 @@ pub fn inspect(ep: &DockerEndpoint, object: DockerObject, id: &str) -> IdeResult
}
}
fn check_id(id: &str) -> IdeResult<&str> {
let id = id.trim();
if id.is_empty() || id.starts_with('-') { Err(IdeError::invalid("invalid Docker identifier")) } else { Ok(id) }
}
/// `docker image history --no-trunc --format '{{json .}}'` of one image.
pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImageLayer>> {
let id = check_id(id)?;
let out = run(ep, &["image", "history", "--no-trunc", "--format", "{{json .}}", id], QUICK)?;
Ok(parse_image_history(&out))
}
/// `docker top <id>` of a running container.
pub fn container_top(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerProcessList> {
let id = check_id(id)?;
let out = run(ep, &["top", id], QUICK)?;
Ok(parse_container_top(&out))
}
/// `docker stats --no-stream --no-trunc --format '{{json .}}' <id>` of a running container.
pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContainerStats> {
let id = check_id(id)?;
let out = run(ep, &["stats", "--no-stream", "--no-trunc", "--format", "{{json .}}", id], QUICK)?;
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
}
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
/// until it ends or `cancel` fires.
pub fn logs(
+181 -19
Переглянути файл
@@ -41,6 +41,15 @@ pub struct DockerContainer {
pub compose_working_dir: Option<String>,
/// `com.docker.compose.project.config_files` label (comma-separated in docker).
pub compose_files: Vec<String>,
/// Mounted volume names or host paths reported by `docker ps` (`Mounts`).
#[serde(default)]
pub mounts: Vec<String>,
/// Connected network names reported by `docker ps` (`Networks`).
#[serde(default)]
pub networks: Vec<String>,
/// User and tool labels assigned to the container.
#[serde(default)]
pub labels: BTreeMap<String, String>,
}
impl DockerContainer {
@@ -80,6 +89,10 @@ pub struct DockerVolume {
pub driver: String,
pub mountpoint: String,
pub compose_project: Option<String>,
#[serde(default)]
pub scope: String,
#[serde(default)]
pub labels: BTreeMap<String, String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -90,6 +103,46 @@ pub struct DockerNetwork {
pub driver: String,
pub scope: String,
pub compose_project: Option<String>,
#[serde(default)]
pub created_at: String,
#[serde(default)]
pub ipv6: bool,
#[serde(default)]
pub internal: bool,
#[serde(default)]
pub labels: BTreeMap<String, String>,
}
/// One layer in `docker image history --no-trunc --format '{{json .}}'`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerImageLayer {
pub id: String,
pub created_by: String,
pub size: String,
pub created_since: String,
pub created_at: String,
pub comment: String,
}
/// Process table returned by `docker top <container>`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerProcessList {
pub titles: Vec<String>,
pub processes: Vec<Vec<String>>,
}
/// Live resource metrics returned by `docker stats --no-stream --no-trunc --format '{{json .}}'`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerContainerStats {
pub cpu_perc: String,
pub mem_usage: String,
pub mem_perc: String,
pub net_io: String,
pub block_io: String,
pub pids: String,
}
/// Everything the Services tree shows, fetched in one go.
@@ -186,17 +239,20 @@ struct RawContainer {
ports: String,
created_at: String,
labels: String,
mounts: String,
networks: String,
}
fn split_csv(raw: &str) -> Vec<String> {
raw.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
}
/// `docker ps -a --no-trunc --format '{{json .}}'`.
pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
let mut out: Vec<DockerContainer> = lines::<RawContainer>(text)
.map(|r| {
let mut labels = parse_labels(&r.labels);
let files = labels
.remove(COMPOSE_FILES)
.map(|f| f.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect())
.unwrap_or_default();
let all_labels = parse_labels(&r.labels);
let files = all_labels.get(COMPOSE_FILES).map(|f| split_csv(f)).unwrap_or_default();
// Older docker versions derive `State` from nothing: fall back on the status text.
let state = if r.state.is_empty() {
if r.status.starts_with("Up") { "running".into() } else { "exited".into() }
@@ -212,10 +268,13 @@ pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
status: r.status,
ports: r.ports,
created_at: r.created_at,
compose_project: labels.remove(COMPOSE_PROJECT).filter(|s| !s.is_empty()),
compose_service: labels.remove(COMPOSE_SERVICE).filter(|s| !s.is_empty()),
compose_working_dir: labels.remove(COMPOSE_DIR).filter(|s| !s.is_empty()),
compose_project: all_labels.get(COMPOSE_PROJECT).filter(|s| !s.is_empty()).cloned(),
compose_service: all_labels.get(COMPOSE_SERVICE).filter(|s| !s.is_empty()).cloned(),
compose_working_dir: all_labels.get(COMPOSE_DIR).filter(|s| !s.is_empty()).cloned(),
compose_files: files,
mounts: split_csv(&r.mounts),
networks: split_csv(&r.networks),
labels: all_labels,
}
})
.collect();
@@ -258,17 +317,23 @@ struct RawVolume {
name: String,
driver: String,
mountpoint: String,
scope: String,
labels: String,
}
/// `docker volume ls --format '{{json .}}'`.
pub fn parse_volumes(text: &str) -> Vec<DockerVolume> {
let mut out: Vec<DockerVolume> = lines::<RawVolume>(text)
.map(|r| DockerVolume {
compose_project: parse_labels(&r.labels).remove(COMPOSE_PROJECT).filter(|s| !s.is_empty()),
name: r.name,
driver: r.driver,
mountpoint: r.mountpoint,
.map(|r| {
let labels = parse_labels(&r.labels);
DockerVolume {
compose_project: labels.get(COMPOSE_PROJECT).filter(|s| !s.is_empty()).cloned(),
name: r.name,
driver: r.driver,
mountpoint: r.mountpoint,
scope: r.scope,
labels,
}
})
.collect();
out.sort_by(|a, b| a.name.cmp(&b.name));
@@ -283,24 +348,121 @@ struct RawNetwork {
name: String,
driver: String,
scope: String,
created_at: String,
#[serde(rename = "IPv6")]
ipv6: String,
internal: String,
labels: String,
}
/// `docker network ls --no-trunc --format '{{json .}}'`.
pub fn parse_networks(text: &str) -> Vec<DockerNetwork> {
let mut out: Vec<DockerNetwork> = lines::<RawNetwork>(text)
.map(|r| DockerNetwork {
compose_project: parse_labels(&r.labels).remove(COMPOSE_PROJECT).filter(|s| !s.is_empty()),
id: r.id,
name: r.name,
driver: r.driver,
scope: r.scope,
.map(|r| {
let labels = parse_labels(&r.labels);
DockerNetwork {
compose_project: labels.get(COMPOSE_PROJECT).filter(|s| !s.is_empty()).cloned(),
id: r.id,
name: r.name,
driver: r.driver,
scope: r.scope,
created_at: r.created_at,
ipv6: r.ipv6.eq_ignore_ascii_case("true"),
internal: r.internal.eq_ignore_ascii_case("true"),
labels,
}
})
.collect();
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawImageLayer {
#[serde(rename = "ID")]
id: String,
created_by: String,
size: String,
created_since: String,
created_at: String,
comment: String,
}
/// `docker image history --no-trunc --format '{{json .}}'`.
pub fn parse_image_history(text: &str) -> Vec<DockerImageLayer> {
lines::<RawImageLayer>(text)
.map(|r| DockerImageLayer {
id: r.id,
created_by: r.created_by,
size: r.size,
created_since: r.created_since,
created_at: r.created_at,
comment: r.comment,
})
.collect()
}
/// `docker top <container>` tabular output.
pub fn parse_container_top(text: &str) -> DockerProcessList {
let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
let Some(header) = lines.next() else {
return DockerProcessList::default();
};
let titles: Vec<String> = header.split_whitespace().map(str::to_owned).collect();
if titles.is_empty() {
return DockerProcessList::default();
}
let cols = titles.len();
let processes = lines
.map(|line| {
let mut row = Vec::with_capacity(cols);
let mut rest = line.trim_start();
for _ in 0..cols.saturating_sub(1) {
match rest.split_once(char::is_whitespace) {
Some((field, tail)) => {
row.push(field.to_owned());
rest = tail.trim_start();
}
None => break,
}
}
if !rest.is_empty() || row.len() < cols {
row.push(rest.to_owned());
}
row
})
.collect();
DockerProcessList { titles, processes }
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawStats {
#[serde(rename = "CPUPerc")]
cpu_perc: String,
mem_usage: String,
mem_perc: String,
#[serde(rename = "NetIO")]
net_io: String,
#[serde(rename = "BlockIO")]
block_io: String,
#[serde(rename = "PIDs")]
pids: String,
}
/// `docker stats --no-stream --no-trunc --format '{{json .}}'`.
pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
lines::<RawStats>(text).next().map(|r| DockerContainerStats {
cpu_perc: r.cpu_perc,
mem_usage: r.mem_usage,
mem_perc: r.mem_perc,
net_io: r.net_io,
block_io: r.block_io,
pids: r.pids,
})
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct RawVersion {
+44 -1
Переглянути файл
@@ -1,6 +1,9 @@
//! Parsing of recorded `docker … --format '{{json .}}'` output.
use ide_docker::{parse_containers, parse_images, parse_networks, parse_volumes};
use ide_docker::{
parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images, parse_networks,
parse_volumes,
};
const PS: &str = include_str!("fixtures/ps.jsonl");
const IMAGES: &str = include_str!("fixtures/images.jsonl");
@@ -22,11 +25,16 @@ fn containers_with_compose_labels() {
assert_eq!(db.compose_working_dir.as_deref(), Some("/work/shop"));
assert_eq!(db.compose_files, ["/work/shop/compose.yaml", "/work/shop/compose.override.yaml"]);
assert_eq!(db.ports, "0.0.0.0:5432->5432/tcp");
assert_eq!(db.mounts, ["shop_pgdata"]);
assert_eq!(db.networks, ["shop_default"]);
assert_eq!(db.labels.get("com.docker.compose.project").map(String::as_str), Some("shop"));
let web = &c[1];
assert_eq!(web.name, "web", "leading slash of legacy names is dropped");
assert!(!web.running());
assert_eq!(web.compose_project, None);
assert!(web.mounts.is_empty());
assert_eq!(web.networks, ["bridge"]);
}
#[test]
@@ -44,9 +52,44 @@ fn volumes_and_networks() {
assert_eq!(v.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["0a1b", "shop_pgdata"]);
assert_eq!(v[1].compose_project.as_deref(), Some("shop"));
assert_eq!(v[1].mountpoint, "/var/lib/docker/volumes/shop_pgdata/_data");
assert_eq!(v[1].scope, "local");
assert_eq!(v[1].labels.get("com.docker.compose.volume").map(String::as_str), Some("pgdata"));
let n = parse_networks(NETWORKS);
assert_eq!(n.iter().map(|n| n.name.as_str()).collect::<Vec<_>>(), ["bridge", "host", "shop_default"]);
assert_eq!(n[2].compose_project.as_deref(), Some("shop"));
assert_eq!(n[1].driver, "host");
assert!(!n[2].ipv6);
assert!(!n[2].internal);
assert_eq!(n[2].labels.get("com.docker.compose.network").map(String::as_str), Some("default"));
}
#[test]
fn image_history_top_and_stats() {
let history = [
r#"{"Comment":"buildkit.dockerfile.v0","CreatedAt":"2026-10-01 09:00:00 +0000 UTC","CreatedBy":"CMD [\"postgres\"]","CreatedSince":"5 weeks ago","ID":"sha256:1234567890ab","Size":"0B"}"#,
r#"{"Comment":"","CreatedAt":"2026-10-01 08:59:00 +0000 UTC","CreatedBy":"/bin/sh -c #(nop) COPY file:abc in /usr/local/bin/ ","CreatedSince":"5 weeks ago","ID":"<missing>","Size":"42.5MB"}"#,
]
.join("\n");
let layers = parse_image_history(&history);
assert_eq!(layers.len(), 2);
assert_eq!(layers[0].created_by, "CMD [\"postgres\"]");
assert_eq!(layers[1].size, "42.5MB");
let top = "UID PID PPID C STIME TTY TIME CMD\nroot 1234 1200 0 09:12 ? 00:00:01 postgres -c config_file=/etc/postgresql.conf\n";
let parsed_top = parse_container_top(top);
assert_eq!(parsed_top.titles, ["UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"]);
assert_eq!(parsed_top.processes.len(), 1);
assert_eq!(parsed_top.processes[0][0], "root");
assert_eq!(parsed_top.processes[0][1], "1234");
assert_eq!(parsed_top.processes[0][7], "postgres -c config_file=/etc/postgresql.conf");
let stats_line = r#"{"BlockIO":"1.2MB / 0B","CPUPerc":"1.25%","Container":"shop-db-1","ID":"4f2b8c1d9e0a","MemPerc":"2.50%","MemUsage":"50MiB / 2GiB","Name":"shop-db-1","NetIO":"12kB / 8kB","PIDs":"14"}"#;
let stats = parse_container_stats(stats_line).expect("stats parsed");
assert_eq!(stats.cpu_perc, "1.25%");
assert_eq!(stats.mem_usage, "50MiB / 2GiB");
assert_eq!(stats.mem_perc, "2.50%");
assert_eq!(stats.net_io, "12kB / 8kB");
assert_eq!(stats.block_io, "1.2MB / 0B");
assert_eq!(stats.pids, "14");
}
+2 -2
Переглянути файл
@@ -592,8 +592,8 @@ pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::
/// References of the symbol at `pos`. `project_wide` also searches project files
/// outside the language server's analysis scope; bulk scans over many symbols
/// leave it off. Java, `project_wide`: without `libraries`, the dependencies and the JDK
/// are not searched; with it, those found in the sources arrive on `on_partial` before
/// leave it off. Java: without `libraries`, the dependencies and the JDK are not
/// searched; with it and `project_wide`, those found in the sources arrive on `on_partial` before
/// the slower search for the rest, and the result has them all. Cancel with
/// `cancel_request(request)`.
#[allow(clippy::too_many_arguments)]
+7 -6
Переглянути файл
@@ -218,12 +218,13 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
.filter(|s| !s.is_empty())
.or_else(|| artifacts.first().map(|a| &a.id))
.ok_or_else(|| IdeError::invalid("Choose a WAR artifact"))?;
let mut plan = ide_build::web::build(
&project.root,
&model,
id,
&ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?,
)?;
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
// "Build before launch" is skipped when the built WAR is already newer than the
// module's sources, so a repeated run does not rebuild (IDEA's up-to-date check).
if ide_run::tomcat::artifact_is_current(&project.root, &base, &config) {
return Ok(None);
}
let mut plan = ide_build::web::build(&project.root, &model, id, &base)?;
plan.env.extend(config.env.clone());
let mut build = RunConfig {
id: format!("tomcat-build:{}", config.id),
+7 -6
Переглянути файл
@@ -1069,12 +1069,13 @@ impl Project {
let Some(root) = root else {
return ide_lsp::CandidateFiles::default();
};
let query = ide_search::WordQuery {
word: q.word.clone(),
dir: q.root.clone(),
exclude: self.search_excludes(),
limit: q.limit,
};
let mut exclude = self.search_excludes();
// Directories the server analyses fully: their files are never read.
exclude.extend(q.skip.iter().filter_map(|dir| {
let rel = dir.strip_prefix(&root).ok()?.to_str()?.replace('\\', "/");
(!rel.is_empty() && !rel.contains(['*', '?', '[', ']', '{', '}', '!', ','])).then(|| format!("{rel}/**"))
}));
let query = ide_search::WordQuery { word: q.word.clone(), dir: q.root.clone(), exclude, limit: q.limit };
let filter = |rel: &str| q.languages.contains(&self.languages.detect(&root.join(rel), None));
match ide_search::files_with_word(&root, &query, Some(&filter), &|p| self.documents.search_text_of(p), cancel) {
Ok(found) => ide_lsp::CandidateFiles { files: found.files, limit_hit: found.limit_hit },
+26
Переглянути файл
@@ -468,6 +468,25 @@ impl ServerCaps {
self.restriction = restriction;
return;
}
// JDT LS registers the commands of bundles that were not loaded when it initialized.
if method == "workspace/executeCommand"
&& let Some(added) = options.and_then(|o| o.get("commands")).and_then(Value::as_array)
{
if !self.raw.get("executeCommandProvider").is_some_and(Value::is_object) {
self.raw["executeCommandProvider"] = json!({ "commands": [] });
}
let provider = &mut self.raw["executeCommandProvider"];
if !provider.get("commands").is_some_and(Value::is_array) {
provider["commands"] = json!([]);
}
let commands = provider["commands"].as_array_mut().expect("commands");
for command in added {
if !commands.contains(command) {
commands.push(command.clone());
}
}
return;
}
if method == "textDocument/didSave" {
let include = options.and_then(|o| o.get("includeText")).and_then(Value::as_bool).unwrap_or(false);
self.save = Some(include);
@@ -566,6 +585,13 @@ mod tests {
assert!(c.file_operation("willRename").is_some());
c.unregister("workspace/willRenameFiles");
assert!(c.file_operation("willRename").is_none());
// Commands registered later join those announced at initialization.
let mut c = ServerCaps::parse(json!({ "executeCommandProvider": { "commands": ["a"] } }));
c.register("workspace/executeCommand", Some(&json!({ "commands": ["b", "a"] })));
assert_eq!(c.commands(), vec!["a", "b"]);
let mut c = ServerCaps::parse(json!({}));
c.register("workspace/executeCommand", Some(&json!({ "commands": ["b"] })));
assert_eq!(c.commands(), vec!["b"]);
}
fn restriction(features: &[&str], kinds: &[&str]) -> Restriction {
+6 -3
Переглянути файл
@@ -1462,8 +1462,8 @@ impl LspManager {
self.references_streaming(doc, pos, include_declaration, project_wide, true, cancel, None).await
}
/// [`Self::references`]. Java, `project_wide`: without `libraries`, only the
/// workspace's sources are searched (`libraries_skipped`); with it, those found
/// [`Self::references`]. Java: without `libraries`, only the workspace's sources
/// are searched (`libraries_skipped`); with it and `project_wide`, those found
/// there arrive on `partial` before the dependencies and the JDK are searched.
#[allow(clippy::too_many_arguments)]
pub async fn references_streaming(
@@ -1630,7 +1630,10 @@ impl LspManager {
};
scope::Widened { first: all, second: Some(found), incomplete: sources.incomplete }
} else {
let first = query(false).await?;
// Scoped probes (usage counts, bulk scans) run for many symbols at once:
// without `libraries`, the dependencies and the JDK are not searched.
libraries_skipped = !libraries;
let first = query(!libraries).await?;
let empty = first.is_empty();
scope::Widened::only(first, empty, &t.server)
};
+51 -14
Переглянути файл
@@ -25,12 +25,17 @@ use std::time::Duration;
/// Files opened for one search at most.
pub const MAX_CANDIDATES: usize = 300;
/// Candidates checked against a server's analysis scope ([`COVERED_FILES`]) at most: most
/// are usually covered, so a common name only exceeds [`MAX_CANDIDATES`] after that check.
const MAX_SCOPE_CANDIDATES: usize = 5000;
/// Larger files (generated code, bundles) are not opened.
const MAX_CANDIDATE_BYTES: u64 = 1 << 20;
/// How long a search that found nothing waits for a server to finish indexing.
const INDEX_WAIT: Duration = Duration::from_secs(10);
/// Optional server command: candidate URIs in, already analysed candidate URIs out.
const COVERED_FILES: &str = "openidea.workspace.coveredFiles";
/// Optional server command: directories whose files of its languages it all analyses.
const COVERED_ROOTS: &str = "openidea.workspace.coveredRoots";
/// Project files that may mention a symbol.
#[derive(Clone, Debug)]
@@ -42,6 +47,8 @@ pub struct CandidateQuery {
/// Only files of these languages.
pub languages: Vec<LanguageId>,
pub limit: usize,
/// Directories not to look in: the server already analyses every file there.
pub skip: Vec<PathBuf>,
}
#[derive(Clone, Debug, Default)]
@@ -92,14 +99,16 @@ impl LspManager {
*self.candidates_hook.write() = Some(Arc::from(hook));
}
async fn candidates(&self, t: &Target, word: String, cancel: &CancellationToken) -> Option<CandidateFiles> {
async fn candidates(
&self,
t: &Target,
word: String,
limit: usize,
skip: Vec<PathBuf>,
cancel: &CancellationToken,
) -> Option<CandidateFiles> {
let hook = self.candidates_hook.read().clone()?;
let query = CandidateQuery {
word,
root: t.server.root.clone(),
languages: t.server.languages(),
limit: MAX_CANDIDATES,
};
let query = CandidateQuery { word, root: t.server.root.clone(), languages: t.server.languages(), limit, skip };
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || hook(&query, &cancel)).await.ok()
}
@@ -125,11 +134,12 @@ impl LspManager {
// gopls searches the view of the file asked about; files opened for it only get views of
// their own (see `go_scope`).
let word = search_word(snap, pos).filter(|_| t.caps().open_close && snap.language.as_str() != "go");
let reports_scope = has_command(t, COVERED_FILES);
let limit = if reports_scope { MAX_SCOPE_CANDIDATES } else { MAX_CANDIDATES };
let candidates = async {
match word {
Some(w) => self.candidates(t, w, cancel).await,
None => None,
}
let w = word?;
let skip = if reports_scope { self.covered_roots(t, cancel).await } else { Vec::new() };
self.candidates(t, w, limit, skip, cancel).await
};
let (first, candidates) = futures::join!(query(), candidates);
let mut first = first?;
@@ -148,10 +158,14 @@ impl LspManager {
}
let known: HashSet<PathBuf> = covered(&first).into_iter().chain([snap.path.clone()]).collect();
let files: Vec<PathBuf> = candidates.files.into_iter().filter(|f| !known.contains(f)).collect();
let files = self.files_beyond_scope(t, files, cancel).await;
let mut files = self.files_beyond_scope(t, files, cancel).await;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if files.len() > MAX_CANDIDATES {
files.truncate(MAX_CANDIDATES);
incomplete = incomplete.or(Some(ReferencesIncomplete::TooManyFiles));
}
if files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
@@ -180,8 +194,25 @@ impl LspManager {
}
}
/// Directories whose files `t` analyses all ([`COVERED_ROOTS`]); none when it can't say.
async fn covered_roots(&self, t: &Target, cancel: &CancellationToken) -> Vec<PathBuf> {
if !has_command(t, COVERED_ROOTS) {
return Vec::new();
}
let params = json!({ "command": COVERED_ROOTS, "arguments": [] });
let roots: IdeResult<Vec<String>> =
self.call(t, "workspace/executeCommand", params, Some(cancel), crate::DEFAULT_TIMEOUT).await;
match roots {
Ok(roots) => roots.iter().filter_map(|uri| crate::uri::uri_to_path(uri)).collect(),
Err(e) => {
tracing::debug!("{}: covered roots unavailable: {}", t.server.name, e.message);
Vec::new()
}
}
}
async fn files_beyond_scope(&self, t: &Target, files: Vec<PathBuf>, cancel: &CancellationToken) -> Vec<PathBuf> {
if files.is_empty() || !t.caps().commands().iter().any(|c| c == COVERED_FILES) {
if files.is_empty() || !has_command(t, COVERED_FILES) {
return files;
}
let uris: Vec<String> = files.iter().map(|p| crate::uri::path_to_uri_string(p)).collect();
@@ -224,7 +255,9 @@ impl LspManager {
.filter(|l| l.uri.is_none())
.collect();
let Some(declaration) = declarations.first() else { return GoMentions::default() };
let Some(candidates) = self.candidates(t, word.clone(), cancel).await else { return GoMentions::default() };
let Some(candidates) = self.candidates(t, word.clone(), MAX_CANDIDATES, Vec::new(), cancel).await else {
return GoMentions::default();
};
let (origin, declared) = (snap.path.clone(), declaration.path.to_path_buf());
let files = tokio::task::spawn_blocking(move || {
crate::go_scope::files_beyond_search(&origin, &declared, candidates.files)
@@ -478,3 +511,7 @@ impl Drop for TransientFiles<'_> {
}
}
}
fn has_command(t: &Target, command: &str) -> bool {
t.caps().commands().iter().any(|c| c == command)
}
+70 -7
Переглянути файл
@@ -52,6 +52,7 @@ pub enum Phase {
struct State {
generation: u64,
conn: Conn,
restarting: bool,
events: VecDeque<IdeEvent>,
publishing: bool,
}
@@ -138,7 +139,13 @@ impl Server {
effective: Mutex::new(None),
resolved_binary: RwLock::new(None),
languages: Mutex::new(vec![language]),
state: Mutex::new(State { generation: 0, conn: Conn::Idle, events: VecDeque::new(), publishing: false }),
state: Mutex::new(State {
generation: 0,
conn: Conn::Idle,
restarting: false,
events: VecDeque::new(),
publishing: false,
}),
initializing: Mutex::new(None),
start_cancel: Mutex::new(CancellationToken::new()),
phase: watch::channel(Phase::Down).0,
@@ -214,6 +221,7 @@ impl Server {
}
st.generation += 1;
st.conn = Conn::Starting;
st.restarting = false;
*self.start_cancel.lock() = CancellationToken::new();
*self.started.lock() = Some(Instant::now());
self.phase.send_replace(Phase::Starting);
@@ -293,21 +301,43 @@ impl Server {
self.running().filter(|r| r.generation == generation)
}
/// Waits while the server is starting; returns the instance once ready.
/// Waits through startup or a planned restart; returns the instance once ready.
pub async fn wait_ready(&self, timeout: Duration) -> Option<Running> {
let mut rx = self.phase.subscribe();
let _ = tokio::time::timeout(timeout, rx.wait_for(|p| *p != Phase::Starting)).await;
self.running()
tokio::time::timeout(timeout, async {
loop {
{
let st = self.state.lock();
// Read both under the writer's lock: a restart can begin just after a wakeup.
if *rx.borrow_and_update() != Phase::Starting {
return match &st.conn {
Conn::Ready(run) => Some(run.clone()),
_ => None,
};
}
}
if rx.changed().await.is_err() {
return None;
}
}
})
.await
.ok()
.flatten()
}
/// Ready → Stopping, returning the instance to shut down. An in-flight
/// start is abandoned instead.
pub fn begin_stop(&self, sink: &SharedSink, final_stop: bool) -> Option<Running> {
let mut st = self.state.lock();
if final_stop {
st.restarting = false;
}
match std::mem::replace(&mut st.conn, Conn::Idle) {
Conn::Ready(run) => {
st.conn = Conn::Stopping;
self.phase.send_replace(Phase::Down);
st.restarting = !final_stop;
self.phase.send_replace(if st.restarting { Phase::Starting } else { Phase::Down });
Some(run)
}
Conn::Starting => {
@@ -315,7 +345,8 @@ impl Server {
self.start_cancel.lock().cancel();
self.queue_cleanup(&mut st);
self.queue_status(&mut st, ServerStatus::Stopped, None);
self.phase.send_replace(Phase::Down);
st.restarting = !final_stop;
self.phase.send_replace(if st.restarting { Phase::Starting } else { Phase::Down });
drop(st);
self.publish(sink);
None
@@ -324,6 +355,7 @@ impl Server {
st.conn = other;
if final_stop {
self.queue_status(&mut st, ServerStatus::Stopped, None);
self.phase.send_replace(Phase::Down);
}
drop(st);
self.publish(sink);
@@ -345,7 +377,7 @@ impl Server {
self.queue_cleanup(&mut st);
self.queue_status(&mut st, ServerStatus::Stopped, None);
st.conn = Conn::Idle;
self.phase.send_replace(Phase::Down);
self.phase.send_replace(if st.restarting { Phase::Starting } else { Phase::Down });
drop(st);
self.publish(sink);
}
@@ -899,6 +931,37 @@ mod tests {
assert_eq!(s.status(), ServerStatus::Stopped);
}
#[tokio::test]
async fn final_stop_cancels_pending_restarts_in_every_phase() {
for phase in ["starting", "stopping", "between"] {
let s = server();
let sink: SharedSink = Arc::new(|_: IdeEvent| {});
let generation = s.begin_start().unwrap();
if phase == "starting" {
s.begin_stop(&sink, false);
} else {
let mut st = s.state.lock();
st.conn = Conn::Stopping;
st.restarting = true;
}
if phase == "between" {
s.end_stop(generation, &sink);
}
assert!(
tokio::time::timeout(Duration::from_millis(10), s.wait_ready(Duration::from_secs(30))).await.is_err()
);
s.begin_stop(&sink, true);
s.end_stop(generation, &sink);
assert_eq!(*s.phase.borrow(), Phase::Down);
assert!(
tokio::time::timeout(Duration::from_secs(1), s.wait_ready(Duration::from_secs(30)))
.await
.unwrap()
.is_none()
);
}
}
#[test]
fn failure_publication_can_restart_without_overwriting_the_new_phase() {
for conn in [Conn::Missing, Conn::Failed] {
+129
Переглянути файл
@@ -1877,6 +1877,34 @@ async fn java_source_paths_reach_initialization_live_configuration_and_builds()
assert_eq!(init["initializationOptions"]["triggerFiles"], json!([uri_of(&file)]));
}
#[tokio::test(flavor = "multi_thread")]
async fn java_build_waits_for_a_reconfigured_server_to_restart() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.open("App.java", "class App {}\n");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
state.respond("java/buildWorkspace", json!(1));
let gate = Arc::new(Gate::default());
*state.held.lock() = Some(("exit".into(), gate.clone()));
h.mgr.set_config_hook(Box::new(|cfg, _| cfg.args.push("--new-configuration".into())));
let reconfigure = tokio::spawn({
let mgr = h.mgr.clone();
async move { mgr.reconfigure().await }
});
eventually(|| gate.entered()).await;
let mut build = tokio::spawn({
let (mgr, root) = (h.mgr.clone(), h.root.clone());
async move { mgr.java_build(&root, false, &Default::default()).await }
});
let early = tokio::time::timeout(Duration::from_millis(100), &mut build).await;
gate.open();
reconfigure.await.unwrap();
assert!(early.is_err(), "a planned restart must not fail a pending build: {early:?}");
assert_eq!(build.await.unwrap().unwrap(), ide_lsp::jdtls::JavaBuildStatus::Succeeded);
assert_eq!(state.launches.load(Ordering::SeqCst), 2);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_build_asks_for_a_full_build_when_rebuilding() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
@@ -3454,6 +3482,81 @@ async fn unavailable_scope_capability_keeps_widening_and_incomplete_signals() {
}
}
/// A common name is mentioned by more files than a search opens, but a server that reports its
/// analysis scope already covers most of them: only those beyond it count toward the limit.
#[tokio::test(flavor = "multi_thread")]
async fn covered_candidates_do_not_count_toward_the_open_limit() {
for covers_all in [true, false] {
let mut caps = incremental_caps();
caps["executeCommandProvider"]["commands"] = json!(["openidea.workspace.coveredFiles"]);
let h = harness(&[("mock", caps)]);
let s = h.launcher.state("mock");
let files: Vec<PathBuf> = (0..ide_lsp::MAX_CANDIDATES + 100)
.map(|i| {
let path = h.root.join(format!("f{i:03}.mk"));
std::fs::write(&path, "target\n").unwrap();
path
})
.collect();
let covered: Vec<String> = if covers_all { files.iter().map(|f| uri_of(f)).collect() } else { vec![] };
let responder = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if method == "workspace/executeCommand" {
return Some(json!(covered));
}
responder(s, method, params)
}));
let seen = grep_candidates(&h);
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert!(seen.lock().iter().all(|q| q.limit > ide_lsp::MAX_CANDIDATES));
let opened = s.notified("textDocument/didOpen").len() - 1;
if covers_all {
assert_eq!(refs.incomplete, None);
assert_eq!(opened, 0);
assert_eq!(s.requested("textDocument/references").len(), 1);
} else {
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::TooManyFiles));
assert_eq!(opened, ide_lsp::MAX_CANDIDATES);
}
}
}
/// Files under the directories a server analyses fully are not read to find candidates.
#[tokio::test(flavor = "multi_thread")]
async fn candidates_skip_the_directories_the_server_covers() {
for (commands, reported) in [
(json!(["openidea.workspace.coveredFiles", "openidea.workspace.coveredRoots"]), json!(["src"])),
(json!(["openidea.workspace.coveredFiles", "openidea.workspace.coveredRoots"]), json!(null)),
(json!(["openidea.workspace.coveredFiles"]), json!(["src"])),
] {
let mut caps = incremental_caps();
caps["executeCommandProvider"]["commands"] = commands.clone();
let h = harness(&[("mock", caps)]);
let s = h.launcher.state("mock");
let src = h.root.join("src");
let roots = reported.as_array().map(|r| r.iter().map(|_| json!(uri_of(&src))).collect::<Vec<_>>());
let responder = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if method == "workspace/executeCommand" {
return Some(match params["command"].as_str() {
Some("openidea.workspace.coveredRoots") => roots.clone().map_or(json!(null), Value::Array),
_ => json!([]),
});
}
responder(s, method, params)
}));
let seen = grep_candidates(&h);
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
let skipped: Vec<Vec<PathBuf>> = seen.lock().iter().map(|q| q.skip.clone()).collect();
let expected = if commands.as_array().unwrap().len() == 2 && reported.is_array() { vec![src] } else { vec![] };
assert_eq!(skipped, vec![expected], "{commands} {reported}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn references_open_unopened_files_that_mention_the_name() {
let (h, s) = scope_harness();
@@ -3752,6 +3855,32 @@ async fn classified_java_references_widen_without_losing_metadata() {
}
}
/// Usage counts probe many symbols at once: without `libraries` they search the sources alone.
#[tokio::test(flavor = "multi_thread")]
async fn scoped_java_usages_search_the_sources_unless_libraries_are_asked_for() {
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
let s = h.launcher.state("jdtls");
s.respond("workspace/executeCommand", json!([]));
let (doc, _) = h.open("a.java", "int target;");
h.wait_status("jdtls", ServerStatus::Ready).await;
let seen = grep_candidates(&h);
for libraries in [false, true] {
let refs = h
.mgr
.references_streaming(doc, Pos::new(0, 5), false, false, libraries, Default::default(), None)
.await
.unwrap();
assert_eq!(refs.libraries_skipped, !libraries);
let requested = s.requested("workspace/executeCommand");
let arguments = requested.last().unwrap()["arguments"].as_array().unwrap().clone();
assert_eq!(arguments.get(4) == Some(&json!("sources")), !libraries);
assert_eq!(arguments.len(), if libraries { 4 } else { 5 });
}
assert!(seen.lock().is_empty());
}
/// A library method's usages in the sources are shown before the dependencies and the JDK
/// are searched, which takes seconds; scope widening searches the sources alone again.
#[tokio::test(flavor = "multi_thread")]
+151 -18
Переглянути файл
@@ -271,6 +271,11 @@ impl Cx<'_> {
}
}
/// A filesystem path: expand IDEA's macros before converting a file URL.
fn path(&self, value: Option<&str>) -> Res<Option<String>> {
Ok(self.text(value)?.map(|v| file_url_path(&v)))
}
/// Words of a parameters field, split like IDEA's `ParametersListUtil.parse`.
fn words(&self, value: Option<&str>) -> Res<Vec<String>> {
self.words_quoted(value, Quotes::Double)
@@ -286,12 +291,16 @@ impl Cx<'_> {
}
fn args_quoted(&self, value: Option<&str>, quotes: Quotes, dir: &Path) -> Res<Vec<String>> {
Ok(self.words_quoted(value, quotes)?.into_iter().map(|a| path_from(self.root, a, dir)).collect())
Ok(self
.words_quoted(value, quotes)?
.into_iter()
.map(|a| path_from(self.root, file_url_path(&a), dir))
.collect())
}
/// The working directory (absolute) and the configuration's `cwd`.
fn cwd(&self, value: Option<&str>) -> Res<(PathBuf, Option<PathBuf>)> {
Ok(match self.text(value)? {
Ok(match self.path(value)? {
Some(dir) => working_dir(self.root, &dir),
None => (self.root.to_path_buf(), None),
})
@@ -350,7 +359,7 @@ impl Cx<'_> {
/// options, and the working directory.
fn interpreter(&self, c: &El, ignored: &mut Vec<String>) -> Res<(String, Vec<String>, PathBuf, Option<PathBuf>)> {
let (dir, cwd) = self.cwd(c.option("WORKING_DIRECTORY"))?;
let sdk = if c.flag("IS_MODULE_SDK") { None } else { self.text(c.option("SDK_HOME"))? };
let sdk = if c.flag("IS_MODULE_SDK") { None } else { self.path(c.option("SDK_HOME"))? };
let (exe, mut args) = match sdk {
Some(sdk) => (path_from(self.root, sdk, &dir), Vec::new()),
None => project_python(self.root, &dir),
@@ -369,7 +378,7 @@ impl Cx<'_> {
rc.extras.include_system_env = c.option("PARENT_ENVS") != Some("false");
// PyCharm 2024+: "Paths to .env files", joined with `File.pathSeparator`.
for file in split_env_files(c.option("ENV_FILES").unwrap_or_default(), PATH_SEPARATOR) {
if let Some(file) = self.text(Some(file))? {
if let Some(file) = self.path(Some(file))? {
rc.extras.env_files.push(path_from(self.root, file, self.root));
}
}
@@ -403,7 +412,7 @@ impl Cx<'_> {
ignored.push(format!("EnvFile {path}"));
continue;
}
if let Some(file) = self.text(Some(path))? {
if let Some(file) = self.path(Some(path))? {
rc.extras.env_files.push(path_from(self.root, file, self.root));
}
}
@@ -418,7 +427,7 @@ impl Cx<'_> {
if c.flag("MODULE_MODE") {
args.extend(["-m".to_owned(), script]);
} else {
args.push(path_from(self.root, script, &dir));
args.push(path_from(self.root, file_url_path(&script), &dir));
}
args.extend(self.args(c.option("PARAMETERS"), &dir)?);
let mut rc = config(name, "python", exe, args, Some("debugpy"));
@@ -480,7 +489,7 @@ impl Cx<'_> {
args.extend([manage, "test".to_owned()]);
args.extend(self.words(c.option("TARGET"))?);
if c.flag("CUSTOM_SETTINGS")
&& let Some(settings) = self.text(c.option("SETTINGS_FILE"))?
&& let Some(settings) = self.path(c.option("SETTINGS_FILE"))?
{
args.extend(["--settings".to_owned(), settings_module(&settings, self.root, &dir)]);
}
@@ -519,7 +528,7 @@ impl Cx<'_> {
}
}
Some("CUSTOM") => {}
_ => args.push(path_from(self.root, target, &dir)),
_ => args.push(path_from(self.root, file_url_path(&target), &dir)),
}
}
if target_type.as_deref() != Some("CUSTOM")
@@ -574,7 +583,7 @@ impl Cx<'_> {
fn node_interpreter(&self, c: &El) -> Res<Option<String>> {
match c.value("node-interpreter").or_else(|| c.attr("node-interpreter")).map(str::trim) {
None | Some("" | "project") => Ok(None),
interpreter => self.text(interpreter),
interpreter => self.path(interpreter),
}
}
@@ -587,12 +596,12 @@ impl Cx<'_> {
}
fn npm(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
let package_json = self.text(c.value("package-json"))?;
let package_json = self.path(c.value("package-json"))?;
let dir = match &package_json {
Some(p) => normalize(&self.root.join(p)).parent().map(Path::to_path_buf).unwrap_or(self.root.to_path_buf()),
None => self.root.to_path_buf(),
};
let manager = match self.text(c.value("package-manager"))? {
let manager = match self.path(c.value("package-manager"))? {
Some(pm) if ["npm", "pnpm", "yarn", "bun"].contains(&command_name(&pm)) => command_name(&pm).to_owned(),
_ => {
let pkg = std::fs::read_to_string(dir.join("package.json"))
@@ -650,14 +659,14 @@ impl Cx<'_> {
fn js_tests(&self, name: &str, c: &El, vitest: bool, ignored: &mut Vec<String>) -> Res<RunConfig> {
let (dir, cwd) = self.cwd(c.value("working-dir"))?;
let mut args: Vec<String> = if vitest { vec!["vitest".into(), "run".into()] } else { vec!["jest".into()] };
if !vitest && let Some(config_file) = self.text(c.value("config-file"))? {
if !vitest && let Some(config_file) = self.path(c.value("config-file"))? {
args.extend(["--config".to_owned(), path_from(self.root, config_file, &dir)]);
}
args.extend(self.args(c.value(if vitest { "vitest-options" } else { "jest-options" }), &dir)?);
match c.value("scope-kind").unwrap_or("ALL") {
"DIRECTORY" => args.extend(self.text(c.value("test-directory"))?.map(|d| path_from(self.root, d, &dir))),
"DIRECTORY" => args.extend(self.path(c.value("test-directory"))?.map(|d| path_from(self.root, d, &dir))),
"TEST_FILE" | "SUITE" | "TEST" => {
args.extend(self.text(c.value("test-file"))?.map(|f| path_from(self.root, f, &dir)));
args.extend(self.path(c.value("test-file"))?.map(|f| path_from(self.root, f, &dir)));
let names: Vec<&str> = c
.child("test-names")
.into_iter()
@@ -686,7 +695,7 @@ impl Cx<'_> {
fn node(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
let (dir, cwd) = self.cwd(c.attr("working-dir"))?;
let Some(file) = self.text(c.attr("path-to-js-file"))? else {
let Some(file) = self.path(c.attr("path-to-js-file"))? else {
return Err(SkipReason::NothingToRun);
};
let mut args = self.words(c.attr("node-parameters"))?;
@@ -756,11 +765,11 @@ impl Cx<'_> {
let mut params = BTreeMap::new();
// Both default to true when missing (`ShRunConfiguration.java:148-149`).
let rc = if c.option("EXECUTE_SCRIPT_FILE") != Some("false") {
let Some(path) = self.text(c.option("SCRIPT_PATH"))? else { return Err(SkipReason::NothingToRun) };
let Some(path) = self.path(c.option("SCRIPT_PATH"))? else { return Err(SkipReason::NothingToRun) };
let path = path_from(self.root, path, &dir);
let options = self.text(c.option("SCRIPT_OPTIONS"))?.unwrap_or_default();
let interpreter =
self.text(c.option("INTERPRETER_PATH"))?.map(|i| path_from(self.root, i, &dir)).unwrap_or_default();
self.path(c.option("INTERPRETER_PATH"))?.map(|i| path_from(self.root, i, &dir)).unwrap_or_default();
let interpreter_options = self.text(c.option("INTERPRETER_OPTIONS"))?.unwrap_or_default();
// Run directly, the script is the program: `./run.sh`, so it isn't looked up on the PATH.
let path = if interpreter.is_empty() { dot_slash(path) } else { path };
@@ -861,7 +870,67 @@ const PATH_SEPARATOR: char = if cfg!(windows) { ';' } else { ':' };
/// The `ENV_FILES` paths, joined with `separator` (intellij-community
/// `AbstractPythonRunConfiguration.java:303-304`, `:337`).
fn split_env_files(value: &str, separator: char) -> impl Iterator<Item = &str> {
value.split(separator).filter(|f| !f.trim().is_empty())
let mut rest = value;
std::iter::from_fn(move || {
if rest.is_empty() {
return None;
}
let end = rest.match_indices(separator).find_map(|(end, _)| {
let field = rest[..end].trim_start();
if separator == ':' {
// A URL's scheme and optional drive letter aren't list separators.
let scheme = field.eq_ignore_ascii_case("file");
let drive = field.strip_prefix("file:").is_some_and(|body| {
let body = body.trim_start_matches('/');
let body = body
.split_once('/')
.filter(|(host, _)| host.eq_ignore_ascii_case("localhost"))
.map_or(body, |(_, path)| path);
body.len() == 1 && body.as_bytes()[0].is_ascii_alphabetic()
});
if scheme || drive {
return None;
}
}
Some(end)
});
let field = match end {
Some(end) => {
let field = &rest[..end];
rest = &rest[end + separator.len_utf8()..];
field
}
None => std::mem::take(&mut rest),
};
Some(field)
})
.filter(|f| !f.trim().is_empty())
}
/// The path a `file:` URL names, and `value` unchanged when it is not one.
///
/// IDEA writes path options as URLs (`file://$PROJECT_DIR$`), which expand to
/// `file://C:/project` on Windows: the drive letter lands where a URL's authority
/// belongs. Parsing that as a path yields `C:project`, a drive-relative path that
/// then resolves against the project directory instead of replacing it.
fn file_url_path(value: &str) -> String {
let Some(rest) = value.strip_prefix("file:") else {
return value.to_owned();
};
let rest = match rest.strip_prefix("//").and_then(|r| r.split_once('/')) {
Some((host, path)) if host.eq_ignore_ascii_case("localhost") => path,
_ => rest,
};
let body = rest.trim_start_matches('/');
let drive = matches!(body.as_bytes(), [d, b':', ..] if d.is_ascii_alphabetic());
if drive {
body.to_owned()
} else if rest.starts_with("//") && !rest.starts_with("///") {
// A real authority (`file://server/share`): a UNC path.
format!("//{body}")
} else {
format!("/{body}")
}
}
/// Keywords without the quotes around them (`"not slow"` → `not slow`).
@@ -965,6 +1034,57 @@ mod tests {
assert!(parse("<a><b></a>").is_err());
}
#[test]
fn file_urls_become_paths_whatever_the_drive_letter_looks_like() {
// IDEA on Windows: the drive letter sits where the authority belongs.
assert_eq!(file_url_path("file://C:/p"), "C:/p");
assert_eq!(file_url_path(r"file://C:\p"), r"C:\p");
assert_eq!(file_url_path("file:///C:/p"), "C:/p");
assert_eq!(file_url_path("file:///p/a"), "/p/a");
assert_eq!(file_url_path("file://server/share"), "//server/share");
// Not a URL: left alone, including a bare Windows path.
assert_eq!(file_url_path(r"C:\p"), r"C:\p");
assert_eq!(file_url_path("/p/a"), "/p/a");
assert_eq!(file_url_path(""), "");
}
#[test]
fn file_urls_preserve_paths_and_treat_localhost_as_local() {
for (url, expected) in [
("file:///p/100%20", "/p/100%20"),
("file:///p/a%E4", "/p/a%E4"),
("file:///p/a b/中.py", "/p/a b/中.py"),
("file://C:/a b/é", "C:/a b/é"),
("file:///C:/a%20b", "C:/a%20b"),
("file://localhost/p/a%20b", "/p/a%20b"),
("file://localhost/C:/a%20b", "C:/a%20b"),
("file://LOCALHOST/p", "/p"),
("file://server/share/a%20b", "//server/share/a%20b"),
("file:///p/%2520", "/p/%2520"),
("/p/a%20b", "/p/a%20b"),
("relative%20path", "relative%20path"),
("https://localhost/a%20b", "https://localhost/a%20b"),
] {
assert_eq!(file_url_path(url), expected, "{url}");
}
}
/// The property the bug broke: `working_dir` joins its `cwd` onto the project
/// directory, so a URL that reads as a relative path resolves inside it instead
/// of replacing it.
#[test]
fn file_urls_name_absolute_paths() {
let absolute = if cfg!(windows) {
vec!["file://C:/p", "file:///C:/p", r"file://C:\p", "file://server/share"]
} else {
vec!["file:///p/a", "file://server/share"]
};
for url in absolute {
let path = file_url_path(url);
assert!(Path::new(&path).is_absolute(), "{url} became {path:?}, which is not absolute");
}
}
#[test]
fn env_files_split_on_the_path_separator() {
assert_eq!(
@@ -975,6 +1095,19 @@ mod tests {
split_env_files(r"C:\p\.env;C:\p\.env.local", ';').collect::<Vec<_>>(),
[r"C:\p\.env", r"C:\p\.env.local"]
);
assert_eq!(
split_env_files("file://$PROJECT_DIR$/.env:file://localhost/p/a%20b:.env.local", ':').collect::<Vec<_>>(),
["file://$PROJECT_DIR$/.env", "file://localhost/p/a%20b", ".env.local"]
);
assert_eq!(
split_env_files("file://C:/p/.env:file:///D:/p/.env:file://localhost/E:/p/.env%3Adev", ':')
.collect::<Vec<_>>(),
["file://C:/p/.env", "file:///D:/p/.env", "file://localhost/E:/p/.env%3Adev"]
);
assert_eq!(
split_env_files("file://C:/p/.env;file://localhost/C:/p/.env.local", ';').collect::<Vec<_>>(),
["file://C:/p/.env", "file://localhost/C:/p/.env.local"]
);
assert_eq!(split_env_files("", ':').count(), 0);
assert_eq!(PATH_SEPARATOR, if cfg!(windows) { ';' } else { ':' });
}
+156 -11
Переглянути файл
@@ -849,21 +849,115 @@ fn sync_tree(
Ok(())
}
/// A built `*.war` under a module's usual output directory (`target/`, `build/libs/`).
fn is_war(path: &Path) -> bool {
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("war"))
}
/// The module directory a config's `cwd` names (absolute, or relative to the project root).
fn module_dir(root: &Path, module: Option<&Path>) -> PathBuf {
match module {
Some(m) if m.is_absolute() => m.to_path_buf(),
Some(m) => root.join(m),
None => root.to_path_buf(),
}
}
/// The newest modification time of `path` or, for a directory, anything below it.
fn newest_mtime_under(path: &Path) -> Option<std::time::SystemTime> {
let meta = fs::metadata(path).ok()?;
let mut newest = meta.modified().ok();
if meta.is_dir() {
for entry in fs::read_dir(path).ok()?.flatten() {
if let Some(time) = newest_mtime_under(&entry.path())
&& newest.is_none_or(|cur| time > cur)
{
newest = Some(time);
}
}
}
newest
}
/// The newest `*.war` a build tool left in the module's output directories. Used when no
/// build ran this launch and nothing was recorded, so a project that was already built can
/// start directly (IDEA deploys the existing artifact instead of rebuilding it).
fn find_built_war(root: &Path, module: Option<&Path>) -> Option<PathBuf> {
let module = module_dir(root, module);
let mut newest: Option<(std::time::SystemTime, PathBuf)> = None;
for dir in [module.join("target"), module.join("build/libs")] {
let Ok(entries) = fs::read_dir(dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && is_war(&path) {
let modified = entry.metadata().and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH);
if newest.as_ref().is_none_or(|(at, _)| modified > *at) {
newest = Some((modified, path));
}
}
}
}
newest.map(|(_, path)| path)
}
/// Whether the WAR a Tomcat config deploys is newer than the module's sources, so its
/// "Before launch › Build" task can be skipped (IDEA's up-to-date check). Conservative:
/// a missing WAR or a newer source/build file means it is not current. Only the module's
/// own sources and build files are inspected, not dependency modules.
pub fn artifact_is_current(root: &Path, base: &Path, config: &RunConfig) -> bool {
let p = &config.extras.params;
if p.get("deployment").map(String::as_str).unwrap_or("artifact") != "artifact" {
return true;
}
let module = module_dir(root, config.cwd.as_ref().map(|c| c.0.as_path()));
let selected = p.get("artifact").filter(|s| !s.is_empty());
let recorded_id = fs::read_to_string(base.join("artifact-id.txt")).ok();
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,
_ => 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 mut newest = newest_mtime_under(&module.join("src"));
for dir in [module.as_path(), root] {
for name in ["pom.xml", "build.gradle", "build.gradle.kts"] {
if let Ok(time) = fs::metadata(dir.join(name)).and_then(|m| m.modified())
&& newest.is_none_or(|cur| time > cur)
{
newest = Some(time);
}
}
}
newest.is_none_or(|time| time <= war_time)
}
pub fn deployment(root: &Path, base: &Path, config: &RunConfig, resources_only: bool) -> IdeResult<PathBuf> {
let p = &config.extras.params;
match p.get("deployment").map(String::as_str).unwrap_or("artifact") {
"artifact" => {
if let Some(id) = p.get("artifact").filter(|s| !s.is_empty())
&& fs::read_to_string(base.join("artifact-id.txt")).ok().as_ref() != Some(id)
{
return Err(invalid("Build the selected WAR artifact before launching Tomcat"));
}
let war = fs::read_to_string(base.join("artifact-path.txt"))
.map_err(|_| invalid("Build the WAR artifact before launching Tomcat"))?;
let war = PathBuf::from(war.trim());
if !war.is_file() || !war.extension().is_some_and(|e| e.eq_ignore_ascii_case("war")) {
return Err(invalid(format!("The built WAR artifact does not exist: {}", war.display())));
}
// A build run this launch records its archive here. Without one (Before launch ›
// Build removed, as IDEA allows), reuse the last build's archive, or an archive a
// build tool already left in the module output, instead of rebuilding.
let selected = p.get("artifact").filter(|s| !s.is_empty());
let recorded_id = fs::read_to_string(base.join("artifact-id.txt")).ok();
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
} else {
return Err(invalid(format!("The built WAR artifact does not exist: {}", war.display())));
}
}
None => find_built_war(root, config.cwd.as_ref().map(|c| c.0.as_path())).ok_or_else(|| {
invalid("No built WAR artifact found - build the project first, or add 'Build' to Before launch")
})?,
};
let dest = base.join("deployment");
explode(&war, &dest, resources_only)?;
Ok(dest)
@@ -1402,6 +1496,57 @@ mod tests {
}
}
}
#[test]
fn reuses_a_built_war_when_no_build_ran() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let module = root.join("web");
fs::create_dir_all(module.join("target")).unwrap();
let war = module.join("target/app.war");
archive(&war, &[("index.html", "built")]);
let base = root.join("cache");
fs::create_dir_all(&base).unwrap();
let mut c = config();
c.cwd = Some(ide_core::IpcPath(PathBuf::from("web")));
c.extras.params.insert("artifact".into(), "maven:web/pom.xml".into());
// No artifact-path.txt / artifact-id.txt: it was never built through Tomcat.
let dest = deployment(root, &base, &c, false).unwrap();
assert_eq!(fs::read_to_string(dest.join("index.html")).unwrap(), "built");
}
#[test]
fn reports_a_missing_artifact_when_nothing_was_built() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path().join("cache");
fs::create_dir_all(&base).unwrap();
let error = deployment(tmp.path(), &base, &config(), false).unwrap_err().to_string();
assert!(error.contains("No built WAR artifact found"), "{error}");
}
#[test]
fn skips_the_build_when_the_built_war_is_current() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let module = root.join("web");
fs::create_dir_all(module.join("src/main/java")).unwrap();
fs::create_dir_all(module.join("target")).unwrap();
fs::write(module.join("pom.xml"), "<project/>").unwrap();
let source = module.join("src/main/java/App.java");
fs::write(&source, "class App {}").unwrap();
let war = module.join("target/app.war");
archive(&war, &[("index.html", "built")]);
let base = root.join("cache");
fs::create_dir_all(&base).unwrap();
let mut c = config();
c.cwd = Some(ide_core::IpcPath(PathBuf::from("web")));
c.extras.params.insert("artifact".into(), "maven:web/pom.xml".into());
// The WAR was packed after the source was written.
assert!(artifact_is_current(root, &base, &c));
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(&source, "class App { int changed; }").unwrap();
assert!(!artifact_is_current(root, &base, &c));
}
#[test]
fn prepares_isolated_base_and_jdwp_only_for_run() {
let tmp = tempfile::tempdir().unwrap();
+220
Переглянути файл
@@ -787,3 +787,223 @@ fn java_applications_and_spring_boot_keep_their_module() {
assert_eq!(reason(&r, "NoMain"), &SkipReason::NothingToRun);
}
/// IDEA writes the working directory as a URL. On Windows `file://$PROJECT_DIR$`
/// expands to `file://C:/project`, where the drive letter sits where the authority
/// belongs; read as a path that is `C:project`, which resolves against the project
/// directory instead of replacing it and the launch fails on the doubled path.
#[test]
fn file_url_working_directories_stay_inside_the_project() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(&root, "pom.xml", "<project><artifactId>shop</artifactId><packaging>pom</packaging></project>");
write(
&root,
"gateway/pom.xml",
"<project><parent><artifactId>shop</artifactId></parent><artifactId>gateway</artifactId></project>",
);
write(
&root,
".run/Gateway.run.xml",
&run_file(
"Gateway",
r#"<configuration name="NAME" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="gateway" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.example.GatewayApplication" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ACTIVE_PROFILES" value="dev,local" />
<option name="VM_PARAMETERS" value="-Xmx512m" />
<option name="PROGRAM_PARAMETERS" value="--server.port=8081" />
<envs><env name="TZ" value="UTC" /></envs>
<method v="2"><option name="Make" enabled="true" /></method>
</configuration>"#,
),
);
write(
&root,
".run/Sub.run.xml",
&run_file(
"Sub",
r#"<configuration name="NAME" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="gateway" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.example.SubApplication" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$/gateway" />
<method v="2" />
</configuration>"#,
),
);
let local_root = root.to_string_lossy().replace('\\', "/");
for (name, working_directory) in [
("Literal", "file://$PROJECT_DIR$/gateway é".to_owned()),
("Localhost", format!("file://localhost/{}", local_root.trim_start_matches('/'))),
] {
write(
&root,
&format!(".run/{name}.run.xml"),
&run_file(
name,
&format!(
r#"
<configuration name="NAME" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="gateway" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.example.GatewayApplication" />
<option name="WORKING_DIRECTORY" value="{working_directory}" />
</configuration>"#
),
),
);
}
let r = import_from(&root, &[]);
let boot = get(&r, "Gateway");
assert_eq!(boot.kind, "spring-boot");
assert_eq!(boot.extras.module.as_deref(), Some("gateway"));
assert_eq!(
boot.args,
s(&[
"-Xmx512m",
"-cp",
"${classpath}",
"com.example.GatewayApplication",
"--spring.profiles.active=dev,local",
"--server.port=8081"
])
);
assert_eq!(boot.env["TZ"], "UTC");
assert_eq!(cwd(get(&r, "Literal")), Some(PathBuf::from("gateway é")));
assert_eq!(cwd(get(&r, "Localhost")), None);
// The project directory itself: no `cwd` to store.
assert_eq!(cwd(get(&r, "Gateway")), None);
assert_eq!(cwd(get(&r, "Sub")), Some(PathBuf::from("gateway")));
}
#[test]
fn file_urls_work_in_all_imported_path_fields() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
let cases = [
(
"Python",
r#"<configuration name="NAME" type="PythonConfigurationType">
<option name="WORKING_DIRECTORY" value="{base}/jobs 中" />
<option name="SDK_HOME" value="{base}/bin/python" />
<option name="SCRIPT_NAME" value="{base}/jobs 中/run me.py" />
<option name="PARAMETERS" value="&quot;{base}/data file&quot; unchanged%20arg" />
<option name="ENV_FILES" value="{base}/.env dev{sep}{base}/.env local" />
<extension name="net.ashald.envfile">
<option name="IS_ENABLED" value="true" />
<ENTRIES><ENTRY PATH="{base}/.env plugin" PARSER="env" /></ENTRIES>
</extension>
</configuration>"#,
),
(
"Django",
r#"<configuration name="NAME" type="DjangoTestsConfigurationType">
<option name="CUSTOM_SETTINGS" value="true" />
<option name="SETTINGS_FILE" value="{base}/settings/dev.py" />
</configuration>"#,
),
(
"Pytest",
r#"<configuration name="NAME" type="tests" factoryName="pytest">
<option name="_new_targetType" value="&quot;PATH&quot;" />
<option name="_new_target" value="&quot;{base}/test file.py&quot;" />
<option name="_new_additionalArguments" value="&quot;'{base}/data file'&quot;" />
</configuration>"#,
),
(
"Npm",
r#"<configuration name="NAME" type="js.build_tools.npm">
<package-json value="{base}/web app/package.json" />
<package-manager value="{base}/bin/pnpm" />
<node-interpreter value="{base}/bin/node" />
<command value="run" /><scripts><script value="start" /></scripts>
</configuration>"#,
),
(
"Jest",
r#"<configuration name="NAME" type="JavaScriptTestRunnerJest">
<working-dir value="{base}/web app" />
<config-file value="{base}/web app/jest config.js" />
<scope-kind value="TEST_FILE" /><test-file value="{base}/web app/test file.js" />
</configuration>"#,
),
(
"Vitest",
r#"<configuration name="NAME" type="JavaScriptTestRunnerVitest">
<scope-kind value="DIRECTORY" /><test-directory value="{base}/test dir" />
</configuration>"#,
),
(
"Node",
r#"<configuration name="NAME" type="NodeJSConfigurationType"
working-dir="{base}/web app" path-to-js-file="{base}/web app/main file.js"
application-parameters="&quot;{base}/data file&quot;" />"#,
),
(
"Shell",
r#"<configuration name="NAME" type="ShConfigurationType">
<option name="SCRIPT_WORKING_DIRECTORY" value="{base}/jobs 中" />
<option name="SCRIPT_PATH" value="{base}/jobs 中/run me.sh" />
<option name="INTERPRETER_PATH" value="{base}/bin/sh" />
</configuration>"#,
),
];
write(&root, "manage.py", "");
for (name, body) in cases {
write(
&root,
&format!(".run/{name}.run.xml"),
&run_file(name, &body.replace("{base}", "file://$PROJECT_DIR$").replace("{sep}", &SEP.to_string())),
);
}
let r = import_from(&root, &[]);
assert!(r.skipped.is_empty(), "{r:#?}");
let python = get(&r, "Python");
assert_eq!(cwd(python), Some(PathBuf::from("jobs 中")));
assert_eq!(python.command, "../bin/python");
assert_eq!(python.args, s(&["run me.py", "../data file", "unchanged%20arg"]));
assert_eq!(python.extras.env_files, s(&[".env dev", ".env local", ".env plugin"]));
assert_eq!(get(&r, "Django").args, s(&["manage.py", "test", "--settings", "settings.dev"]));
assert_eq!(get(&r, "Pytest").args, s(&["-m", "pytest", "test file.py", "data file"]));
let npm = get(&r, "Npm");
assert_eq!(cwd(npm), Some(PathBuf::from("web app")));
assert_eq!(npm.command, "pnpm");
assert_eq!(Path::new(&npm.extras.params["nodeInterpreter"]), root.join("bin/node"));
assert_eq!(get(&r, "Jest").args, s(&["jest", "--config", "jest config.js", "test file.js"]));
assert_eq!(get(&r, "Vitest").args, s(&["vitest", "run", "test dir"]));
assert_eq!(get(&r, "Node").args, s(&["main file.js", "../data file"]));
let shell = get(&r, "Shell");
assert_eq!(shell.command, "../bin/sh");
assert_eq!(shell.args, s(&["run me.sh"]));
assert_eq!(shell.extras.params["path"], "run me.sh");
}
#[test]
fn file_urls_expand_module_and_home_macros() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(
&root,
".run/Home.run.xml",
&run_file(
"Home",
r#"<configuration name="NAME" type="PythonConfigurationType">
<option name="WORKING_DIRECTORY" value="file://$MODULE_DIR$/jobs dir" />
<option name="SCRIPT_NAME" value="file://$MODULE_WORKING_DIR$/jobs dir/main.py" />
<option name="SDK_HOME" value="file://$USER_HOME$/bin/python" />
</configuration>"#,
),
);
let mut environment = env();
let home = root.join("home").to_string_lossy().into_owned();
environment.insert("HOME".into(), home.clone());
environment.insert("USERPROFILE".into(), home);
let r = import(&root, RunImportSource::Jetbrains, &[], &environment).unwrap();
let home = get(&r, "Home");
assert_eq!(home.command, "../home/bin/python");
assert_eq!(home.args, s(&["main.py"]));
assert_eq!(cwd(home), Some(PathBuf::from("jobs dir")));
assert!(home.extras.local);
}
+67 -6
Переглянути файл
@@ -523,6 +523,63 @@ pub fn maven_local_repository(root: &Path, s: &Settings) -> Option<PathBuf> {
})
}
fn xml_escape(text: &str) -> String {
text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}
/// Inserts `<localRepository>` right after the `<settings>` open tag.
fn inject_local_repository(settings_xml: &str, repo: &str) -> Option<String> {
let start = settings_xml.find("<settings")?;
let end = settings_xml[start..].find('>')? + start;
let mut out = String::with_capacity(settings_xml.len() + repo.len() + 40);
out.push_str(&settings_xml[..=end]);
out.push_str("<localRepository>");
out.push_str(&xml_escape(repo));
out.push_str("</localRepository>");
out.push_str(&settings_xml[end + 1..]);
Some(out)
}
fn write_m2e_settings(root: &Path, text: &str) -> Option<PathBuf> {
let file = ide_core::project_dir::path(root, "maven-settings.xml");
if let Some(parent) = file.parent() {
std::fs::create_dir_all(parent).ok()?;
}
match std::fs::read_to_string(&file) {
Ok(existing) if existing == text => {}
_ => std::fs::write(&file, text).ok()?,
}
Some(file)
}
/// The user settings file m2e (the JDTLS Maven import) should read: the
/// configured `settings.xml` when it already declares `<localRepository>`,
/// else a derived copy under `<root>/.openidea/` with the configured local
/// repository injected. m2e resolves the local repository from the settings
/// XML, not from `-Dmaven.repo.local`, so without this the import downloads
/// into `~/.m2/repository` even when the IDE's own `mvn` runs honor the
/// configured path (#1739). `None` = m2e's default applies.
pub fn maven_user_settings_for_m2e(root: &Path, s: &Settings) -> Option<PathBuf> {
let m = &s.languages.java.maven;
if let Some(file) = setting_path(root, &m.user_settings) {
let text = std::fs::read_to_string(&file).ok()?;
if crate::java::xml_value(&crate::lombok::strip_xml_comments(&text), "localRepository").is_some() {
return Some(file);
}
if let Some(repo) = setting_path(root, &m.local_repository) {
let merged = inject_local_repository(&text, &repo.to_string_lossy())?;
if let Some(derived) = write_m2e_settings(root, &merged) {
return Some(derived);
}
}
return Some(file);
}
let repo = setting_path(root, &m.local_repository)?;
let minimal =
format!("<settings><localRepository>{}</localRepository></settings>", xml_escape(&repo.to_string_lossy()));
write_m2e_settings(root, &minimal)
}
/// TypeScript `lib` directory for the selected version; `None` = the server's bundled one.
pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
match s.languages.typescript.version.trim() {
@@ -861,18 +918,22 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
// The jdtls launcher forwards `--jvm-arg=` values to the JVM it starts.
let args = s.languages.java.jdtls_vm_args.split_whitespace().map(|a| format!("--jvm-arg={a}"));
cfg.args.extend(args);
// m2e (the Maven import) reads mirrors, servers and `<localRepository>` from it.
if let Some(file) = setting_path(root, &s.languages.java.maven.user_settings) {
// m2e (the Maven import) reads mirrors, servers and `<localRepository>`
// from the settings file — never from `-Dmaven.repo.local`. The
// derived file carries the configured local repository so the import
// downloads where the IDE's own `mvn` runs do (#1739).
if let Some(file) =
maven_user_settings_for_m2e(root, s).or_else(|| setting_path(root, &s.languages.java.maven.user_settings))
{
let file = file.to_string_lossy();
merge_init_options(
cfg,
json!({ "settings": { "java": { "configuration": { "maven": { "userSettings": file } } } } }),
);
}
// m2e resolves and downloads into `maven.repo.local`; without it the
// embedded Maven falls back to ~/.m2 even when the IDE's own `mvn`
// runs honor the configured local repository. A `-Dmaven.repo.local`
// the user put in their own jdtls VM options wins.
// The JVM system property is still forwarded for JVM-level consumers,
// but it is the settings file above that m2e honors. A
// `-Dmaven.repo.local` the user put in their own jdtls VM options wins.
if let Some(repo) = maven_local_repository(root, s) {
let arg = format!("-Dmaven.repo.local={}", repo.to_string_lossy());
let taken = cfg.args.iter().enumerate().any(|(i, a)| {
+1 -1
Переглянути файл
@@ -1508,7 +1508,7 @@ mod kotlin_bridge_bundle_tests {
/// Installs the app-owned JDT LS command bundle, falling back to ordinary LSP on IO failure.
pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
let extension = data_dir.join("java-usages-1.9.0.jar");
let extension = data_dir.join("java-usages-1.12.0.jar");
let bytes = include_bytes!("../../../java/java-usages/openidea-java-usages.jar");
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
clean_usages_bundles(data_dir, &extension);
+47
Переглянути файл
@@ -208,6 +208,53 @@ fn jdtls_honors_the_configured_maven_local_repository() {
assert!(cfg.args.iter().all(|a| !a.contains("maven.repo.local")));
}
#[test]
fn jdtls_m2e_gets_effective_settings_with_local_repository() {
fn user_settings(cfg: &LanguageServerConfig) -> Option<std::path::PathBuf> {
let opts = serde_json::to_value(cfg.initialization_options.clone()?).ok()?;
opts.pointer("/settings/java/configuration/maven/userSettings")?.as_str().map(std::path::PathBuf::from)
}
// Configured repository, no user settings: a derived file is passed (#1739).
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("m2-repo");
let mut s = Settings::default();
s.languages.java.maven.local_repository = repo.to_string_lossy().into_owned();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
let derived = tmp.path().join(".openidea").join("maven-settings.xml");
assert_eq!(user_settings(&cfg), Some(derived.clone()));
let text = std::fs::read_to_string(&derived).unwrap();
assert!(text.contains(&format!("<localRepository>{}</localRepository>", repo.to_string_lossy())));
// Stable across runs (no rewrite churn).
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(user_settings(&cfg), Some(derived.clone()));
// User settings without `<localRepository>`: the derived copy keeps the
// user's mirrors and gains the configured repository.
let settings = tmp.path().join("mine.xml");
std::fs::write(&settings, "<settings><mirrors><mirror><id>m</id></mirror></mirrors></settings>").unwrap();
s.languages.java.maven.user_settings = settings.to_string_lossy().into_owned();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(user_settings(&cfg), Some(derived.clone()));
let text = std::fs::read_to_string(&derived).unwrap();
assert!(text.contains("<mirror><id>m</id></mirror>"));
assert!(text.contains(&format!("<localRepository>{}</localRepository>", repo.to_string_lossy())));
// User settings already declaring `<localRepository>`: passed through untouched.
std::fs::write(&settings, "<settings><localRepository>/user/repo</localRepository></settings>").unwrap();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(user_settings(&cfg), Some(settings.clone()));
// Neither configured: no userSettings at all.
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &Settings::default());
assert_eq!(user_settings(&cfg), None);
}
#[test]
fn rust_analyzer_check_command_and_toolchain() {
if cfg!(windows) {
+42
Переглянути файл
@@ -0,0 +1,42 @@
# Open scripts from Unity
OpenIDEA can open scripts and Console source locations without a Unity plugin.
1. In Unity, open **Edit > Preferences > External Tools** (on macOS,
**Unity > Settings/Preferences > External Tools**).
2. Under **External Script Editor**, choose **Browse** and select OpenIDEA's
executable (or its `.app` on macOS).
3. Set **External Script Editor Args** to:
```text
$(ProjectPath) --file $(File) --line $(Line) --column $(Column)
```
Unity 2022.3 quotes the expanded project and file paths itself, including paths
with spaces. Do not add another pair of quotes around these placeholders.
Double-click a script in the Project window or a source location in the Console.
OpenIDEA opens the project and file, or focuses its existing project window, then
places the caret at the supplied location. Other open tabs stay in place.
The project argument makes cold launches open the Unity project rather than a
standalone file. Without it, `--file` opens in an existing matching project window
or in LightEdit. Relative file paths resolve against the supplied project folder,
or against the launch working directory when no project is supplied.
For a direct invocation of the application executable, quote paths as required
by your shell. The separately installed `openidea` command has its own syntax:
```text
/path/to/openidea "/path/to/My Game" --file "/path/to/My Game/Assets/Player.cs" --line 12 --column 5
```
`--file=...`, `--line=...` and `--column=...` also work. Lines and columns are
1-based; Unity's `0` and `-1` mean an unknown position. An omitted or unknown
column uses the start of the line. Without a known line, the file opens without
an explicit caret position. Invalid arguments and missing files report an error.
On Windows, use the same permissions for Unity and OpenIDEA when possible.
If a running instance does not receive a request, restart both applications with
matching permissions and retry. This integration opens local projects; it does
not generate C# project files or attach a debugger.
+20
Переглянути файл
@@ -340,3 +340,23 @@ test("selects through code blocks and tables while keeping copy controls outside
await copies.last().click();
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(flow);
});
test("keeps mermaid `<style>` rules scoped to the rendered svg after id rewriting", async ({ page }) => {
const diagram = [
"```mermaid",
"%%{init: {'theme': 'base', 'flowchart': {'htmlLabels': false, 'curve': 'basis'}}}%%",
"flowchart TB",
' subgraph T1["Tier 1"]',
" A[(Local)] <--> B[(Peer)]",
" end",
' subgraph T2["Tier 2"]',
" C[(Host RAM)]",
" end",
' C -->|"PCIe"| A',
"```",
].join("\n");
const reply = await openReply(page, `Diagram:\n\n${diagram}`);
await expect(reply.locator("[data-mermaid-state='ok'] .mermaid-output svg")).toBeVisible();
expect(await css(reply, ".cluster rect", "fill")).not.toBe("rgb(0, 0, 0)");
expect(await css(reply, ".flowchart-link", "fill")).toBe("none");
});
+32
Переглянути файл
@@ -0,0 +1,32 @@
import { expect, openFromTree, test } from "./fixtures";
/** The end of a long line must stay visible: the floating corner widgets leave it room. */
test("the inspection widget does not cover the end of a long line", async ({ workbench: page }) => {
const editor = await openFromTree(page, "build.gradle.kts");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("x".repeat(600));
await expect(editor.locator(".cm-line")).toHaveCount(1);
await expect(editor.locator(".cm-openidea-corner")).toBeAttached();
const scroller = editor.locator(".cm-scroller");
await expect.poll(() => scroller.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeGreaterThan(0);
await scroller.evaluate((el) => {
el.scrollLeft = el.scrollWidth;
});
const rects = await editor.evaluate((el) => {
const line = el.querySelector(".cm-line")!;
const range = document.createRange();
range.selectNodeContents(line);
return {
textRight: range.getBoundingClientRect().right,
cornerLeft: el.querySelector(".cm-openidea-corner")!.getBoundingClientRect().left,
scrollLeft: el.querySelector(".cm-scroller")!.scrollLeft,
};
});
// Scrolled as far right as it goes, and the last character sits left of the widget.
expect(rects.scrollLeft).toBeGreaterThan(0);
expect(rects.cornerLeft).toBeGreaterThan(rects.textRight);
});
+124
Переглянути файл
@@ -18,6 +18,7 @@ interface Opts {
alignChanges?: boolean;
syncScroll?: boolean;
collapse?: boolean;
softWrap?: boolean;
ignore?: "none" | "trim" | "whitespace" | "whitespaceAndLines";
}
@@ -350,3 +351,126 @@ test.describe("10,000-line files", () => {
await shot(page, `rewrite-${mode.replace(" ", "-")}`);
});
});
test.describe("soft wrapping", () => {
for (const [mode, opts] of [
["split", { alignChanges: false }],
["aligned", { alignChanges: true }],
["unified", { mode: "unified" }],
] as [string, Opts][]) {
test(`toggles in place, retains the visible line and routes the editor action (${mode})`, async ({
workbench: page,
}) => {
await openCase(page, "src/soft-wrap.ts", { ...opts, softWrap: false });
const editors = page.locator(".cm-editor.cm-merge-a, .cm-editor.cm-merge-b");
const count = mode === "unified" ? 1 : 2;
await expect(editors).toHaveCount(count);
await editors.evaluateAll((eds) => {
for (const ed of eds) (ed as HTMLElement).dataset.wrapIdentity = "original";
});
const right = page.locator(".cm-editor.cm-merge-b");
await right.evaluate(async (ed) => {
const path = "/node_modules/.vite/deps/@codemirror_view.js";
const { EditorView } = await import(/* @vite-ignore */ path);
const view = EditorView.findFromDOM(ed)!;
const pos = view.state.doc.line(125).from;
view.dispatch({ selection: { anchor: pos }, effects: EditorView.scrollIntoView(pos, { y: "center" }) });
view.focus();
});
const topLine = () =>
right.evaluate(async (ed) => {
const path = "/node_modules/.vite/deps/@codemirror_view.js";
const { EditorView } = await import(/* @vite-ignore */ path);
const v = EditorView.findFromDOM(ed)!;
const outer = ed.closest<HTMLElement>(".cm-mergeView");
const top = Math.max(v.scrollDOM.getBoundingClientRect().top, outer?.getBoundingClientRect().top ?? 0);
return v.state.doc.lineAt(v.lineBlockAtHeight(Math.max(0, top - v.documentTop)).from).number;
});
await expect.poll(topLine).toBeGreaterThan(80);
const before = await topLine();
await toolbar(page).getByRole("button", { name: "Settings", exact: true }).click();
const checkbox = page.getByRole("menuitemcheckbox", { name: "Use Soft Wraps", exact: true });
await expect(checkbox).toHaveAttribute("aria-checked", "false");
await checkbox.click();
await expect(page.locator(".cm-lineWrapping")).toHaveCount(count);
await expect.poll(async () => Math.abs((await topLine()) - before)).toBeLessThanOrEqual(3);
await expect(page.locator('[data-wrap-identity="original"]')).toHaveCount(count);
await right.evaluate(async (ed) => {
const path = "/node_modules/.vite/deps/@codemirror_view.js";
const { EditorView } = await import(/* @vite-ignore */ path);
const v = EditorView.findFromDOM(ed)!;
if (v.state.doc.lineAt(v.state.selection.main.head).number !== 125) throw new Error("Selection lost");
v.dispatch({ effects: EditorView.scrollIntoView(0, { y: "start" }) });
});
const first = right.locator(".cm-content > .cm-line").first();
await expect.poll(() => first.evaluate((line) => line.getBoundingClientRect().height)).toBeGreaterThan(100);
// Line-number backgrounds cover the entire wrapped logical line.
if (mode !== "unified") {
await expect
.poll(() =>
right.evaluate((ed) =>
Math.abs(
ed.querySelector(".cm-content > .cm-line")!.getBoundingClientRect().height -
ed.querySelector(".cm-lineNumbers .cm-diffGutter-modified")!.getBoundingClientRect().height,
),
),
)
.toBeLessThan(2);
if (mode === "aligned") {
await expect
.poll(async () => {
const tops = await editors.evaluateAll(async (eds) => {
const path = "/node_modules/.vite/deps/@codemirror_view.js";
const { EditorView } = await import(/* @vite-ignore */ path);
return eds.map((ed) => {
const view = EditorView.findFromDOM(ed)!;
return view.documentTop + view.lineBlockAt(view.state.doc.line(2).from).bottom;
});
});
return Math.abs(tops[0]! - tops[1]!);
})
.toBeLessThan(2);
} else {
const path = await page.locator(".cm-diffDivider svg path").first().getAttribute("d");
expect(path).toBeTruthy();
expect(path).not.toMatch(/NaN|Infinity/);
}
} else {
await expect
.poll(() =>
right
.locator(".cm-deletedLine")
.first()
.evaluate((line) => line.getBoundingClientRect().height),
)
.toBeGreaterThan(100);
}
// The standard action toggles both panes, whether the read-only left or right is focused.
for (let i = 0; i < count; i++) {
await editors.nth(i).locator(".cm-content").focus();
await page.evaluate(async () => {
const path = "/src/platform/actions.ts";
const { executeAction, isActionEnabled, useActions } = await import(/* @vite-ignore */ path);
if (!isActionEnabled(useActions.getState().actions.get("editor.toggleSoftWrap")!))
throw new Error("Soft-Wrap action disabled");
if (document.activeElement?.closest(".cm-merge-a")) {
const path = "/src/ui/index.ts";
const { showContextMenu } = await import(/* @vite-ignore */ path);
showContextMenu({ x: 100, y: 100 }, [{ kind: "action", action: "editor.toggleSoftWrap" }]);
} else await executeAction("editor.toggleSoftWrap");
});
if (count === 2 && i === 0) {
const action = page.getByRole("menuitemcheckbox", { name: "Soft-Wrap", exact: true });
await expect(action).toBeEnabled();
await expect(action).toHaveAttribute("aria-checked", "true");
await action.click();
}
await expect(page.locator(".cm-lineWrapping")).toHaveCount(i % 2 === 0 ? 0 : count);
}
const persisted = await page.evaluate(
() => JSON.parse(localStorage.getItem("openidea.vcs.diffOptions")!).softWrap,
);
expect(persisted).toBe(count === 2);
});
}
});
+11
Переглянути файл
@@ -61,6 +61,17 @@ const FUNCS = ["parse", "format", "validate", "render", "save"].map(
const MINIFIED = Array.from({ length: 2_000 }, (_, i) => `var a${i}=f(${i},"k${i}");`).join("");
export const CASES: readonly DiffCase[] = [
{
path: "src/soft-wrap.ts",
before:
`// ${"long original text ".repeat(100)}\n` +
lines(150, (i) => `const value${i} = ${i};`) +
`// ${"old tail ".repeat(100)}\n`,
after:
`// ${"long changed text ".repeat(160)}\n` +
lines(150, (i) => `const value${i} = ${i};`) +
`// ${"new changed tail ".repeat(180)}\n`,
},
// A word edited and a comment added: one modified block (the reported case).
{ path: "src/options.ts", before: OPTIONS_BEFORE, after: OPTIONS_AFTER },
{
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.9.0
Bundle-Version: 1.12.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+17 -2
Переглянути файл
@@ -27,6 +27,11 @@ from directory names. References, rename and incoming calls leave those files cl
and only widen with the remaining candidates. A missing or failing command retains
widening. The result is query-local, so imports and classpath changes need no cache invalidation.
`openidea.workspace.coveredRoots()` returns the URIs of source folders whose Java files the search
scope covers all: no exclusion patterns, no inclusion pattern other than Maven's `**/*.java`, and
enclosed by the test-source policy. The client does not read the files under them when it looks
for candidates, which on a large project took most of a cached search's time.
## Search plan and access semantics
For source fields on the verified JDT LS implementation, a single plan merges
@@ -58,7 +63,14 @@ traversals. It indexes only requested exact AST ranges and verified invocation
selector-to-call-end spans; duplicate, recovered, malformed or uncontained ranges
fall back to NodeFinder. Method references do not get invocation aliases. Source
snapshot checks remain per result, and the index is discarded after the query.
There is no cross-request cache or binding-resolution shortcut.
Answers are cached by their search targets (JDT handles, kinds, declarations), the scope and the
search settings, together with a digest of the editors' unsaved contents, until a Java element
delta reports a change to the sources, a compilation unit or a classpath (`UsageCache`). Opening
or closing an editor and decompiled library classes' private working copies do not invalidate
them. A usage count and the usages shown when it is clicked, or the same search run again, need
no second search, and concurrent requests for the same targets share one. There is no
binding-resolution shortcut.
Popup and Find share persisted read/write toolbar switches. Both initially show;
turning the last one off automatically enables the other. Unknown and readWrite
@@ -76,7 +88,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.9.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.12.0.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
@@ -118,6 +130,9 @@ longer resolves every Spring Boot property again; its reproducible SHA-256 is
Version 1.9.0 adds the analysis-scope command to avoid redundant semantic queries;
its reproducible SHA-256 is
`ae04182d6a86dfdd6f6befaaeb28907fd9e4c022ceedb445f0b32ea917dca379`.
Version 1.12.0 caches usages answers until the Java model or an unsaved edit changes and adds
`openidea.workspace.coveredRoots`; its reproducible SHA-256 is
`c1bd28d7b956cb64af3e936aac0553413a5dc5fd373a043ddba003009e0ea783`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
Бінарний файл не відображається.
+3
Переглянути файл
@@ -4,6 +4,9 @@
<delegateCommandHandler class="ai.openidea.usages.CoveredFilesCommand">
<command id="openidea.workspace.coveredFiles"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.usages.CoveredRootsCommand">
<command id="openidea.workspace.coveredRoots"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.usages.UsagesCommand">
<command id="openidea.java.usages"/>
</delegateCommandHandler>
+51
Переглянути файл
@@ -0,0 +1,51 @@
package ai.openidea.usages;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.managers.ProjectsManager;
import org.eclipse.jdt.ls.core.internal.preferences.Preferences.SearchScope;
/**
* Directories whose Java files are all in the workspace's semantic source searches: source
* folders without inclusion or exclusion patterns that the search scope encloses. A client
* looking for files beyond that scope need not read the files under them.
*/
public final class CoveredRootsCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
var setting = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().getSearchScope();
var scope = SearchEngine.createJavaSearchScope(setting == SearchScope.main, projects,
IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS);
List<String> covered = new ArrayList<>();
for (IJavaProject project : projects) {
// The default project holds standalone open files, not an indexed source tree.
if (ProjectsManager.getDefaultProject().equals(project.getProject())) continue;
for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
if (monitor.isCanceled()) throw new OperationCanceledException();
if (root.getKind() != IPackageFragmentRoot.K_SOURCE || root.getResource() == null) continue;
IClasspathEntry entry = root.getRawClasspathEntry();
if (entry == null || entry.getExclusionPatterns().length > 0) continue;
// Maven projects include `**/*.java`: every Java file, like no pattern at all.
boolean allJava = true;
for (var pattern : entry.getInclusionPatterns()) allJava &= pattern.toString().equals("**/*.java");
if (!allJava) continue;
if (!scope.encloses(root)) continue;
var location = root.getResource().getLocationURI();
if (location != null) covered.add(location.toString());
}
}
return covered;
}
}
+157
Переглянути файл
@@ -0,0 +1,157 @@
package ai.openidea.usages;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.managers.ProjectsManager;
/**
* Answers of `openidea.java.usages` by search targets, kept until a Java element changes: the
* sources or unsaved edits of a compilation unit, or a project's classpath. A usage count and
* the usages shown when it is clicked, or the same search run again, then need no new search.
* Concurrent requests for the same targets share one search.
*/
final class UsageCache {
private static final int MAX_ENTRIES = 32, MAX_ROWS = 200_000;
/** Opening or closing an editor's working copy and AST-only reconciles change no usage. */
private static final int IGNORED_FLAGS = IJavaElementDelta.F_CHILDREN | IJavaElementDelta.F_PRIMARY_WORKING_COPY
| IJavaElementDelta.F_AST_AFFECTED | IJavaElementDelta.F_FINE_GRAINED;
private static final AtomicLong REVISION = new AtomicLong();
private record Entry(long revision, List<Map<String, Object>> rows) {}
private static final Map<String, Entry> DONE = new LinkedHashMap<>(16, 0.75f, true);
private static final Map<String, CompletableFuture<List<Map<String, Object>>>> RUNNING = new HashMap<>();
static {
JavaCore.addElementChangedListener(event -> {
if (affects(event.getDelta())) REVISION.incrementAndGet();
}, ElementChangedEvent.POST_CHANGE | ElementChangedEvent.POST_RECONCILE);
}
private UsageCache() {}
interface Search {
List<Map<String, Object>> run() throws Exception;
}
static boolean affects(IJavaElementDelta delta) {
// Decompiled library classes open as private working copies; searches never see them.
if (delta.getElement() instanceof ICompilationUnit unit && unit.getOwner() != null) return false;
// Files outside the source folders (opened to widen a search) join the default project
// while open: they are part of the key instead (`openContents`).
IJavaProject project = delta.getElement().getJavaProject();
if (project != null && standalone(project)) return false;
int flags = delta.getFlags() & ~IGNORED_FLAGS;
if (delta.getElement().getElementType() < IJavaElement.COMPILATION_UNIT) flags &= ~IJavaElementDelta.F_CONTENT;
if (delta.getKind() != IJavaElementDelta.CHANGED || flags != 0) return true;
for (IJavaElementDelta child : delta.getAffectedChildren()) if (affects(child)) return true;
return false;
}
static List<Map<String, Object>> get(String targets, IProgressMonitor monitor, Search search) throws Exception {
// Searches read unsaved editor contents, which change before the reconcile that reports them.
String key = targets + '|' + openContents(monitor);
while (true) {
long revision = REVISION.get();
CompletableFuture<List<Map<String, Object>>> running;
boolean owner = false;
synchronized (UsageCache.class) {
Entry done = DONE.get(key);
if (done != null && done.revision == revision) return done.rows;
running = RUNNING.get(key);
if (running == null) {
running = new CompletableFuture<>();
RUNNING.put(key, running);
owner = true;
}
}
if (owner) return search(key, revision, running, search);
// The same targets are searched for another request: its answer, or a new search
// when that one was cancelled, failed or saw a change.
while (true) {
if (monitor.isCanceled()) throw new OperationCanceledException();
try {
List<Map<String, Object>> rows = running.get(50, TimeUnit.MILLISECONDS);
if (REVISION.get() == revision) return rows;
break;
} catch (TimeoutException e) {
continue;
} catch (ExecutionException e) {
break;
}
}
}
}
private static boolean standalone(IJavaProject project) {
return ProjectsManager.getDefaultProject().equals(project.getProject());
}
/** A digest of the editors' unsaved contents and of the open files outside the source
* folders: merely opening or closing a file of the sources keeps it. */
private static String openContents(IProgressMonitor monitor) throws Exception {
Map<String, ICompilationUnit> copies = new TreeMap<>();
for (ICompilationUnit copy : JavaCore.getWorkingCopies(null)) copies.put(copy.getPrimary().getHandleIdentifier(), copy);
for (ICompilationUnit copy : JavaCore.getWorkingCopies(JavaLanguageServerPlugin.getInstance().getWorkingCopyOwner()))
copies.put(copy.getPrimary().getHandleIdentifier(), copy);
var digest = MessageDigest.getInstance("SHA-256");
for (var entry : copies.entrySet()) {
if (monitor.isCanceled()) throw new OperationCanceledException();
ICompilationUnit copy = entry.getValue();
if (!copy.hasUnsavedChanges() && !standalone(copy.getJavaProject())) continue;
digest.update(entry.getKey().getBytes(StandardCharsets.UTF_8));
String source = entry.getValue().getSource();
if (source != null) digest.update(source.getBytes(StandardCharsets.UTF_8));
}
return HexFormat.of().formatHex(digest.digest());
}
private static List<Map<String, Object>> search(String key, long revision,
CompletableFuture<List<Map<String, Object>>> running, Search search) throws Exception {
List<Map<String, Object>> rows;
try {
rows = List.copyOf(search.run());
} catch (Throwable e) {
synchronized (UsageCache.class) { RUNNING.remove(key); }
running.completeExceptionally(e);
throw e;
}
synchronized (UsageCache.class) {
RUNNING.remove(key);
if (REVISION.get() == revision && rows.size() <= MAX_ROWS) remember(key, new Entry(revision, rows));
}
running.complete(rows);
return rows;
}
private static void remember(String key, Entry entry) {
DONE.put(key, entry);
int rows = DONE.values().stream().mapToInt(e -> e.rows.size()).sum();
// Least recently used first; `get` on this access-ordered map would reorder it.
var oldest = DONE.entrySet().iterator();
while ((DONE.size() > MAX_ENTRIES || rows > MAX_ROWS) && oldest.hasNext()) {
var evicted = oldest.next();
if (evicted.getKey().equals(key)) continue;
rows -= evicted.getValue().rows.size();
oldest.remove();
}
}
}
+25 -4
Переглянути файл
@@ -92,13 +92,34 @@ public final class UsagesCommand implements IDelegateCommandHandler {
}
}
}
for (var target : plan.targets.values()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
add(search, target.element, target.kind(), target.declarations, results, monitor);
}
UsageCache.Search run = () -> respond(search, plan, results, monitor);
// Unverified builds answer partly through the native handler, before the plan.
return replicated && !plan.targets.isEmpty()
? UsageCache.get(cacheKey(plan, sources, preferences), monitor, run) : run.run();
} finally {
if (targetRoot != null) JDTUtils.discardClassFileWorkingCopy(targetRoot);
}
}
/** What a search depends on besides the Java model: its targets, scope and search settings. */
private static String cacheKey(SearchPlan plan, boolean sources,
org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager preferences) {
var settings = preferences.getPreferences();
StringBuilder key = new StringBuilder().append(sources).append('|').append(settings.getSearchScope())
.append('|').append(preferences.isClientSupportsClassFileContent() && settings.isIncludeDecompiledSources());
for (var target : plan.targets.values()) {
key.append('|').append(target.element.getHandleIdentifier()).append('#').append(target.kind())
.append('#').append(target.declarations);
}
return key.toString();
}
private static List<Map<String, Object>> respond(Search search, SearchPlan plan, Map<Location, String> results,
IProgressMonitor monitor) throws Exception {
for (var target : plan.targets.values()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
add(search, target.element, target.kind(), target.declarations, results, monitor);
}
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
List<Map<String, Object>> response = new ArrayList<>();
UsageAccess access = new UsageAccess(monitor, results);
+25
Переглянути файл
@@ -136,6 +136,31 @@ try:
line, text = next((i, t) for i, t in enumerate(source.splitlines()) if 'println' in t)
evidence['jdkSources'] = assert_sources(line, text.index('println'))
assert evidence['jdkSources'], 'no JDK method usages in the sources'
# Answers are reused until the sources change: an unsaved edit is seen at once, before its reconcile.
line, text = next((i, t) for i, t in enumerate(source.splitlines()) if 'private String name;' in t)
usages = lambda: request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),line,text.index('name'),False]})
getters = lambda rows: [r['kind'] for r in rows].count('getter')
first = usages()
assert usages() == first
edited = source.replace(' void calls(Bean b)', ' void more(Bean b) { b.getName(); }\n void calls(Bean b)')
send({'jsonrpc':'2.0','method':'textDocument/didChange','params':{'textDocument':{'uri':file.as_uri(),'version':2},'contentChanges':[{'text':edited}]}})
changed = usages()
assert getters(changed) == getters(first) + 1, (first, changed)
send({'jsonrpc':'2.0','method':'textDocument/didChange','params':{'textDocument':{'uri':file.as_uri(),'version':3},'contentChanges':[{'text':source}]}})
assert usages() == first
# The source folder holds only covered files; the folder beside it does not.
roots = request('workspace/executeCommand', {'command':'openidea.workspace.coveredRoots','arguments':[]})
assert [pathlib.Path(r.replace('file:', '', 1)).resolve() for r in roots] == [(project / 'src').resolve()], roots
evidence['coveredRoots'] = roots
# A file outside the source folders, opened and closed to widen a search, leaves the answer as it was.
extra = project / 'other' / 'Extra.java'
extra.parent.mkdir()
extra.write_text('class Extra { void use(Bean b) { b.getName(); } }\n')
send({'jsonrpc':'2.0','method':'textDocument/didOpen','params':{'textDocument':{'uri':extra.as_uri(),'languageId':'java','version':1,'text':extra.read_text()}}})
widened = usages()
send({'jsonrpc':'2.0','method':'textDocument/didClose','params':{'textDocument':{'uri':extra.as_uri()}}})
assert usages() == first
evidence['cached'] = {'first':first, 'edited':changed, 'widened':widened}
# Respect the existing global preference: the command must not switch it on.
send({'jsonrpc':'2.0','method':'workspace/didChangeConfiguration','params':{'settings':{'java':{'references':{'includeAccessors':False}}}}})
disabled = request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),3,19,False]})
+3
Переглянути файл
@@ -43,6 +43,9 @@ contentProvider = { preferred = "fernflowerContentProvider" }
maven = { downloadSources = true, updateSnapshots = false }
eclipse = { downloadSources = true }
references = { includeDecompiledSources = true }
# The editor's usage lenses count usages; the server's own lenses would search every
# declaration of the file again, all at once (on by default in JDT LS).
referencesCodeLens = { enabled = false }
signatureHelp = { enabled = true }
symbols = { includeGeneratedCode = true }
configuration = { updateBuildConfiguration = "automatic" }
+1
Переглянути файл
@@ -73,6 +73,7 @@
"tabs.openSmallMs": 100,
"tabs.switchP95Ms": 33,
"tabs.switcherP50Ms": 33,
"tabs.viewsRebuilt": 0,
"agentTabs.conversationNodes": 20000,
"agentTabs.rowsAlwaysRendered": 0,
+16 -2
Переглянути файл
@@ -449,12 +449,24 @@ const tabs: Scenario = {
await h.openFile(`${ROOT}/src/tabs/${name}`, tsSource(2_000, `tab-${i}`));
}
const switches: number[] = [];
// Recently shown tabs keep their editor view: showing one again must not build a new one.
let viewsRebuilt = 0;
let switchWork = await h.counters();
for (let round = 0; round < 3; round++) {
if (round === 1) switchWork = await h.counters();
for (let i = 0; i < names.length; i++) {
const tab = h.page.getByRole("tab", { name: names[i], exact: true });
switches.push(await h.measure(() => tab.click(), ".cm-content", `// tab-${i}`));
const fresh = await h.page.evaluate(() => {
const view = document.querySelector("[data-editor-host] .cm-editor") as { perfSeen?: boolean } | null;
if (!view || view.perfSeen) return false;
view.perfSeen = true;
return true;
});
if (round > 0 && fresh) viewsRebuilt++;
}
}
const work = Harness.delta(switchWork, await h.counters());
// The Switcher (Ctrl+Tab) back and forth between the two most recent tabs.
const before = await h.counters();
const switcher: number[] = [];
@@ -463,12 +475,14 @@ const tabs: Scenario = {
switcher.push(await h.measure(() => h.pressAction("navigate.switcher"), ".cm-content", `// tab-${tag}`));
await h.page.waitForTimeout(150);
}
const work = Harness.delta(before, await h.counters());
const switcherWork = Harness.delta(before, await h.counters());
return {
openSmallMs,
...latencySummary(switches, "switch"),
switchMainThreadMs: work.taskMs / (names.length * 2),
viewsRebuilt,
...latencySummary(switcher, "switcher"),
switcherMainThreadMs: work.taskMs / switcher.length,
switcherMainThreadMs: switcherWork.taskMs / switcher.length,
};
},
};
+23 -2
Переглянути файл
@@ -3,8 +3,8 @@
use crate::state::AppState;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_docker::{
ComposeOp, ContainerOp, DockerEndpoint, DockerEvent, DockerLogLine, DockerObject, DockerRegistry, DockerSettings,
DockerSnapshot, PruneTarget, RegistryAuth,
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
};
use tauri::State;
use tauri::ipc::Channel;
@@ -56,6 +56,27 @@ pub async fn docker_inspect(endpoint: DockerEndpoint, object: DockerObject, id:
blocking(move || ide_docker::inspect(&endpoint, object, &id)).await
}
/// Layers of an image (`docker image history`).
#[tauri::command]
#[specta::specta]
pub async fn docker_image_history(endpoint: DockerEndpoint, id: String) -> IdeResult<Vec<DockerImageLayer>> {
blocking(move || ide_docker::image_history(&endpoint, &id)).await
}
/// Processes running inside a container (`docker top`).
#[tauri::command]
#[specta::specta]
pub async fn docker_container_top(endpoint: DockerEndpoint, id: String) -> IdeResult<DockerProcessList> {
blocking(move || ide_docker::container_top(&endpoint, &id)).await
}
/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`).
#[tauri::command]
#[specta::specta]
pub async fn docker_container_stats(endpoint: DockerEndpoint, id: String) -> IdeResult<DockerContainerStats> {
blocking(move || ide_docker::container_stats(&endpoint, &id)).await
}
/// Streams a container's log lines until it stops or the request is cancelled.
#[tauri::command]
#[specta::specta]
+4
Переглянути файл
@@ -447,6 +447,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
window::window_is_fullscreen,
window_drag::window_start_drag,
window::window_take_launch,
window::window_complete_launch,
window::window_close_context,
window::window_open_projects,
window::app_quit,
@@ -563,6 +564,9 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
docker::docker_container_op,
docker::docker_remove,
docker::docker_inspect,
docker::docker_image_history,
docker::docker_container_top,
docker::docker_container_stats,
docker::docker_logs,
docker::docker_events,
docker::docker_pull,
+8
Переглянути файл
@@ -163,6 +163,14 @@ pub fn window_take_launch(window: WebviewWindow, windows: State<'_, WindowsState
windows.take_launch(window.label())
}
/// Release the opening window's reservation after navigation or cancellation.
#[tauri::command]
#[specta::specta]
pub fn window_complete_launch(window: WebviewWindow, windows: State<'_, WindowsState>) -> IdeResult<()> {
windows.complete_launch(window.label());
Ok(())
}
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct OpenProject {
+12 -15
Переглянути файл
@@ -102,7 +102,7 @@ pub fn run() {
#[cfg(debug_assertions)]
export_bindings(&builder);
let app = tauri::Builder::default();
let app = tauri::Builder::default().manage(WindowsState::default());
// Single instance first: a second launch focuses this one and opens its path argument.
// Debug builds have a separate identifier per worktree.
let app = app.plugin(tauri_plugin_single_instance::init(windows::on_second_instance));
@@ -176,26 +176,22 @@ pub fn run() {
.setup(move |app| {
builder.mount_events(app);
let state = AppState::new(app.handle().clone())?;
let windows = WindowsState::default();
let windows = app.state::<WindowsState>();
if let Ok(cwd) = std::env::current_dir() {
let args = std::env::args().collect::<Vec<_>>();
match windows::cli_launch(&args, &cwd) {
Some(windows::CliLaunch::Path(path)) => {
windows::remember_cli_position(&windows, &args, &path);
windows.set_launch("main", windows::path_launch(path));
}
// `openidea diff a.txt b.txt`: the main window opens the pair in the diff viewer.
Some(windows::CliLaunch::Diff(diff)) => {
windows.set_launch("main", windows::Launch { diff: Some(Box::new(diff)), ..Default::default() });
}
None => {}
match windows::cli_launch(&std::env::args().collect::<Vec<_>>(), &cwd) {
Ok(Some(launch)) => windows.set_launch("main", launch),
Ok(None) => {}
Err(error) => windows::report_cli_error(app.handle(), error),
}
}
let menu_state = menu::MenuState::default();
menu::install(app.handle(), &menu_state, &state.recent.list());
app.manage(state);
commands::mcp::apply(&app.state::<AppState>());
app.manage(windows);
#[cfg(windows)]
if let Err(error) = windows::allow_external_launches(app.handle()) {
windows::report_cli_error(app.handle(), error);
}
app.manage(application_focus::ApplicationFocus::default());
#[cfg(target_os = "macos")]
macos::intercept_system_quit(app.handle());
@@ -212,6 +208,7 @@ pub fn run() {
}
app.on_menu_event(on_menu_event);
windows::create_main_window(app.handle())?;
windows::ready_for_cli(app.handle());
jump_list::refresh(app.handle(), app.state::<AppState>().recent.list());
Ok(())
})
@@ -262,7 +259,7 @@ pub fn run() {
#[cfg(target_os = "macos")]
if let tauri::RunEvent::Opened { urls } = &event {
let paths = windows::opened_paths(urls);
if app.try_state::<WindowsState>().is_some() {
if app.try_state::<AppState>().is_some() {
windows::open_paths(app, paths);
} else {
early_opens.lock().get_or_insert_default().extend(paths);
+19
Переглянути файл
@@ -395,6 +395,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
sub("statusBarWidgets", "Status Bar Widgets", vec![Entry::Dynamic(DYNAMIC_STATUS_BAR_WIDGETS)]),
],
),
sub("activeEditor", "Active Editor", vec![act("editor.toggleSoftWrap", "Soft-Wrap")]),
SEP,
act("code.quickDefinition", "Quick Definition"),
act("code.quickTypeDefinition", "Quick Type Definition"),
@@ -1652,6 +1653,24 @@ mod tests {
}
}
#[test]
fn soft_wrap_is_available_under_view_active_editor_on_every_os() {
for os in ALL_OS {
let menus = spec(os);
let Entry::Submenu { children: view, .. } =
menus.iter().find(|e| matches!(e, Entry::Submenu { id: "view", .. })).unwrap()
else {
panic!("View menu missing")
};
let Entry::Submenu { children: active, .. } =
view.iter().find(|e| matches!(e, Entry::Submenu { id: "activeEditor", .. })).unwrap()
else {
panic!("Active Editor menu missing")
};
assert!(action_ids(active).contains(&"editor.toggleSoftWrap"), "{os:?}");
}
}
#[test]
fn unchanged_menu_config_is_not_rebuilt() {
let state = MenuState::default();
File diff suppressed because it is too large. Load diff
+227
Переглянути файл
@@ -0,0 +1,227 @@
//! External file-opening arguments, shared by cold and second-instance launches.
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
/// Guarded by WindowsState's mutex. One worker drains requests in arrival order.
#[derive(Default)]
pub struct Queue {
requests: VecDeque<(Vec<String>, String)>,
ready: bool,
running: bool,
}
impl Queue {
pub fn push(&mut self, args: Vec<String>, cwd: String) -> bool {
self.requests.push_back((args, cwd));
self.start()
}
pub fn ready(&mut self) -> bool {
self.ready = true;
self.start()
}
fn start(&mut self) -> bool {
if self.ready && !self.running && !self.requests.is_empty() {
self.running = true;
true
} else {
false
}
}
pub fn next(&mut self) -> Option<(Vec<String>, String)> {
let request = self.requests.pop_front();
if request.is_none() {
self.running = false;
}
request
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Request {
pub path: Option<PathBuf>,
pub file: Option<PathBuf>,
pub position: Option<(u32, u32)>,
}
/// Preserve the application's `diff` subcommand; a non-leading `diff` remains a path.
pub fn diff_paths(args: &[String], cwd: &Path) -> Option<Vec<PathBuf>> {
if args.get(1).map(String::as_str) != Some("diff") {
return None;
}
let mut paths = Vec::new();
let mut args = args.iter().skip(2);
let mut positional = false;
while let Some(arg) = args.next() {
if !positional && arg == "--" {
positional = true;
} else if !positional && matches!(arg.as_str(), "--line" | "--column") {
args.next();
} else if !arg.is_empty() && (positional || !arg.starts_with('-')) {
paths.push(absolute(cwd, Path::new(arg)));
}
}
Some(paths)
}
pub fn parse(args: &[String], cwd: &Path) -> Result<Request, String> {
let (mut path, mut file, mut line, mut column) = (None, None, None, None);
let mut positional = false;
let mut args = args.iter().skip(1);
while let Some(arg) = args.next() {
if !positional && arg == "--" {
positional = true;
continue;
}
let (flag, inline) = arg.split_once('=').map_or((arg.as_str(), None), |(k, v)| (k, Some(v)));
if !positional && matches!(flag, "--file" | "--line" | "--column") {
let value = inline
.or_else(|| args.next().map(String::as_str))
.filter(|s| !s.is_empty() && !s.starts_with("--"))
.ok_or_else(|| format!("{flag} requires a value"))?;
match flag {
"--file" => {
if file.replace(PathBuf::from(value)).is_some() {
return Err("--file may only be supplied once".into());
}
}
"--line" => line = coordinate(flag, value)?,
"--column" => column = coordinate(flag, value)?,
_ => unreachable!(),
}
} else if !arg.is_empty() && (positional || (!arg.starts_with('-') && !arg.starts_with("psn_"))) {
// Preserve ordinary CLI opening: the first positional path is the target.
if path.is_none() {
path = Some(absolute(cwd, Path::new(arg)));
}
}
}
let base = path.as_deref().filter(|p| p.is_dir()).unwrap_or(cwd);
let file = file.map(|p| absolute(base, &p));
Ok(Request { path, file, position: line.map(|l| (l - 1, column.unwrap_or(1) - 1)) })
}
fn absolute(base: &Path, path: &Path) -> PathBuf {
if path.is_absolute() { path.to_owned() } else { base.join(path) }
}
fn coordinate(flag: &str, value: &str) -> Result<Option<u32>, String> {
// Unity supplies 0/-1 when an asset has no source position.
match value.parse::<i64>() {
Ok(-1 | 0) => Ok(None),
Ok(n @ 1..=4294967295) => Ok(Some(n as u32)),
_ => Err(format!("{flag} expects a 1-based position (or 0/-1 for an unknown position)")),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn request(args: &[&str]) -> Result<Request, String> {
parse(
&std::iter::once("openidea").chain(args.iter().copied()).map(str::to_owned).collect::<Vec<_>>(),
Path::new("/work"),
)
}
#[test]
fn diff_paths_keep_flags_out_and_honor_end_of_options() {
let args = |tail: &[&str]| {
std::iter::once("openidea").chain(tail.iter().copied()).map(str::to_owned).collect::<Vec<_>>()
};
let cwd = Path::new("/work");
assert_eq!(
diff_paths(&args(&["diff", "--line", "12", "--column=3", "a.txt", "b.txt"]), cwd),
Some(vec![cwd.join("a.txt"), cwd.join("b.txt")])
);
assert_eq!(
diff_paths(&args(&["diff", "--", "-a.txt", "-b.txt"]), cwd),
Some(vec![cwd.join("-a.txt"), cwd.join("-b.txt")])
);
assert_eq!(diff_paths(&args(&["--", "diff"]), cwd), None);
assert_eq!(diff_paths(&args(&["project", "diff"]), cwd), None);
assert_eq!(diff_paths(&args(&["diff"]), cwd), Some(vec![]));
}
#[test]
fn queued_launches_stay_in_order_across_startup_and_later_arrivals() {
let mut queue = Queue::default();
assert!(!queue.push(vec!["first".into()], "cwd1".into()));
assert!(!queue.push(vec!["second".into()], "cwd2".into()));
assert!(queue.ready());
assert!(!queue.push(vec!["third".into()], "cwd3".into()));
assert_eq!(queue.next(), Some((vec!["first".into()], "cwd1".into())));
assert_eq!(queue.next(), Some((vec!["second".into()], "cwd2".into())));
assert_eq!(queue.next(), Some((vec!["third".into()], "cwd3".into())));
assert_eq!(queue.next(), None);
assert!(queue.push(vec!["later".into()], "cwd4".into()));
assert!(!queue.ready());
assert_eq!(queue.next(), Some((vec!["later".into()], "cwd4".into())));
}
#[test]
fn named_files_positions_and_unicode() {
for args in [
vec!["--file", "Game Scripts/角色.cs", "--line", "42", "--column", "7"],
vec!["--column=7", "--line=42", "--file=Game Scripts/角色.cs"],
] {
assert_eq!(
request(&args).unwrap(),
Request {
path: None,
file: Some(PathBuf::from("/work/Game Scripts/角色.cs")),
position: Some((41, 6)),
}
);
}
assert_eq!(request(&["--line=5", "file.cs"]).unwrap().position, Some((4, 0)));
}
#[test]
fn unknown_positions_and_malformed_flags() {
for value in ["0", "-1"] {
assert_eq!(request(&["--file", "a.cs", "--line", value, "--column", value]).unwrap().position, None);
assert_eq!(request(&["--file", "a.cs", "--line", "5", "--column", value]).unwrap().position, Some((4, 0)));
}
for args in [
vec!["--file"],
vec!["--file="],
vec!["--file", "--line", "2"],
vec!["--line", "bad", "a.cs"],
vec!["--line=4294967296", "a.cs"],
vec!["--column=-2", "a.cs"],
vec!["--file=a.cs", "--file=b.cs"],
] {
assert!(request(&args).is_err(), "{args:?}");
}
}
#[test]
fn positional_opening_and_end_of_options() {
assert_eq!(request(&["--verbose", "proj"]).unwrap().path, Some(PathBuf::from("/work/proj")));
assert_eq!(request(&["--", "-notes.txt"]).unwrap().path, Some(PathBuf::from("/work/-notes.txt")));
assert_eq!(request(&["-psn_0_123"]).unwrap(), Request::default());
assert_eq!(request(&["--column", "7", "a.cs"]).unwrap().position, None);
}
#[test]
fn project_relative_file_is_independent_of_invocation_directory() {
let project = std::env::temp_dir();
let args = vec!["openidea".into(), project.to_string_lossy().into_owned(), "--file=Assets/A.cs".into()];
let r = parse(&args, Path::new("/unrelated")).unwrap();
assert_eq!(r.path, Some(project.clone()));
assert_eq!(r.file, Some(project.join("Assets/A.cs")));
}
#[test]
#[cfg(windows)]
fn windows_absolute_paths_are_not_prefixed() {
for file in [r"D:\Game Scripts\角色.cs", r"\\server\share\Game\A.cs", "D:/Game Scripts/A.cs"] {
assert_eq!(request(&["--file", file]).unwrap().file, Some(PathBuf::from(file)));
}
}
}
+41
Переглянути файл
@@ -0,0 +1,41 @@
//! Receive external file-open requests when the editor has a higher integrity level.
use ide_core::{IdeError, IdeResult};
use tauri::AppHandle;
use windows_sys::Win32::UI::WindowsAndMessaging::{
ChangeWindowMessageFilterEx, FindWindowW, GetWindowThreadProcessId, MSGFLT_ALLOW, WM_COPYDATA,
};
/// Called after the single-instance plugin creates its receiver and app state is ready.
pub fn allow_external_launches(app: &AppHandle) -> IdeResult<()> {
// tauri-plugin-single-instance names its receiver using the configured identifier,
// including the worktree suffix in debug builds. Never change a webview's filter.
let identifier = &app.config().identifier;
let class: Vec<u16> = format!("{identifier}-sic").encode_utf16().chain(Some(0)).collect();
let title: Vec<u16> = format!("{identifier}-siw").encode_utf16().chain(Some(0)).collect();
// SAFETY: both strings are NUL-terminated. Check ownership before allowing the
// plugin's argument-transfer message on this one window.
unsafe {
let receiver = FindWindowW(class.as_ptr(), title.as_ptr());
if receiver.is_null() {
return Err(IdeError::unavailable("Cannot find the single-instance receiver for external editor requests"));
}
let mut owner = 0;
if GetWindowThreadProcessId(receiver, &mut owner) == 0 {
return Err(IdeError::unavailable(format!(
"Cannot identify the single-instance receiver: {}",
std::io::Error::last_os_error()
)));
}
if owner != std::process::id() {
return Err(IdeError::unavailable("The single-instance receiver belongs to another process"));
}
if ChangeWindowMessageFilterEx(receiver, WM_COPYDATA, MSGFLT_ALLOW, std::ptr::null_mut()) == 0 {
return Err(IdeError::unavailable(format!(
"Cannot enable external editor requests: {}. Run Unity and OpenIDEA with the same permissions.",
std::io::Error::last_os_error()
)));
}
}
Ok(())
}
+1
Переглянути файл
@@ -20,6 +20,7 @@
"windows": {
"nsis": {
"installMode": "both",
"template": "windows/installer.nsi",
"installerIcon": "icons/icon.ico",
"uninstallerIcon": "icons/icon.ico"
}
+997
Переглянути файл
@@ -0,0 +1,997 @@
; Based on tauri-bundler 2.10.3 (MIT OR Apache-2.0).
; https://github.com/tauri-apps/tauri/blob/tauri-bundler-v2.10.3/crates/tauri-bundler/src/bundle/windows/nsis/installer.nsi
; Preserve legacy install scope through UninstallString; keep the rest in sync with upstream.
Unicode true
ManifestDPIAware true
; Add in `dpiAwareness` `PerMonitorV2` to manifest for Windows 10 1607+ (note this should not affect lower versions since they should be able to ignore this and pick up `dpiAware` `true` set by `ManifestDPIAware true`)
; Currently undocumented on NSIS's website but is in the Docs folder of source tree, see
; https://github.com/kichik/nsis/blob/5fc0b87b819a9eec006df4967d08e522ddd651c9/Docs/src/attributes.but#L286-L300
; https://github.com/tauri-apps/tauri/pull/10106
ManifestDPIAwareness PerMonitorV2
!if "{{compression}}" == "none"
SetCompress off
!else
; Set the compression algorithm. We default to LZMA.
SetCompressor /SOLID "{{compression}}"
!endif
; Keep above !include to stay ahead of any plugin command
; see https://github.com/tauri-apps/tauri/pull/15422#discussion_r3289239624
{{#if signed_plugins_path}}
!addplugindir "{{signed_plugins_path}}"
{{/if}}
!include MUI2.nsh
!include FileFunc.nsh
!include x64.nsh
!include WordFunc.nsh
!include "utils.nsh"
!include "FileAssociation.nsh"
!include "Win\COM.nsh"
!include "Win\Propkey.nsh"
!include "Win\RestartManager.nsh"
!include "StrFunc.nsh"
${StrCase}
${StrLoc}
{{#if installer_hooks}}
!include "{{installer_hooks}}"
{{/if}}
!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
!define MANUFACTURER "{{manufacturer}}"
!define PRODUCTNAME "{{product_name}}"
!define VERSION "{{version}}"
!define VERSIONWITHBUILD "{{version_with_build}}"
!define HOMEPAGE "{{homepage}}"
!define INSTALLMODE "{{install_mode}}"
!define LICENSE "{{license}}"
!define INSTALLERICON "{{installer_icon}}"
!define SIDEBARIMAGE "{{sidebar_image}}"
!define HEADERIMAGE "{{header_image}}"
!define UNINSTALLERICON "{{uninstaller_icon}}"
!define UNINSTALLERHEADERIMAGE "{{uninstaller_header_image}}"
!define MAINBINARYNAME "{{main_binary_name}}"
!define MAINBINARYSRCPATH "{{main_binary_path}}"
!define BUNDLEID "{{bundle_id}}"
!define COPYRIGHT "{{copyright}}"
!define OUTFILE "{{out_file}}"
!define ARCH "{{arch}}"
!define ADDITIONALPLUGINSPATH "{{additional_plugins_path}}"
!define ALLOWDOWNGRADES "{{allow_downgrades}}"
!define DISPLAYLANGUAGESELECTOR "{{display_language_selector}}"
!define INSTALLWEBVIEW2MODE "{{install_webview2_mode}}"
!define WEBVIEW2INSTALLERARGS "{{webview2_installer_args}}"
!define WEBVIEW2BOOTSTRAPPERPATH "{{webview2_bootstrapper_path}}"
!define WEBVIEW2INSTALLERPATH "{{webview2_installer_path}}"
!define MINIMUMWEBVIEW2VERSION "{{minimum_webview2_version}}"
!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}"
!define MANUKEY "Software\${MANUFACTURER}"
!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}"
!define UNINSTALLERSIGNCOMMAND "{{uninstaller_sign_cmd}}"
!define ESTIMATEDSIZE "{{estimated_size}}"
!define STARTMENUFOLDER "{{start_menu_folder}}"
Var PassiveMode
Var UpdateMode
Var NoShortcutMode
Var WixMode
Var OldMainBinaryName
Name "${PRODUCTNAME}"
BrandingText "${COPYRIGHT}"
OutFile "${OUTFILE}"
; We don't actually use this value as default install path,
; it's just for nsis to append the product name folder in the directory selector
; https://nsis.sourceforge.io/Reference/InstallDir
!define PLACEHOLDER_INSTALL_DIR "placeholder\${PRODUCTNAME}"
InstallDir "${PLACEHOLDER_INSTALL_DIR}"
VIProductVersion "${VERSIONWITHBUILD}"
VIAddVersionKey "ProductName" "${PRODUCTNAME}"
VIAddVersionKey "FileDescription" "${PRODUCTNAME}"
VIAddVersionKey "LegalCopyright" "${COPYRIGHT}"
VIAddVersionKey "FileVersion" "${VERSION}"
VIAddVersionKey "ProductVersion" "${VERSION}"
# additional plugins
!addplugindir "${ADDITIONALPLUGINSPATH}"
; Uninstaller signing command
!if "${UNINSTALLERSIGNCOMMAND}" != ""
!uninstfinalize '${UNINSTALLERSIGNCOMMAND}'
!endif
; Handle install mode, `perUser`, `perMachine` or `both`
!if "${INSTALLMODE}" == "perMachine"
RequestExecutionLevel admin
!endif
!if "${INSTALLMODE}" == "currentUser"
RequestExecutionLevel user
!endif
!if "${INSTALLMODE}" == "both"
!define MULTIUSER_MUI
!define MULTIUSER_INSTALLMODE_INSTDIR "${PRODUCTNAME}"
!define MULTIUSER_INSTALLMODE_COMMANDLINE
!if "${ARCH}" == "x64"
!define MULTIUSER_USE_PROGRAMFILES64
!else if "${ARCH}" == "arm64"
!define MULTIUSER_USE_PROGRAMFILES64
!endif
!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}"
!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "UninstallString"
!define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME
!define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation
!define MULTIUSER_EXECUTIONLEVEL Highest
!include MultiUser.nsh
!endif
; Installer icon
!if "${INSTALLERICON}" != ""
!define MUI_ICON "${INSTALLERICON}"
!endif
; Installer sidebar image
!if "${SIDEBARIMAGE}" != ""
!define MUI_WELCOMEFINISHPAGE_BITMAP "${SIDEBARIMAGE}"
!endif
; Enable header images for installer and uninstaller pages when either image is configured.
!if "${HEADERIMAGE}" != ""
!define MUI_HEADERIMAGE
!else if "${UNINSTALLERHEADERIMAGE}" != ""
!define MUI_HEADERIMAGE
!endif
; Installer header image
!if "${HEADERIMAGE}" != ""
!define MUI_HEADERIMAGE_BITMAP "${HEADERIMAGE}"
!endif
; Uninstaller header image
!if "${UNINSTALLERHEADERIMAGE}" != ""
!define MUI_HEADERIMAGE_UNBITMAP "${UNINSTALLERHEADERIMAGE}"
!endif
; Uninstaller icon
!if "${UNINSTALLERICON}" != ""
!define MUI_UNICON "${UNINSTALLERICON}"
!endif
; Define registry key to store installer language
!define MUI_LANGDLL_REGISTRY_ROOT "HKCU"
!define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}"
!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language"
; Installer pages, must be ordered as they appear
; 1. Welcome Page
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MUI_PAGE_WELCOME
; 2. License Page (if defined)
!if "${LICENSE}" != ""
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MUI_PAGE_LICENSE "${LICENSE}"
!endif
; 3. Install mode (if it is set to `both`)
!if "${INSTALLMODE}" == "both"
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MULTIUSER_PAGE_INSTALLMODE
!endif
; 4. Custom page to ask user if he wants to reinstall/uninstall
; only if a previous installation was detected
Var ReinstallPageCheck
Page custom PageReinstall PageLeaveReinstall
Function PageReinstall
; Uninstall previous WiX installation if exists.
;
; A WiX installer stores the installation info in registry
; using a UUID and so we have to loop through all keys under
; `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`
; and check if `DisplayName` and `Publisher` keys match ${PRODUCTNAME} and ${MANUFACTURER}
;
; This has a potential issue that there maybe another installation that matches
; our ${PRODUCTNAME} and ${MANUFACTURER} but wasn't installed by our WiX installer,
; however, this should be fine since the user will have to confirm the uninstallation
; and they can chose to abort it if doesn't make sense.
StrCpy $0 0
wix_loop:
EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0
StrCmp $1 "" wix_loop_done ; Exit loop if there is no more keys to loop on
IntOp $0 $0 + 1
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName"
ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher"
StrCmp "$R0$R1" "${PRODUCTNAME}${MANUFACTURER}" 0 wix_loop
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "UninstallString"
${StrCase} $R1 $R0 "L"
${StrLoc} $R0 $R1 "msiexec" ">"
StrCmp $R0 0 0 wix_loop_done
StrCpy $WixMode 1
StrCpy $R6 "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1"
Goto compare_version
wix_loop_done:
; Check if there is an existing installation, if not, abort the reinstall page
ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
${IfThen} "$R0$R1" == "" ${|} Abort ${|}
; Compare this installar version with the existing installation
; and modify the messages presented to the user accordingly
compare_version:
StrCpy $R4 "$(older)"
${If} $WixMode = 1
ReadRegStr $R0 HKLM "$R6" "DisplayVersion"
${Else}
ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"
${EndIf}
${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|}
nsis_tauri_utils::SemverCompare "${VERSION}" $R0
Pop $R0
; Reinstalling the same version
${If} $R0 = 0
StrCpy $R1 "$(alreadyInstalledLong)"
StrCpy $R2 "$(addOrReinstall)"
StrCpy $R3 "$(uninstallApp)"
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(chooseMaintenanceOption)"
; Upgrading
${ElseIf} $R0 = 1
StrCpy $R1 "$(olderOrUnknownVersionInstalled)"
StrCpy $R2 "$(uninstallBeforeInstalling)"
StrCpy $R3 "$(dontUninstall)"
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
; Downgrading
${ElseIf} $R0 = -1
StrCpy $R1 "$(newerVersionInstalled)"
StrCpy $R2 "$(uninstallBeforeInstalling)"
!if "${ALLOWDOWNGRADES}" == "true"
StrCpy $R3 "$(dontUninstall)"
!else
StrCpy $R3 "$(dontUninstallDowngrade)"
!endif
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
${Else}
Abort
${EndIf}
; Skip showing the page if passive
;
; Note that we don't call this earlier at the beginning
; of this function because we need to populate some variables
; related to current installed version if detected and whether
; we are downgrading or not.
${If} $PassiveMode = 1
Call PageLeaveReinstall
${Else}
nsDialogs::Create 1018
Pop $R4
${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|}
${NSD_CreateLabel} 0 0 100% 24u $R1
Pop $R1
${NSD_CreateRadioButton} 30u 50u -30u 8u $R2
Pop $R2
${NSD_OnClick} $R2 PageReinstallUpdateSelection
${NSD_CreateRadioButton} 30u 70u -30u 8u $R3
Pop $R3
; Disable this radio button if downgrading and downgrades are disabled
!if "${ALLOWDOWNGRADES}" == "false"
${IfThen} $R0 = -1 ${|} EnableWindow $R3 0 ${|}
!endif
${NSD_OnClick} $R3 PageReinstallUpdateSelection
; Check the first radio button if this the first time
; we enter this page or if the second button wasn't
; selected the last time we were on this page
${If} $ReinstallPageCheck <> 2
SendMessage $R2 ${BM_SETCHECK} ${BST_CHECKED} 0
${Else}
SendMessage $R3 ${BM_SETCHECK} ${BST_CHECKED} 0
${EndIf}
${NSD_SetFocus} $R2
nsDialogs::Show
${EndIf}
FunctionEnd
Function PageReinstallUpdateSelection
${NSD_GetState} $R2 $R1
${If} $R1 == ${BST_CHECKED}
StrCpy $ReinstallPageCheck 1
${Else}
StrCpy $ReinstallPageCheck 2
${EndIf}
FunctionEnd
Function PageLeaveReinstall
${NSD_GetState} $R2 $R1
; If migrating from Wix, always uninstall
${If} $WixMode = 1
Goto reinst_uninstall
${EndIf}
; In update mode, always proceeds without uninstalling
${If} $UpdateMode = 1
Goto reinst_done
${EndIf}
; $R0 holds whether same(0)/upgrading(1)/downgrading(-1) version
; $R1 holds the radio buttons state:
; 1 => first choice was selected
; 0 => second choice was selected
${If} $R0 = 0 ; Same version, proceed
${If} $R1 = 1 ; User chose to add/reinstall
Goto reinst_done
${Else} ; User chose to uninstall
Goto reinst_uninstall
${EndIf}
${ElseIf} $R0 = 1 ; Upgrading
${If} $R1 = 1 ; User chose to uninstall
Goto reinst_uninstall
${Else}
Goto reinst_done ; User chose NOT to uninstall
${EndIf}
${ElseIf} $R0 = -1 ; Downgrading
${If} $R1 = 1 ; User chose to uninstall
Goto reinst_uninstall
${Else}
Goto reinst_done ; User chose NOT to uninstall
${EndIf}
${EndIf}
reinst_uninstall:
HideWindow
ClearErrors
${If} $WixMode = 1
ReadRegStr $R1 HKLM "$R6" "UninstallString"
ExecWait '$R1' $0
${Else}
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
ExecWait '$R1' $0
${EndIf}
BringToFront
${IfThen} ${Errors} ${|} StrCpy $0 2 ${|} ; ExecWait failed, set fake exit code
${If} $0 <> 0
${OrIf} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe"
; User cancelled wix uninstaller? return to select un/reinstall page
${If} $WixMode = 1
${AndIf} $0 = 1602
Abort
${EndIf}
; User cancelled NSIS uninstaller? return to select un/reinstall page
${If} $0 = 1
Abort
${EndIf}
; Other errors? show generic error message and return to select un/reinstall page
MessageBox MB_ICONEXCLAMATION "$(unableToUninstall)"
Abort
${EndIf}
; The NSIS uninstaller was run in place (`_?=`), so it cannot delete itself
; and the install directory, clean them up here once the uninstall succeeded
; https://nsis.sourceforge.io/Docs/Chapter3.html#:~:text=path%20contains%20spaces.-,3.2.3%20Examples,-installer.exe%20/NCRC
${If} $WixMode = 0
${AndIf} $4 != ""
Delete "$4\uninstall.exe"
RMDir "$4"
${EndIf}
reinst_done:
FunctionEnd
; 5. Choose install directory page
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MUI_PAGE_DIRECTORY
; 6. Start menu shortcut page
Var AppStartMenuFolder
!if "${STARTMENUFOLDER}" != ""
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!define MUI_STARTMENUPAGE_DEFAULTFOLDER "${STARTMENUFOLDER}"
!else
!define MUI_PAGE_CUSTOMFUNCTION_PRE Skip
!endif
!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder
; 7. Installation page
!insertmacro MUI_PAGE_INSTFILES
; 8. Finish page
;
; Don't auto jump to finish page after installation page,
; because the installation page has useful info that can be used debug any issues with the installer.
!define MUI_FINISHPAGE_NOAUTOCLOSE
; Use show readme button in the finish page as a button create a desktop shortcut
!define MUI_FINISHPAGE_SHOWREADME
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)"
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateOrUpdateDesktopShortcut
; Show run app after installation.
!define MUI_FINISHPAGE_RUN
!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MUI_PAGE_FINISH
Function RunMainBinary
nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" ""
FunctionEnd
; Uninstaller Pages
; 1. Confirm uninstall page
Var DeleteAppDataCheckbox
Var DeleteAppDataCheckboxState
!define /ifndef WS_EX_LAYOUTRTL 0x00400000
!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow
Function un.ConfirmShow ; Add add a `Delete app data` check box
; $1 inner dialog HWND
; $2 window DPI
; $3 style
; $4 x
; $5 y
; $6 width
; $7 height
FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog
System::Call "user32::GetDpiForWindow(p r1) i .r2"
${If} $(^RTL) = 1
StrCpy $3 "${__NSD_CheckBox_EXSTYLE} | ${WS_EX_LAYOUTRTL}"
IntOp $4 50 * $2
${Else}
StrCpy $3 "${__NSD_CheckBox_EXSTYLE}"
IntOp $4 0 * $2
${EndIf}
IntOp $5 100 * $2
IntOp $6 400 * $2
IntOp $7 25 * $2
IntOp $4 $4 / 96
IntOp $5 $5 / 96
IntOp $6 $6 / 96
IntOp $7 $7 / 96
System::Call 'user32::CreateWindowEx(i r3, w "${__NSD_CheckBox_CLASS}", w "$(deleteAppData)", i ${__NSD_CheckBox_STYLE}, i r4, i r5, i r6, i r7, p r1, i0, i0, i0) i .s'
Pop $DeleteAppDataCheckbox
SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1
SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1
FunctionEnd
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave
Function un.ConfirmLeave
SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState
FunctionEnd
!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive
!insertmacro MUI_UNPAGE_CONFIRM
; 2. Uninstalling Page
!insertmacro MUI_UNPAGE_INSTFILES
;Languages
{{#each languages}}
!insertmacro MUI_LANGUAGE "{{this}}"
{{/each}}
!insertmacro MUI_RESERVEFILE_LANGDLL
{{#each language_files}}
!include "{{this}}"
{{/each}}
Function .onInit
${GetOptions} $CMDLINE "/P" $PassiveMode
${IfNot} ${Errors}
StrCpy $PassiveMode 1
${EndIf}
${GetOptions} $CMDLINE "/NS" $NoShortcutMode
${IfNot} ${Errors}
StrCpy $NoShortcutMode 1
${EndIf}
${GetOptions} $CMDLINE "/UPDATE" $UpdateMode
${IfNot} ${Errors}
StrCpy $UpdateMode 1
${EndIf}
!if "${DISPLAYLANGUAGESELECTOR}" == "true"
!insertmacro MUI_LANGDLL_DISPLAY
!endif
!insertmacro SetContext
${If} $INSTDIR == "${PLACEHOLDER_INSTALL_DIR}"
; Set default install location
!if "${INSTALLMODE}" == "perMachine"
${If} ${RunningX64}
!if "${ARCH}" == "x64"
StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
!else if "${ARCH}" == "arm64"
StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
!else
StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
!endif
${Else}
StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
${EndIf}
!else if "${INSTALLMODE}" == "currentUser"
StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}"
!endif
Call RestorePreviousInstallLocation
${EndIf}
!if "${INSTALLMODE}" == "both"
!insertmacro MULTIUSER_INIT
!endif
; Abort downgrades if they are disabled, in the modes that skip the reinstall page choice:
; silent, passive and update
!if "${ALLOWDOWNGRADES}" == "false"
${If} ${Silent}
${OrIf} $PassiveMode = 1
${OrIf} $UpdateMode = 1
ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"
nsis_tauri_utils::SemverCompare "${VERSION}" $R0
Pop $R0
; If downgrading
${If} $R0 = -1
${If} ${Silent}
System::Call 'kernel32::AttachConsole(i -1)i.r0'
${If} $0 <> 0
System::Call 'kernel32::GetStdHandle(i -11)i.r0'
System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color
FileWrite $0 "$(silentDowngrades)"
${EndIf}
${Else}
MessageBox MB_ICONSTOP "$(silentDowngrades)"
${EndIf}
Abort
${EndIf}
${EndIf}
!endif
FunctionEnd
Section WebView2
; Check if Webview2 is already installed and skip this section
${If} ${RunningX64}
ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
${Else}
ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
${EndIf}
${If} $4 == ""
ReadRegStr $4 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
${EndIf}
${If} $4 == ""
; Webview2 installation
;
; Skip if updating
${If} $UpdateMode <> 1
!if "${INSTALLWEBVIEW2MODE}" == "downloadBootstrapper"
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
DetailPrint "$(webview2Downloading)"
NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe"
Pop $0
${If} $0 == "success"
DetailPrint "$(webview2DownloadSuccess)"
${Else}
DetailPrint "$(webview2DownloadError)"
Abort "$(webview2AbortError)"
${EndIf}
StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
Goto install_webview2
!endif
!if "${INSTALLWEBVIEW2MODE}" == "embedBootstrapper"
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
File "/oname=$TEMP\MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPERPATH}"
DetailPrint "$(installingWebview2)"
StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
Goto install_webview2
!endif
!if "${INSTALLWEBVIEW2MODE}" == "offlineInstaller"
Delete "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
File "/oname=$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" "${WEBVIEW2INSTALLERPATH}"
DetailPrint "$(installingWebview2)"
StrCpy $6 "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
Goto install_webview2
!endif
Goto webview2_done
install_webview2:
DetailPrint "$(installingWebview2)"
; $6 holds the path to the webview2 installer
ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1
${If} $1 = 0
DetailPrint "$(webview2InstallSuccess)"
${Else}
DetailPrint "$(webview2InstallError)"
Abort "$(webview2AbortError)"
${EndIf}
webview2_done:
${EndIf}
${Else}
!if "${MINIMUMWEBVIEW2VERSION}" != ""
${VersionCompare} "${MINIMUMWEBVIEW2VERSION}" "$4" $R0
${If} $R0 = 1
update_webview:
DetailPrint "$(installingWebview2)"
${If} ${RunningX64}
ReadRegStr $R1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate" "path"
${Else}
ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\EdgeUpdate" "path"
${EndIf}
${If} $R1 == ""
ReadRegStr $R1 HKCU "SOFTWARE\Microsoft\EdgeUpdate" "path"
${EndIf}
${If} $R1 != ""
; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md
; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath"
ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1
${If} $1 = 0
DetailPrint "$(webview2InstallSuccess)"
${Else}
MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview
Quit
ignore:
${EndIf}
${EndIf}
${EndIf}
!endif
${EndIf}
SectionEnd
Section Install
SetOutPath $INSTDIR
!ifmacrodef NSIS_HOOK_PREINSTALL
!insertmacro NSIS_HOOK_PREINSTALL
!endif
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
; Copy main executable
File "${MAINBINARYSRCPATH}"
; Copy resources
{{#each resources_dirs}}
CreateDirectory "$INSTDIR\\{{this}}"
{{/each}}
{{#each resources}}
File /a "/oname={{this.[1]}}" "{{no-escape @key}}"
{{/each}}
; Copy external binaries
{{#each binaries}}
File /a "/oname={{this}}" "{{no-escape @key}}"
{{/each}}
; Create file associations
{{#each file_associations as |association| ~}}
{{#each association.ext as |ext| ~}}
!insertmacro APP_ASSOCIATE "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\""
{{/each}}
{{/each}}
; Register deep links
{{#each deep_link_protocols as |protocol| ~}}
WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "URL Protocol" ""
WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "" "URL:${BUNDLEID} protocol"
WriteRegStr SHCTX "Software\Classes\\{{protocol}}\DefaultIcon" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\",0"
WriteRegStr SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""
{{/each}}
; Create uninstaller
WriteUninstaller "$INSTDIR\uninstall.exe"
; Save $INSTDIR in registry for future installations
WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR
!if "${INSTALLMODE}" == "both"
; Save install mode to be selected by default for the next installation such as updating
; or when uninstalling
WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1
!endif
; Remove old main binary if it doesn't match new main binary name
ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName"
${If} $OldMainBinaryName != ""
${AndIf} $OldMainBinaryName != "${MAINBINARYNAME}.exe"
Delete "$INSTDIR\$OldMainBinaryName"
${EndIf}
; Save current MAINBINARYNAME for future updates
WriteRegStr SHCTX "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe"
; Registry information for add/remove programs
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}"
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${VERSION}"
WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}"
WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\""
WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" "1"
WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" "1"
${GetSize} "$INSTDIR" "/M=uninstall.exe /S=0K /G=0" $0 $1 $2
IntOp $0 $0 + ${ESTIMATEDSIZE}
IntFmt $0 "0x%08X" $0
WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "$0"
!if "${HOMEPAGE}" != ""
WriteRegStr SHCTX "${UNINSTKEY}" "URLInfoAbout" "${HOMEPAGE}"
WriteRegStr SHCTX "${UNINSTKEY}" "URLUpdateInfo" "${HOMEPAGE}"
WriteRegStr SHCTX "${UNINSTKEY}" "HelpLink" "${HOMEPAGE}"
!endif
; Create start menu shortcut
!insertmacro MUI_STARTMENU_WRITE_BEGIN Application
Call CreateOrUpdateStartMenuShortcut
!insertmacro MUI_STARTMENU_WRITE_END
; Create desktop shortcut for silent and passive installers
; because finish page will be skipped
${If} $PassiveMode = 1
${OrIf} ${Silent}
Call CreateOrUpdateDesktopShortcut
${EndIf}
!ifmacrodef NSIS_HOOK_POSTINSTALL
!insertmacro NSIS_HOOK_POSTINSTALL
!endif
; Auto close this page for passive mode
${If} $PassiveMode = 1
SetAutoClose true
${EndIf}
SectionEnd
Function .onInstSuccess
; Check for `/R` flag only in silent and passive installers because
; GUI installer has a toggle for the user to (re)start the app
${If} $PassiveMode = 1
${OrIf} ${Silent}
${GetOptions} $CMDLINE "/R" $R0
${IfNot} ${Errors}
${GetOptions} $CMDLINE "/ARGS" $R0
nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "$R0"
${EndIf}
${EndIf}
FunctionEnd
Function un.onInit
!insertmacro SetContext
!if "${INSTALLMODE}" == "both"
!insertmacro MULTIUSER_UNINIT
!endif
!insertmacro MUI_UNGETLANGUAGE
${GetOptions} $CMDLINE "/P" $PassiveMode
${IfNot} ${Errors}
StrCpy $PassiveMode 1
${EndIf}
${GetOptions} $CMDLINE "/UPDATE" $UpdateMode
${IfNot} ${Errors}
StrCpy $UpdateMode 1
${EndIf}
FunctionEnd
Section Uninstall
!ifmacrodef NSIS_HOOK_PREUNINSTALL
!insertmacro NSIS_HOOK_PREUNINSTALL
!endif
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
; Delete the app directory and its content from disk
; Copy main executable
Delete "$INSTDIR\${MAINBINARYNAME}.exe"
; Delete resources
{{#each resources}}
Delete "$INSTDIR\\{{this.[1]}}"
{{/each}}
; Delete external binaries
{{#each binaries}}
Delete "$INSTDIR\\{{this}}"
{{/each}}
; Delete app associations
{{#each file_associations as |association| ~}}
{{#each association.ext as |ext| ~}}
!insertmacro APP_UNASSOCIATE "{{ext}}" "{{or association.name ext}}"
{{/each}}
{{/each}}
; Delete deep links
{{#each deep_link_protocols as |protocol| ~}}
ReadRegStr $R7 SHCTX "Software\Classes\\{{protocol}}\shell\open\command" ""
${If} $R7 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""
DeleteRegKey SHCTX "Software\Classes\\{{protocol}}"
${EndIf}
{{/each}}
; Delete uninstaller
Delete "$INSTDIR\uninstall.exe"
{{#each resources_ancestors}}
RMDir /REBOOTOK "$INSTDIR\\{{this}}"
{{/each}}
RMDir "$INSTDIR"
; Remove shortcuts if not updating
${If} $UpdateMode <> 1
!insertmacro DeleteAppUserModelId
; Remove start menu shortcut
!insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder
!insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
Pop $0
${If} $0 = 1
!insertmacro UnpinShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
Delete "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
RMDir "$SMPROGRAMS\$AppStartMenuFolder"
${EndIf}
!insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
Pop $0
${If} $0 = 1
!insertmacro UnpinShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk"
Delete "$SMPROGRAMS\${PRODUCTNAME}.lnk"
${EndIf}
; Remove desktop shortcuts
!insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
Pop $0
${If} $0 = 1
!insertmacro UnpinShortcut "$DESKTOP\${PRODUCTNAME}.lnk"
Delete "$DESKTOP\${PRODUCTNAME}.lnk"
${EndIf}
${EndIf}
; Remove registry information for add/remove programs
!if "${INSTALLMODE}" == "both"
DeleteRegKey SHCTX "${UNINSTKEY}"
!else if "${INSTALLMODE}" == "perMachine"
DeleteRegKey HKLM "${UNINSTKEY}"
!else
DeleteRegKey HKCU "${UNINSTKEY}"
!endif
; Removes the Autostart entry for ${PRODUCTNAME} from the HKCU Run key if it exists.
; This ensures the program does not launch automatically after uninstallation if it exists.
; If it doesn't exist, it does nothing.
; We do this when not updating (to preserve the registry value on updates)
${If} $UpdateMode <> 1
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
${EndIf}
; Delete app data if the checkbox is selected
; and if not updating
${If} $DeleteAppDataCheckboxState = 1
${AndIf} $UpdateMode <> 1
; Clear the install location $INSTDIR from registry
DeleteRegKey SHCTX "${MANUPRODUCTKEY}"
DeleteRegKey /ifempty SHCTX "${MANUKEY}"
; Clear the install language from registry
DeleteRegValue HKCU "${MANUPRODUCTKEY}" "Installer Language"
DeleteRegKey /ifempty HKCU "${MANUPRODUCTKEY}"
DeleteRegKey /ifempty HKCU "${MANUKEY}"
SetShellVarContext current
RmDir /r "$APPDATA\${BUNDLEID}"
RmDir /r "$LOCALAPPDATA\${BUNDLEID}"
${EndIf}
!ifmacrodef NSIS_HOOK_POSTUNINSTALL
!insertmacro NSIS_HOOK_POSTUNINSTALL
!endif
; Auto close if passive mode or updating
${If} $PassiveMode = 1
${OrIf} $UpdateMode = 1
SetAutoClose true
${EndIf}
SectionEnd
Function RestorePreviousInstallLocation
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
StrCmp $4 "" +2 0
StrCpy $INSTDIR $4
FunctionEnd
Function Skip
Abort
FunctionEnd
Function SkipIfPassive
${IfThen} $PassiveMode = 1 ${|} Abort ${|}
FunctionEnd
Function un.SkipIfPassive
${IfThen} $PassiveMode = 1 ${|} Abort ${|}
FunctionEnd
Function CreateOrUpdateStartMenuShortcut
; We used to use product name as MAINBINARYNAME
; migrate old shortcuts to target the new MAINBINARYNAME
StrCpy $R0 0
!insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
Pop $0
${If} $0 = 1
!insertmacro SetShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
StrCpy $R0 1
${EndIf}
!insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
Pop $0
${If} $0 = 1
!insertmacro SetShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
StrCpy $R0 1
${EndIf}
${If} $R0 = 1
Return
${EndIf}
; Skip creating shortcut if in update mode or no shortcut mode
; but always create if migrating from wix
${If} $WixMode = 0
${If} $UpdateMode = 1
${OrIf} $NoShortcutMode = 1
Return
${EndIf}
${EndIf}
!if "${STARTMENUFOLDER}" != ""
CreateDirectory "$SMPROGRAMS\$AppStartMenuFolder"
CreateShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
!insertmacro SetLnkAppUserModelId "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
!else
CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
!insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk"
!endif
FunctionEnd
Function CreateOrUpdateDesktopShortcut
; We used to use product name as MAINBINARYNAME
; migrate old shortcuts to target the new MAINBINARYNAME
!insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
Pop $0
${If} $0 = 1
!insertmacro SetShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
Return
${EndIf}
; Skip creating shortcut if in update mode or no shortcut mode
; but always create if migrating from wix
${If} $WixMode = 0
${If} $UpdateMode = 1
${OrIf} $NoShortcutMode = 1
Return
${EndIf}
${EndIf}
CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
!insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk"
FunctionEnd
+50
Переглянути файл
@@ -965,9 +965,13 @@ export const commands = {
comparison?: ComparisonLaunch | null,
/** `openidea diff a.txt b.txt`: the two files to open in the diff viewer (boxed: most launches have none). */
diff?: DiffFilesLaunch | null,
/** Files requested after the pending diff take focus after it opens. */
diffBeforeFiles?: boolean,
/** Deployment windows: the server and local selection to compare. */
deployment?: DeploymentLaunch | null,
} | null>("window_take_launch"),
/** Release the opening window's reservation after navigation or cancellation. */
windowCompleteLaunch: () => typedError<null, IdeError>(__TAURI_INVOKE("window_complete_launch")),
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
/** Projects open in project windows, in window order (title bar project widget). */
windowOpenProjects: () => typedError<OpenProject[], IdeError>(__TAURI_INVOKE("window_open_projects")),
@@ -1282,6 +1286,12 @@ export const commands = {
dockerRemove: (endpoint: DockerEndpoint, object: DockerObject, ids: string[], force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("docker_remove", { endpoint, object, ids, force })),
/** Pretty-printed `docker inspect` JSON. */
dockerInspect: (endpoint: DockerEndpoint, object: DockerObject, id: string) => typedError<string, IdeError>(__TAURI_INVOKE("docker_inspect", { endpoint, object, id })),
/** Layers of an image (`docker image history`). */
dockerImageHistory: (endpoint: DockerEndpoint, id: string) => typedError<DockerImageLayer[], IdeError>(__TAURI_INVOKE("docker_image_history", { endpoint, id })),
/** Processes running inside a container (`docker top`). */
dockerContainerTop: (endpoint: DockerEndpoint, id: string) => typedError<DockerProcessList, IdeError>(__TAURI_INVOKE("docker_container_top", { endpoint, id })),
/** One-shot resource usage snapshot of a running container (`docker stats --no-stream`). */
dockerContainerStats: (endpoint: DockerEndpoint, id: string) => typedError<DockerContainerStats, IdeError>(__TAURI_INVOKE("docker_container_stats", { endpoint, id })),
/** Streams a container's log lines until it stops or the request is cancelled. */
dockerLogs: (request: RequestId, endpoint: DockerEndpoint, id: string, tail: number, follow: boolean, timestamps: boolean, onLine: Channel<DockerLogLine>) => typedError<null, IdeError>(__TAURI_INVOKE("docker_logs", { request, endpoint, id, tail, follow, timestamps, onLine })),
/** Follows `docker events` until the daemon goes away or the request is cancelled. */
@@ -3546,6 +3556,22 @@ export type DockerContainer = {
composeWorkingDir: string | null,
/** `com.docker.compose.project.config_files` label (comma-separated in docker). */
composeFiles: string[],
/** Mounted volume names or host paths reported by `docker ps` (`Mounts`). */
mounts?: string[],
/** Connected network names reported by `docker ps` (`Networks`). */
networks?: string[],
/** User and tool labels assigned to the container. */
labels?: { [key in string]: string },
};
/** Live resource metrics returned by `docker stats --no-stream --no-trunc --format '{{json .}}'`. */
export type DockerContainerStats = {
cpuPerc: string,
memUsage: string,
memPerc: string,
netIo: string,
blockIo: string,
pids: string,
};
/** Which daemon a docker command talks to. */
@@ -3580,6 +3606,16 @@ export type DockerImage = {
createdSince: string,
};
/** One layer in `docker image history --no-trunc --format '{{json .}}'`. */
export type DockerImageLayer = {
id: string,
createdBy: string,
size: string,
createdSince: string,
createdAt: string,
comment: string,
};
/** A line of `docker logs` output. */
export type DockerLogLine = {
stderr: boolean,
@@ -3592,10 +3628,20 @@ export type DockerNetwork = {
driver: string,
scope: string,
composeProject: string | null,
createdAt?: string,
ipv6?: boolean,
internal?: boolean,
labels?: { [key in string]: string },
};
export type DockerObject = "container" | "image" | "volume" | "network";
/** Process table returned by `docker top <container>`. */
export type DockerProcessList = {
titles: string[],
processes: string[][],
};
/** A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately. */
export type DockerRegistry = {
id: string,
@@ -3630,6 +3676,8 @@ export type DockerVolume = {
driver: string,
mountpoint: string,
composeProject: string | null,
scope?: string,
labels?: { [key in string]: string },
};
/** What the UI needs to show an opened document. */
@@ -5473,6 +5521,8 @@ export type Launch = {
comparison?: ComparisonLaunch | null,
/** `openidea diff a.txt b.txt`: the two files to open in the diff viewer (boxed: most launches have none). */
diff?: DiffFilesLaunch | null,
/** Files requested after the pending diff take focus after it opens. */
diffBeforeFiles?: boolean,
/** Deployment windows: the server and local selection to compare. */
deployment?: DeploymentLaunch | null,
};
+15 -1
Переглянути файл
@@ -28,11 +28,12 @@ import {
type RangeSet,
type Transaction,
} from "@codemirror/state";
import { GutterMarker, ViewPlugin, type EditorView } from "@codemirror/view";
import { GutterMarker, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import type { LanguageDescription } from "@codemirror/language";
import type { LineEnding } from "@/platform/ipc";
import { create } from "zustand";
import { maybeEditorService } from "@/workbench/contributions";
import { cornerInset } from "@/editor/core/cm/cornerInset";
/** Documents above this size (UTF-16 units) skip per-line decorations. */
export const HEAVY_LIMIT = 8_000_000;
@@ -358,6 +359,8 @@ export function editorCorner(view: EditorView): HTMLElement {
gap: "4px",
});
view.dom.appendChild(el);
// The lines leave room for its measured width, so it never covers a line end.
view.plugin(cornerInset)?.track(el);
return el;
}
@@ -402,6 +405,17 @@ export interface ContributedIntention {
/** A background provider has new context actions for the current document. */
export const intentionsChanged = StateEffect.define<null>();
/**
* A hidden editor view is shown again. Recently used tabs keep their view, detached from the
* document, while hidden; plugins that skip work while `view.dom` is disconnected redo it when
* `shownAgain`.
*/
export const viewShown = StateEffect.define<null>();
export function shownAgain(u: ViewUpdate): boolean {
return u.transactions.some((tr) => tr.effects.some((e) => e.is(viewShown)));
}
/** Local fixes of a diagnostic range (hover link and Apply Quick Fix). */
export const quickFixProviders = Facet.define<(view: EditorView, from: number, to: number) => ContributedIntention[]>();
+8 -3
Переглянути файл
@@ -6,6 +6,7 @@ import { foldEffect, syntaxTree, toggleFold } from "@codemirror/language";
import { acceptCompletion, completionStatus } from "@codemirror/autocomplete";
import { executeAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { focusedSoftWrapSurface } from "@/workbench/softWrap";
import { resetSurfaceFontZoom, stepFocusedSurfaceFontZoom } from "@/workbench/contributions";
import { editorController, useGotoLine, useTabs } from "./controller";
import {
@@ -738,9 +739,13 @@ export function registerEditorActions(): () => void {
category: "View",
icon: "soft-wrap",
keywords: ["word wrap", "line wrap"],
when: "textEditorActive",
toggled: () => activeSlot()?.model.softWrapOn() ?? false,
run: () => activeSlot()?.model.toggleSoftWrap(),
when: "textEditorActive || softWrapSurfaceFocus",
toggled: () => focusedSoftWrapSurface()?.enabled() ?? activeSlot()?.model.softWrapOn() ?? false,
run: () => {
const surface = focusedSoftWrapSurface();
if (surface) surface.toggle();
else activeSlot()?.model.toggleSoftWrap();
},
},
text("code.foldAll", "Collapse All", (v) => collapseAll(v), { category: "Folding", icon: "collapse-all" }),
text("code.unfoldAll", "Expand All", (v) => expandAll(v), { category: "Folding", icon: "expand-all" }),
+73
Переглянути файл
@@ -0,0 +1,73 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { editorCorner } from "@/editor/api";
import { cornerInset } from "./cornerInset";
let view: EditorView;
let resize: (() => void) | null = null;
beforeEach(() => {
vi.stubGlobal(
"ResizeObserver",
class {
constructor(callback: () => void) {
resize = callback;
}
observe() {}
disconnect() {
resize = null;
}
},
);
view = new EditorView({
state: EditorState.create({ doc: "const a = 1;", extensions: [cornerInset] }),
parent: document.body,
});
});
afterEach(() => {
view.destroy();
vi.unstubAllGlobals();
});
const inset = () => view.dom.style.getPropertyValue("--cm-corner-inset");
/** The corner's measured width arrives from the ResizeObserver, not from jsdom. */
function resizeTo(width: number) {
const corner = view.dom.querySelector<HTMLElement>(".cm-openidea-corner");
if (!corner) throw new Error("no corner");
corner.getBoundingClientRect = () => ({ width }) as DOMRect;
resize?.();
}
describe("corner inset", () => {
it("leaves the corner's width plus a gap for the text: 20px check, 32+ with counts", () => {
editorCorner(view);
resizeTo(20);
expect(inset()).toBe("24px");
resizeTo(32);
expect(inset()).toBe("36px");
});
it("clears the reserved room when the corner is empty", () => {
editorCorner(view);
resizeTo(20);
resizeTo(0);
expect(inset()).toBe("");
});
it("keeps at least half of the editor width for the text", () => {
Object.defineProperty(view.scrollDOM, "clientWidth", { configurable: true, value: 200 });
editorCorner(view);
resizeTo(400);
expect(inset()).toBe("100px");
});
it("does nothing without the extension", () => {
const plain = new EditorView({ state: EditorState.create({ doc: "x" }), parent: document.body });
expect(() => editorCorner(plain)).not.toThrow();
expect(plain.dom.style.getPropertyValue("--cm-corner-inset")).toBe("");
plain.destroy();
});
});
+81
Переглянути файл
@@ -0,0 +1,81 @@
/**
* Keeps the end of a line clear of the floating corner widgets (`editorCorner()`
* in `editor/api.ts`: the inspection widget, the Review Mode group).
*
* The corner is absolutely positioned in `.cm-editor`, outside `.cm-scroller`:
* scrolling does not move it and it does not count in `scrollWidth`, so at full
* horizontal scroll the last characters of a line land under it. Its width is
* not a constant (a green check, then counts and previous/next buttons as
* problems appear), so the lines' right padding follows its measured width
* through `--cm-corner-inset` (`theme.ts`), the way the fixed line padding
* already reserves room for the overview lane.
*/
import { type EditorView, ViewPlugin } from "@codemirror/view";
/** Space between the corner's left edge and the end of a line. */
const CORNER_GAP = 4;
/** Width changes of the corner that matter: `getBoundingClientRect()` is fractional. */
const round = (width: number) => Math.ceil(width);
class CornerInset {
private corner: HTMLElement | null = null;
private observer: ResizeObserver | null = null;
private inset = -1;
constructor(private readonly view: EditorView) {
this.sync();
}
/** A new corner: `editorCorner()` calls this right after appending it. */
track(corner: HTMLElement) {
if (corner === this.corner) return;
this.observer?.disconnect();
this.corner = corner;
if (typeof ResizeObserver === "undefined") return;
// The widget's content grows and shrinks (diagnostic counts, Review Mode).
this.observer = new ResizeObserver(() => this.measure());
this.observer.observe(corner);
this.measure();
}
update() {
// The corner is created lazily, possibly after this plugin: catch it on the next update.
if (!this.corner) this.sync();
}
private sync() {
const corner = this.view.dom.querySelector<HTMLElement>(":scope > .cm-openidea-corner");
if (corner) this.track(corner);
}
private measure() {
const corner = this.corner;
if (!corner) return;
const width = corner.getBoundingClientRect().width;
let inset = width > 0 ? round(width) + CORNER_GAP : 0;
// A narrow window or a wide corner: keep at least half of the width for text.
const room = this.view.scrollDOM.clientWidth;
if (inset > 0 && room > 0) inset = Math.min(inset, Math.floor(room / 2));
this.apply(inset);
}
private apply(inset: number) {
if (inset === this.inset) return;
this.inset = inset;
const style = this.view.dom.style;
// An empty corner needs no room; the `theme.ts` fallback is 0.
if (inset > 0) style.setProperty("--cm-corner-inset", `${inset}px`);
else style.removeProperty("--cm-corner-inset");
// The line boxes changed: CodeMirror re-measures the content and the scroll extent.
this.view.requestMeasure();
}
destroy() {
this.observer?.disconnect();
this.observer = null;
this.corner = null;
}
}
export const cornerInset = ViewPlugin.fromClass(CornerInset);
+2
Переглянути файл
@@ -34,6 +34,7 @@ import { openideaHighlightStyle } from "./highlight";
import { openideaTheme } from "./theme";
import { caretRowHighlight } from "./caretRow";
import { changeLane, overviewLane } from "./lanes";
import { cornerInset } from "./cornerInset";
import { foldingExtension } from "./folding";
import { syntaxHighlightField } from "./syntaxHighlight";
import { indentGuides } from "./indentGuides";
@@ -370,6 +371,7 @@ export function baseExtensions(o: SetupOptions): Extension {
methodLinesField,
findExtension(),
overviewLane,
cornerInset,
codeLensExtension,
EditorView.contentAttributes.of({
spellcheck: "false",
+5 -2
Переглянути файл
@@ -153,7 +153,8 @@ export const openideaTheme = EditorView.theme({
caretColor: "var(--caret, var(--fg-strong))",
cursor: "text",
},
".cm-line": { padding: "0 16px 0 6px" },
// The right side also leaves room for the floating corner widgets (core/cm/cornerInset.ts).
".cm-line": { padding: "0 calc(16px + var(--cm-corner-inset, 0px)) 0 6px" },
...caretStyles,
"&.cm-openidea-ligatures .cm-scroller, &.cm-openidea-ligatures .cm-openidea-sticky": {
fontVariantLigatures: "normal",
@@ -370,5 +371,7 @@ export const openideaTheme = EditorView.theme({
".cm-openidea-stickyText": { flex: "1", overflow: "hidden" },
// Soft-wrap: continuation rows indent slightly, like IDEA's wrap sign column.
"&.cm-lineWrapping .cm-line, .cm-lineWrapping .cm-line": { paddingRight: "24px" },
"&.cm-lineWrapping .cm-line, .cm-lineWrapping .cm-line": {
paddingRight: "calc(24px + var(--cm-corner-inset, 0px))",
},
});
+4 -1
Переглянути файл
@@ -56,6 +56,7 @@ import {
enforceTabLimit,
findTab,
initialTabsState,
mergeSessionTabs,
moveTab,
moveTabToNewSplit,
neighbourPane,
@@ -531,7 +532,9 @@ export class EditorController implements SlotHost {
this.restoredTabs = new Set(Object.values(state.panes).flatMap((p) => p.tabs.map((t) => t.id)));
this.restoring = true;
try {
useTabs.setState(state, true);
// A restore landing after tabs were already opened (e.g. a launched file
// admitted while the transition was still in flight) must not wipe them.
useTabs.setState((current) => mergeSessionTabs(current, state), true);
} finally {
this.restoring = false;
}
+63
Переглянути файл
@@ -0,0 +1,63 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorController, LIGHT_EDIT_SESSION, openFilePaths, useTabs } from "./controller";
import { createMemoryBackend } from "./backend";
import { initialTabsState } from "./model/tabs";
import { storeSession } from "./model/session";
import { useProject } from "@/platform/project";
let ctrl: EditorController | null = null;
const initialSettings = useProject.getState().settings;
afterEach(() => {
ctrl?.stop();
ctrl = null;
useTabs.setState(initialTabsState(), true);
useProject.setState({ project: null, lightEdit: false, settings: initialSettings } as never);
try {
localStorage.removeItem(`openidea.editorSession.v1:${LIGHT_EDIT_SESSION}`);
} catch {
/* ignore */
}
});
function activePath() {
const state = useTabs.getState();
const pane = state.panes[state.activePane]!;
return pane.tabs.find((tab) => tab.id === pane.active)?.input.path;
}
function seedLightEditSession() {
storeSession(LIGHT_EDIT_SESSION, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/a.ts" }], active: 0 },
activePane: 0,
files: {},
});
}
describe("lightedit launch (#2229)", () => {
it("admits the launched file after the saved session restores", async () => {
seedLightEditSession();
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b" }));
ctrl.start();
// openFilesHere: window has neither project nor LightEdit -> openLightEdit(b) then openInEditor([b]).
useProject.setState({ project: null, lightEdit: true });
await ctrl.openFile("/p/b.ts", { focus: true });
await new Promise((r) => setTimeout(r, 50));
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
});
it("merges a late saved-session restore with the launched tab instead of replacing it", async () => {
seedLightEditSession();
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b" }));
ctrl.start();
useProject.setState({ project: null, lightEdit: true });
await ctrl.openFile("/p/b.ts", { focus: true });
// A stale/second transition restore landing after the admit (#2229).
ctrl.restoreSession(LIGHT_EDIT_SESSION);
await new Promise((r) => setTimeout(r, 50));
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
});
});
+1 -8
Переглянути файл
@@ -111,14 +111,7 @@ export async function attachDocument(
if (model.ctx().readOnly || released || model.closed) return false;
const slot = model.primarySlot();
if (slot?.view) return command(slot.view);
if (slot)
return command({
state: slot.state,
dispatch: (tr) => {
slot.state = tr.state;
if (tr.docChanged) model.onLocal(tr.changes, slot);
},
});
if (slot) return command({ state: slot.state, dispatch: (tr) => slot.dispatchLocal(tr) });
return target.view ? command(target.view) : false;
};
+71 -3
Переглянути файл
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { indentUnit, language as languageFacet } from "@codemirror/language";
import { HEAVY_LIMIT, registerSaveParticipant, remoteChange } from "@/editor/api";
import { HEAVY_LIMIT, registerSaveParticipant, remoteChange, shownAgain } from "@/editor/api";
import { createMemoryBackend, type MemoryBackend } from "../backend";
import { _resetLanguages } from "../cm/languages";
import { DocumentManager, ModifiedRanges, saveCleanupChanges, useDocMeta } from "./document";
@@ -142,9 +142,10 @@ describe("DocumentManager + slots", () => {
const a = new EditorSlot(model, "t1", host);
const b = new EditorSlot(model, "t2", host);
let sawRemote = false;
const spy = vi.spyOn(a, "applyExternal").mockImplementation(function (this: EditorSlot, changes, annotations) {
const applyExternal = a.applyExternal.bind(a);
const spy = vi.spyOn(a, "applyExternal").mockImplementation((changes, annotations) => {
sawRemote = annotations.some((x) => x.type === remoteChange);
this.state = this.state.update({ changes, annotations }).state;
applyExternal(changes, annotations);
});
backend.patch(model.doc, [{ from: 3, to: 3, insert: "def" }]);
expect(sawRemote).toBe(true);
@@ -301,6 +302,73 @@ describe("DocumentManager + slots", () => {
manager.stop();
}
});
it("keeps a hidden tab's view and shows it again instead of building a new one", async () => {
const { backend, manager } = setup({ "/p/a.txt": "abc" });
const model = await manager.acquire("/p/a.txt");
const slot = new EditorSlot(model, "t1", host);
const shown: boolean[] = [];
slot.listeners.add((u) => shown.push(shownAgain(u)));
const view = slot.mount(document.body);
slot.unmount();
expect(slot.view).toBeNull();
expect(view.dom.isConnected).toBe(false);
// Changes while hidden go to the kept view.
backend.patch(model.doc, [{ from: 3, to: 3, insert: "def" }]);
expect(view.state.doc.toString()).toBe("abcdef");
expect(slot.currentState()).toBe(view.state);
shown.length = 0;
expect(slot.mount(document.body)).toBe(view);
expect(view.dom.isConnected).toBe(true);
expect(shown).toContain(true);
slot.dispose();
manager.stop();
});
it("destroys the least recently hidden views beyond the kept ones, and kept views on dispose", async () => {
const { manager } = setup({ "/p/a.txt": "abc" });
const model = await manager.acquire("/p/a.txt");
const slots = Array.from({ length: 8 }, (_, i) => new EditorSlot(model, `t${i}`, host));
const views = slots.map((slot) => {
const view = slot.mount(document.body);
slot.unmount();
return view;
});
const destroyed = views.map((view) => vi.spyOn(view, "destroy"));
slots.push(new EditorSlot(model, "t8", host));
slots[8]!.mount(document.body);
slots[8]!.unmount();
expect(destroyed[0]).toHaveBeenCalled();
expect(destroyed[1]).not.toHaveBeenCalled();
// A destroyed view leaves its state behind; showing the tab builds a new view on it.
expect(slots[0]!.mount(document.body)).not.toBe(views[0]);
slots[1]!.dispose();
expect(destroyed[1]).toHaveBeenCalled();
for (const slot of slots) slot.dispose();
manager.stop();
});
it("restores a destroyed kept view at its exact scroll offset, not its top line", async () => {
const { manager } = setup({ "/p/a.txt": "line\n".repeat(500) });
const model = await manager.acquire("/p/a.txt");
const slot = new EditorSlot(model, "t0", host);
const view = slot.mount(document.body);
Object.defineProperty(view.scrollDOM, "scrollTop", { value: 137, configurable: true });
view.scrollDOM.dispatchEvent(new Event("scroll"));
slot.unmount();
const expected = view.scrollSnapshot().value as { range: unknown; yMargin: number; isSnapshot: boolean };
const others = Array.from({ length: 8 }, (_, i) => new EditorSlot(model, `t${i + 1}`, host));
for (const other of others) {
other.mount(document.body);
other.unmount();
}
const restored = (slot as unknown as { scroll: { value: typeof expected } }).scroll.value;
expect(restored.isSnapshot).toBe(true);
expect(restored.range).toEqual(expected.range);
expect(restored.yMargin).toBe(expected.yMargin);
for (const s of [slot, ...others]) s.dispose();
manager.stop();
});
});
describe("save cleanup", () => {
+110 -33
Переглянути файл
@@ -1,8 +1,10 @@
/**
* An editor slot is one tab showing a text document in one pane. It owns the
* tab's EditorState (selection, folds, undo history, scroll) and, while the
* tab is visible, an EditorView. Background tabs keep only their state; views
* are created on show and destroyed on hide, so many open tabs cost little.
* tab is visible, an EditorView. The most recently used tabs keep their view,
* detached, while hidden (`KEPT_VIEWS`): showing one again re-attaches it with
* its decorations, height map and plugin state; older background tabs keep
* only their state and get a new view when shown.
*
* All slots of a document share its DocModel: local edits flow
* slot → model → backend and are mirrored into the other slots.
@@ -23,6 +25,7 @@ import {
_addEditor,
_removeEditor,
documentSynced,
viewShown,
isExternalChange,
transientChange,
type EditorDocContext,
@@ -53,11 +56,20 @@ export interface Reveal {
center?: boolean;
}
/** Hidden views kept for showing again, least recently hidden first. */
const KEPT_VIEWS = 8;
const keptSlots: EditorSlot[] = [];
export class EditorSlot {
state: EditorState;
private stored: EditorState;
private historyTarget: WorkspaceHistoryTarget;
private detachHistory: () => void;
/** The view while the tab is visible. */
view: EditorView | null = null;
/** The view kept, detached from the document, while the tab is hidden. */
private kept: EditorView | null = null;
/** The view's scroll offset, tracked so hiding it needn't read layout. */
private scrollPos = { top: 0, left: 0 };
handle: TextEditorHandle | null = null;
private scroll: StateEffect<unknown> | null = null;
private pendingReveal: Reveal | null = null;
@@ -80,8 +92,8 @@ export class EditorSlot {
path: model.path,
state: () => this.currentState(),
dispatch: (tr) => {
if (this.view) this.view.dispatch(tr);
else this.state = tr.state;
if (this.live) this.live.dispatch(tr);
else this.stored = tr.state;
},
};
const source = init?.from;
@@ -91,7 +103,7 @@ export class EditorSlot {
.find((state) => state?.field(historyField, false))
: null;
const history = secondary?.field(historyField, false);
this.state = EditorState.create({
this.stored = EditorState.create({
doc: model.sync.localText,
selection: source ? source.currentState().selection : undefined,
extensions: [
@@ -121,8 +133,17 @@ export class EditorSlot {
return this.model.ctx();
}
/** The visible or kept view: the one holding the tab's state. */
private get live(): EditorView | null {
return this.view ?? this.kept;
}
get state(): EditorState {
return this.live?.state ?? this.stored;
}
currentState(): EditorState {
return this.view?.state ?? this.state;
return this.state;
}
private slotExtensions() {
@@ -137,6 +158,11 @@ export class EditorSlot {
}
}),
Prec.highest(keymap.of([{ key: "Escape", run: () => this.host.onEscape?.(this) ?? false }])),
EditorView.domEventObservers({
scroll: (_e, view) => {
if (view === this.view) this.scrollPos = { top: view.scrollDOM.scrollTop, left: view.scrollDOM.scrollLeft };
},
}),
EditorView.domEventHandlers({
contextmenu: (e) => {
this.host.onContextMenu(this, e);
@@ -162,14 +188,28 @@ export class EditorSlot {
mount(parent: HTMLElement): EditorView {
if (this.view) return this.view;
this.syncContributions();
const view = new EditorView({
state: this.state,
parent,
dispatchTransactions: (trs, v) => this.onTransactions(trs, v),
});
this.view = view;
if (this.scroll) view.dispatch({ effects: this.scroll });
const kept = this.kept;
let view: EditorView;
if (kept) {
this.kept = null;
keptSlots.splice(keptSlots.indexOf(this), 1);
parent.appendChild(kept.dom);
// Detached, it lost its scroll offset.
kept.scrollDOM.scrollTop = this.scrollPos.top;
kept.scrollDOM.scrollLeft = this.scrollPos.left;
view = this.view = kept;
this.syncContributions();
// Plugins that skipped work while it was hidden catch up.
view.dispatch({ effects: this.scroll ? [this.scroll, viewShown.of(null)] : viewShown.of(null) });
} else {
this.syncContributions();
view = this.view = new EditorView({
state: this.stored,
parent,
dispatchTransactions: (trs, v) => this.onTransactions(trs, v),
});
if (this.scroll) view.dispatch({ effects: this.scroll });
}
this.scroll = null;
this.handle = { view, ctx: this.model.ctx() };
_addEditor(this.handle);
@@ -181,22 +221,38 @@ export class EditorSlot {
return view;
}
unmount() {
/** Hides the view: keeps it detached for the most recent tabs, else (or `keep: false`) destroys it. */
unmount(keep = true) {
const view = this.view;
if (!view) return;
this.savedTopLine = topLineOf(view);
this.state = view.state;
this.scroll = view.scrollSnapshot();
if (this.handle) _removeEditor(this.handle);
this.handle = null;
this.view = null;
this.kept = view;
if (!keep) return this.release();
view.dom.remove();
keptSlots.push(this);
if (keptSlots.length > KEPT_VIEWS) keptSlots.shift()!.release();
}
/** Destroys the kept view, keeping its state. */
private release() {
const view = this.kept;
if (!view) return;
this.kept = null;
const i = keptSlots.indexOf(this);
if (i >= 0) keptSlots.splice(i, 1);
this.savedTopLine = topLineAt(view, this.scrollPos.top);
this.scroll = scrollSnapshotAt(view, this.scrollPos);
this.stored = view.state;
view.destroy();
}
dispose() {
if (this.disposed) return;
this.detachHistory();
this.unmount();
this.unmount(false);
this.release();
this.disposed = true;
this.model.removeSlot(this);
}
@@ -237,13 +293,13 @@ export class EditorSlot {
}
/** Applies a transaction as if the user made it (synced, undoable). */
dispatchLocal(spec: TransactionSpec) {
if (this.view) {
this.view.dispatch(spec);
dispatchLocal(spec: TransactionSpec | Transaction) {
if (this.live) {
this.live.dispatch(spec);
return;
}
const tr = this.state.update(spec);
this.state = tr.state;
const tr = "startState" in spec ? spec : this.stored.update(spec);
this.stored = tr.state;
if (tr.docChanged) this.model.onLocal(tr.changes, this);
if (tr.docChanged && tr.isUserEvent("format.reformat")) this.model.redetectIndent();
}
@@ -251,15 +307,15 @@ export class EditorSlot {
/** Applies changes that are already in the model (other slot / backend). */
applyExternal(changes: ChangeSet, annotations: Annotation<unknown>[]) {
const spec: TransactionSpec = { changes, annotations };
if (this.view) this.view.dispatch(spec);
else this.state = this.state.update(spec).state;
if (this.live) this.live.dispatch(spec);
else this.stored = this.stored.update(spec).state;
}
/** Applies effects (reconfiguration) to the view or the stored state. */
reconfigure(effects: StateEffect<unknown>[]) {
if (!effects.length) return;
if (this.view) this.view.dispatch({ effects });
else this.state = this.state.update({ effects }).state;
if (this.live) this.live.dispatch({ effects });
else this.stored = this.stored.update({ effects }).state;
if (this.handle) this.handle.ctx = this.model.ctx();
}
@@ -278,7 +334,7 @@ export class EditorSlot {
const anchor = Math.min(Math.max(0, r.anchor), len);
const head = Math.min(Math.max(0, r.head ?? anchor), len);
if (!this.view) {
this.state = this.state.update({ selection: EditorSelection.single(anchor, head) }).state;
this.dispatchState({ selection: EditorSelection.single(anchor, head) });
this.pendingReveal = r;
return;
}
@@ -294,7 +350,11 @@ export class EditorSlot {
/** Caret and first visible line, for the persisted editor session. */
viewState(): { anchor: number; head: number; topLine?: number } {
const main = this.currentState().selection.main;
const topLine = this.view ? topLineOf(this.view) : this.savedTopLine;
const topLine = this.view
? topLineOf(this.view)
: this.kept
? topLineAt(this.kept, this.scrollPos.top)
: this.savedTopLine;
return { anchor: main.anchor, head: main.head, ...(topLine !== undefined ? { topLine } : {}) };
}
@@ -313,13 +373,19 @@ export class EditorSlot {
this.view.dispatch({ selection, effects: scroll ? [scroll] : [] });
return;
}
this.state = this.state.update({ selection }).state;
this.dispatchState({ selection });
if (scroll) {
this.scroll = scroll;
this.savedTopLine = v.topLine;
}
}
/** Updates the state of a hidden tab (its kept view, if any). */
private dispatchState(spec: TransactionSpec) {
if (this.kept) this.kept.dispatch(spec);
else this.stored = this.stored.update(spec).state;
}
caret(): { line: number; col: number; offset: number } {
const s = this.currentState();
const head = s.selection.main.head;
@@ -329,6 +395,17 @@ export class EditorSlot {
}
function topLineOf(view: EditorView): number {
const block = view.lineBlockAtHeight(Math.max(0, view.scrollDOM.scrollTop));
return topLineAt(view, view.scrollDOM.scrollTop);
}
/** `view.scrollSnapshot()` at a tracked offset: a detached view's scrollDOM reports 0. */
function scrollSnapshotAt(view: EditorView, pos: { top: number; left: number }): StateEffect<unknown> {
const atPos = Object.create(view) as EditorView;
Object.defineProperty(atPos, "scrollDOM", { value: { scrollTop: pos.top, scrollLeft: pos.left } });
return atPos.scrollSnapshot();
}
function topLineAt(view: EditorView, scrollTop: number): number {
const block = view.lineBlockAtHeight(Math.max(0, scrollTop));
return view.state.doc.lineAt(block.from).number - 1;
}
+23
Переглянути файл
@@ -93,6 +93,29 @@ export function openKeys(s: TabsState): Set<string> {
return keys;
}
/**
* Folds restored tabs into the current tabs without losing anything open: tabs
* already open stay (with their active tab), restored tabs missing by key are
* appended to the active pane. An empty window takes the restored state as-is,
* keeping its saved layout and active tab.
*/
export function mergeSessionTabs(current: TabsState, restored: TabsState): TabsState {
const target = current.panes[current.activePane];
if (!target || !Object.values(current.panes).some((p) => p.tabs.length)) return restored;
const seen = openKeys(current);
const additions: Tab[] = [];
for (const pane of Object.values(restored.panes))
for (const tab of pane.tabs) {
if (seen.has(tab.input.key)) continue;
seen.add(tab.input.key);
additions.push(tab);
}
if (!additions.length) return current;
const tabs = [...target.tabs, ...additions];
const mru = [...target.mru, ...additions.map((t) => t.id).filter((id) => !target.mru.includes(id))];
return withPane(current, { ...target, tabs, mru });
}
function withPane(s: TabsState, pane: Pane): TabsState {
return { ...s, panes: { ...s.panes, [pane.id]: pane } };
}
+1 -3
Переглянути файл
@@ -62,9 +62,7 @@ async function rename() {
function historyStep(slot: EditorSlot, forward = false) {
return (forward ? redo : undo)({
state: slot.currentState(),
dispatch: (tr) => {
slot.state = tr.state;
},
dispatch: (tr) => slot.dispatchLocal(tr),
});
}
+15 -9
Переглянути файл
@@ -8,7 +8,7 @@
import { Channel } from "@tauri-apps/api/core";
import { EditorSelection, MapMode, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
import { codeLenses, shownAgain, type CodeLens } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { commands, nextRequestId, type OutlineItem, type RequestId, type SymbolKind } from "@/platform/ipc";
import { useProject } from "@/platform/project";
@@ -35,7 +35,7 @@ const LENS_KINDS = new Set<SymbolKind>([
const MAX_PER_PASS = 40;
const CONCURRENCY = 4;
/** Lines above/below the viewport that are counted too, so scrolling feels instant. */
const MARGIN_LINES = 60;
const MARGIN_LINES = 10;
const usagesBackoff = featureBackoff();
export interface LensTarget {
@@ -114,11 +114,13 @@ class UsagesLensPlugin {
private outline: { doc: Text; targets: LensTarget[] } | null = null;
private generation = 0;
private pending = new Set<RequestId>();
private incomplete = false;
/** Keys whose count came back incomplete (the server was indexing): not shown, asked again once it settles. */
private incomplete = new Set<string>();
private unsubscribe: () => void;
private offReady: () => void;
private offSettled: () => void;
private offBlame: () => void;
private skipped = false;
constructor(private view: EditorView) {
this.refresh();
@@ -128,16 +130,19 @@ class UsagesLensPlugin {
// Counts computed while the server was indexing may be incomplete.
this.offReady = onLspRefresh("codeLens", () => {
this.cache.clear();
this.incomplete.clear();
this.refresh();
});
this.offSettled = onServerSettled(() => {
if (this.incomplete) this.refresh();
if (!this.incomplete.size) return;
this.incomplete.clear();
this.refresh();
});
this.offBlame = onBlameInvalidated(() => this.refresh());
}
update(u: ViewUpdate) {
if (u.docChanged || u.viewportChanged) this.refresh();
if (u.docChanged || u.viewportChanged || (this.skipped && shownAgain(u))) this.refresh();
}
private cancel() {
@@ -153,7 +158,8 @@ class UsagesLensPlugin {
private async run() {
const view = this.view;
if (!view.dom.isConnected) return;
this.skipped = !view.dom.isConnected;
if (this.skipped) return;
const doc = docOf(view);
if (!doc) return;
const gen = this.generation;
@@ -165,11 +171,11 @@ class UsagesLensPlugin {
}
const text = view.state.doc;
const wanted = () => gen === this.generation && view.state.doc === text;
this.incomplete = false;
// Blame runs beside the reference requests; it never holds up the counts.
const blame = authors ? blameFor(doc.path, text) : Promise.resolve(null);
if (this.cacheDoc !== text) {
this.cache = new Map();
this.incomplete = new Set();
this.cacheDoc = text;
}
try {
@@ -185,7 +191,7 @@ class UsagesLensPlugin {
.filter((t) => t.line >= firstLine && t.line <= lastLine)
.slice(0, MAX_PER_PASS);
const key = (t: LensTarget) => `${t.line}:${t.col}:${t.name}`;
const todo = usages ? visible.filter((t) => !this.cache.has(key(t))) : [];
const todo = usages ? visible.filter((t) => !this.cache.has(key(t)) && !this.incomplete.has(key(t))) : [];
let unavailable = false;
for (let i = 0; i < todo.length && !unavailable; i += CONCURRENCY) {
await Promise.all(
@@ -207,7 +213,7 @@ class UsagesLensPlugin {
);
}, wanted);
if (wanted()) {
if (incomplete) this.incomplete = true;
if (incomplete) this.incomplete.add(key(t));
else this.cache.set(key(t), refs.length);
}
} catch (e) {
+28 -1
Переглянути файл
@@ -1,7 +1,12 @@
import { describe, expect, it, vi } from "vitest";
import { Text } from "@codemirror/state";
import { EditorState, Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { viewShown, type EditorDocContext } from "@/editor/api";
import { lspDoc } from "./lsp";
import type { Diagnostic } from "@/bindings";
import {
diagnosticsAt,
diagnosticsExtension,
diagnosticsFor,
installDiagnosticsEvents,
setFileDiagnostics,
@@ -84,3 +89,25 @@ describe("toLintDiagnostics", () => {
expect(toLintDiagnostics(doc, [d(2, 1, 1)])[0]).toMatchObject({ from: doc.length - 1, to: doc.length });
});
});
describe("editor diagnostics in a view", () => {
it("skips a hidden view and catches up when it is shown again", async () => {
const view = new EditorView({
state: EditorState.create({
doc: "let x = 1;",
extensions: [lspDoc.of({ doc: 1, path: "/p/hidden.rs" } as EditorDocContext), diagnosticsExtension()],
}),
parent: document.body,
});
view.dom.remove();
setFileDiagnostics("/p/hidden.rs", "rust-analyzer", [d(0, 4, 5)]);
await Promise.resolve();
expect(diagnosticsAt(view, 4)).toHaveLength(0);
document.body.appendChild(view.dom);
view.dispatch({ effects: viewShown.of(null) });
await Promise.resolve();
expect(diagnosticsAt(view, 4)).toHaveLength(1);
view.destroy();
setFileDiagnostics("/p/hidden.rs", "rust-analyzer", []);
});
});
+8 -3
Переглянути файл
@@ -6,13 +6,13 @@
*/
import type { Text } from "@codemirror/state";
import { EditorSelection, StateEffect, StateField } from "@codemirror/state";
import { EditorView, ViewPlugin } from "@codemirror/view";
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { forEachDiagnostic, linter, setDiagnostics, type Diagnostic as LintDiagnostic } from "@codemirror/lint";
import type { Diagnostic, Severity } from "@/bindings";
import { commands, ideEventsReady, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { publishLocalDiagnostics } from "@/platform/localDiagnostics";
import { intentionsChanged, scrollbarMarks, type ScrollbarMark } from "@/editor/api";
import { intentionsChanged, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api";
import { rangeToOffsets } from "./positions";
import { lspDoc } from "./lsp";
import { showHint } from "./hint";
@@ -190,6 +190,7 @@ const diagnosticsSync = ViewPlugin.fromClass(
class {
private unsubscribe: () => void;
private pending = false;
private skipped = false;
constructor(private view: EditorView) {
const path = view.state.facet(lspDoc)?.path;
this.unsubscribe = path ? subscribeDiagnostics(path, () => this.schedule()) : () => {};
@@ -201,7 +202,8 @@ const diagnosticsSync = ViewPlugin.fromClass(
queueMicrotask(() => {
this.pending = false;
const path = this.view.state.facet(lspDoc)?.path;
if (!path || !this.view.dom.isConnected) return;
this.skipped = !this.view.dom.isConnected;
if (!path || this.skipped) return;
const lint = toLintDiagnostics(this.view.state.doc, diagnosticsFor(path));
const tr = setDiagnostics(this.view.state, lint);
this.view.dispatch({
@@ -210,6 +212,9 @@ const diagnosticsSync = ViewPlugin.fromClass(
});
});
}
update(u: ViewUpdate) {
if (this.skipped && shownAgain(u)) this.schedule();
}
destroy() {
this.unsubscribe();
}
+5 -2
Переглянути файл
@@ -5,6 +5,7 @@
* offers to disable hints of that kind.
*/
import { StateEffect, StateField, type Extension } from "@codemirror/state";
import { shownAgain } from "@/editor/api";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { call, commands, isTauri, type InlayHint } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
@@ -162,6 +163,7 @@ const inlayPlugin = ViewPlugin.fromClass(
private unsubscribe: () => void;
private offReady: () => void;
private offModifier: () => void;
private skipped = false;
constructor(private view: EditorView) {
this.refresh();
view.contentDOM.classList.toggle("cm-lsp-navigation-modifier", navigationModifierHeld());
@@ -178,11 +180,12 @@ const inlayPlugin = ViewPlugin.fromClass(
this.offReady = onLspRefresh("inlayHints", () => this.refresh());
}
update(u: ViewUpdate) {
if (u.docChanged || u.viewportChanged) this.refresh();
if (u.docChanged || u.viewportChanged || (this.skipped && shownAgain(u))) this.refresh();
}
async run() {
const view = this.view;
if (!view.dom.isConnected) return;
this.skipped = !view.dom.isConnected;
if (this.skipped) return;
const doc = docOf(view);
if (!doc) return;
if (!enabled(doc.language) || inlayBackoff.active(doc.doc)) {
+6 -3
Переглянути файл
@@ -1,7 +1,7 @@
/** Language-server and plugin lenses in the shared editor code-vision renderer. */
import { StateEffect, StateField, type Extension } from "@codemirror/state";
import { ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { codeLenses, whenSynced, type CodeLens, type EditorDocContext } from "@/editor/api";
import { codeLenses, shownAgain, whenSynced, type CodeLens, type EditorDocContext } from "@/editor/api";
import { call, commands } from "@/platform/ipc";
import { onNavigationProvidersChanged } from "@/editor/navigationProviders";
import { posToOffset } from "./positions";
@@ -24,6 +24,7 @@ export function serverCodeLenses(ctx: EditorDocContext): Extension {
new (class {
timer: ReturnType<typeof setTimeout> | undefined;
generation = 0;
skipped = false;
off: () => void;
constructor() {
const offs = [
@@ -40,7 +41,7 @@ export function serverCodeLenses(ctx: EditorDocContext): Extension {
this.timer = setTimeout(() => void this.run(), 400);
}
update(u: ViewUpdate) {
if (u.docChanged) this.schedule();
if (u.docChanged || (this.skipped && shownAgain(u))) this.schedule();
}
async run() {
const gen = this.generation;
@@ -48,7 +49,9 @@ export function serverCodeLenses(ctx: EditorDocContext): Extension {
try {
await whenSynced(view);
const result = await call(commands.lspCodeLens(ctx.doc));
if (gen !== this.generation || text !== view.state.doc || !view.dom.isConnected) return;
if (gen !== this.generation || text !== view.state.doc) return;
this.skipped = !view.dom.isConnected;
if (this.skipped) return;
view.dispatch({
effects: set.of(
result.flatMap((l) =>
+5 -3
Переглянути файл
@@ -15,7 +15,7 @@
*/
import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { shownAgain, type EditorDocContext } from "@/editor/api";
import { docOf, debounce, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
import { featureBackoff, onServerSettled } from "@/editor/lsp/availability";
import { readManyFileLines, withDocument } from "@/editor/lsp/files";
@@ -295,6 +295,7 @@ function markerSet(placed: readonly PlacedMarker[]): RangeSet<GutterMarker> {
class MarkersPlugin {
private refresh = debounce(() => void this.run(), DEBOUNCE_MS);
private generation = 0;
private skipped = false;
private request: RequestId | null = null;
private offSettings: () => void;
@@ -316,7 +317,7 @@ class MarkersPlugin {
// Other documents' markers may depend on this one.
changes++;
this.refresh();
} else if (u.viewportChanged) this.refresh();
} else if (u.viewportChanged || (this.skipped && shownAgain(u))) this.refresh();
// Other files may have changed meanwhile (a new implementation).
else if (u.focusChanged && u.view.hasFocus) {
const ctx = docOf(u.view);
@@ -337,7 +338,8 @@ class MarkersPlugin {
private async run() {
const view = this.view;
if (!view.dom.isConnected) return;
this.skipped = !view.dom.isConnected;
if (this.skipped) return;
const ctx = docOf(view);
if (!ctx) return;
const gen = ++this.generation;
+8 -3
Переглянути файл
@@ -33,8 +33,9 @@ beforeEach(() => {
document.body.append(tmp);
return {
svg:
`<svg id="${id}"><defs><marker id="${id}-arrow" orient="auto"><path d="M0,0L8,4"/></marker></defs>` +
`<path d="M0,4" marker-end="url(#${id}-arrow)"/><text>${text.split("\n")[0]}</text></svg>`,
`<svg id="${id}"><style>#${id} .flowchart-link{fill:none;}#${id} [id$="-arrow"] path{fill:#9fa2a8;}</style>` +
`<defs><marker id="${id}-arrow" orient="auto"><path d="M0,0L8,4"/></marker></defs>` +
`<path class="flowchart-link" d="M0,4" marker-end="url(#${id}-arrow)"/><text>${text.split("\n")[0]}</text></svg>`,
};
});
mockIPC((cmd, args) => (cmd === "fs_read_image" ? readImage((args as { path: string }).path) : null));
@@ -236,11 +237,15 @@ describe("mermaid diagrams in a reply", () => {
expect(idsOne).toHaveLength(2);
expect(idsTwo).toHaveLength(2);
expect(idsOne.filter((id) => idsTwo.includes(id))).toEqual([]);
// Every marker reference resolves inside its own copy.
// Every marker reference and scoped `<style>` selector resolves inside its own copy.
for (const root of [one.container, two.container]) {
const svg = root.querySelector(".mermaid-output svg")!;
const ref = svg.querySelector("[marker-end]")!.getAttribute("marker-end")!;
expect(new Set(idsOf(root)).has(/url\(#(.+)\)/.exec(ref)![1]!)).toBe(true);
expect(svg.querySelector("style")!.textContent).toContain(
`#${svg.getAttribute("id")} .flowchart-link{fill:none;}`,
);
expect(svg.querySelector("defs [id$='-arrow'] path")).not.toBeNull();
}
});
+7 -2
Переглянути файл
@@ -554,8 +554,11 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
while (entries && start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--;
const dragging = useRef(false);
// When the user last scrolled the conversation (wheel, touch, keys, the scrollbar, Find):
// only that leaves the end. WebKit also moves the offset back on its own while rows lay out.
// that leaves the end. WebKit also moves the offset back on its own while rows lay out,
// which comes with a change of the content height; a scroll without one is meant too (the
// scrollbar thumb, a jump), whatever moved it.
const userScrolled = useRef(-Infinity);
const seenHeight = useRef(0);
const markUserScroll = useCallback(() => {
userScrolled.current = performance.now();
}, []);
@@ -723,7 +726,9 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
onScroll={(e) => {
const el = e.currentTarget;
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
const byUser = dragging.current || performance.now() - userScrolled.current < 500;
const laidOut = el.scrollHeight !== seenHeight.current;
seenHeight.current = el.scrollHeight;
const byUser = dragging.current || performance.now() - userScrolled.current < 500 || !laidOut;
const stick = atEnd || (position.current.stick && !byUser);
// Still following: back to the end the offset was moved away from.
if (stick && !atEnd) el.scrollTop = el.scrollHeight;
+18 -1
Переглянути файл
@@ -362,7 +362,10 @@ describe("scrolling", () => {
let height = 1000;
Object.defineProperty(el, "scrollHeight", { configurable: true, get: () => height });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
// The conversation grew after it was scrolled to the end, or WebKit moved the offset back.
el.scrollTop = 600;
fireEvent.scroll(el);
// The conversation grew after it was scrolled to the end, or WebKit moved the offset back
// while rows laid out: both change the content height.
height = 1300;
el.scrollTop = 600;
fireEvent.scroll(el);
@@ -376,6 +379,20 @@ describe("scrolling", () => {
expect(await screen.findByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
});
it("leaves the end for a scroll that no layout caused, as dragging the scrollbar thumb", async () => {
render(<SessionEditor input={input("A")} />);
expect(await screen.findByText("Answer A")).toBeInTheDocument();
const el = stream();
Object.defineProperty(el, "scrollHeight", { configurable: true, value: 1000 });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.scrollTop = 600;
fireEvent.scroll(el);
el.scrollTop = 0;
fireEvent.scroll(el);
expect(el.scrollTop).toBe(0);
expect(await screen.findByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
});
it("offers one click back to the latest message after scrolling up", async () => {
render(<SessionEditor input={input("A")} />);
expect(await screen.findByText("Answer A")).toBeInTheDocument();
+261 -5
Переглянути файл
@@ -6,9 +6,14 @@ const projectCurrent = vi.fn();
const windowOpenProject = vi.fn();
const windowOpenFiles = vi.fn();
const windowTakeLaunch = vi.fn();
const windowCompleteLaunch = vi.fn();
const wslResolve = vi.fn();
const cancelClose = vi.fn();
const notify = vi.fn();
const listen = vi.fn();
vi.mock("@tauri-apps/api/webviewWindow", () => ({
getCurrentWebviewWindow: () => ({ listen }),
}));
vi.mock("@/platform/remote", async (original) => ({
...(await original<typeof import("@/platform/remote")>()),
isRemoteWindow: vi.fn(() => false),
@@ -36,6 +41,7 @@ vi.mock("@/platform/ipc", async (orig) => {
windowOpenProject: (...a: unknown[]) => windowOpenProject(...a),
windowOpenFiles: (...a: unknown[]) => windowOpenFiles(...a),
windowTakeLaunch: () => windowTakeLaunch(),
windowCompleteLaunch: () => windowCompleteLaunch(),
wslResolve: (p: string) => wslResolve(p),
lightEditOpen: (p: string) => lightEditOpen(p),
fsReadDir: (p: string) => fsReadDir(p),
@@ -47,18 +53,20 @@ vi.mock("@/platform/project", async (orig) => {
return { ...real, openProject: (p: string) => openProject(p) };
});
const diffs: unknown[] = [];
vi.mock("@/features/vcs/diffInput", () => ({ openVcsDiff: (data: unknown) => void diffs.push(data) }));
const openDiff = vi.fn(async (data: unknown) => void diffs.push(data));
vi.mock("@/features/vcs/diffInput", () => ({ openVcsDiff: (data: unknown) => openDiff(data) }));
const {
openProjectInWindow,
consumeLaunch,
installLaunchHandling,
openFiles,
openPaths,
openLightEditFileAsProject,
openProjectWithPolicy,
windowActions,
} = await import("../windows");
const { useProject } = await import("@/platform/project");
const { useProject, startupLaunchHandled } = await import("@/platform/project");
const { provideEditorService, provideNotificationService } = await import("@/workbench/contributions");
const { isRemoteWindow, connectRemote } = await import("@/platform/remote");
const { IpcError } = await import("@/platform/ipc");
@@ -66,11 +74,14 @@ provideNotificationService({ notify });
const opened: string[] = [];
let activePath: string | null = null;
provideEditorService({
openFile: async (path, options) =>
const openEditorFile = vi.fn<import("@/workbench/contributions").EditorService["openFile"]>(
async (path, options) =>
void opened.push(
`${path}${options?.focus ? " (focus)" : ""}${options?.selection ? ` @${options.selection.line}:${options.selection.col}` : ""}`,
),
);
provideEditorService({
openFile: openEditorFile,
openInput: async () => {},
activePath: () => activePath,
activeCursor: () => null,
@@ -81,18 +92,29 @@ provideEditorService({
const ok = (data: unknown) => ({ status: "ok", data });
const projectState = (root: string) => ({ project: { root, name: root, trusted: true, isGit: false, settings: {} } });
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>((done) => (resolve = done));
return { promise, resolve };
}
beforeEach(() => {
for (const f of [windowOpenProject, windowOpenFiles, windowTakeLaunch, wslResolve]) f.mockReset();
windowTakeLaunch.mockResolvedValue(null);
windowCompleteLaunch.mockReset().mockResolvedValue(ok(null));
wslResolve.mockResolvedValue(null);
vi.mocked(connectRemote).mockClear();
for (const f of [lightEditOpen, fsReadDir, openProject]) f.mockClear();
cancelClose.mockClear();
notify.mockClear();
listen.mockReset();
openEditorFile.mockClear();
openDiff.mockClear();
vi.mocked(isRemoteWindow).mockReturnValue(false);
opened.length = 0;
diffs.length = 0;
activePath = null;
useProject.setState({ project: null, lightEdit: false, settings: null } as never);
useProject.setState({ project: null, lightEdit: false, settings: null, opening: false, openingPath: null } as never);
});
describe("openProjectInWindow", () => {
@@ -272,12 +294,160 @@ describe("Open Containing Folder as Project", () => {
});
describe("launch", () => {
it("subscribes before taking a launch received while the listener is registering", async () => {
const registered = deferred();
const unlisten = vi.fn();
listen.mockImplementationOnce(async () => {
await registered.promise;
windowTakeLaunch.mockResolvedValueOnce({ project: "/p", files: ["/p/late.cs"] });
return unlisten;
});
const dispose = installLaunchHandling();
try {
await vi.waitFor(() => expect(listen).toHaveBeenCalledOnce());
expect(windowTakeLaunch).not.toHaveBeenCalled();
registered.resolve();
await startupLaunchHandled();
expect(opened).toEqual(["/p/late.cs (focus)"]);
} finally {
registered.resolve();
await startupLaunchHandled();
dispose();
}
expect(unlisten).toHaveBeenCalledOnce();
});
it("does not consume a launch after disposal while the listener is registering", async () => {
const registered = deferred();
const unlisten = vi.fn();
listen.mockImplementationOnce(async () => {
await registered.promise;
return unlisten;
});
windowTakeLaunch.mockResolvedValueOnce({ project: "/p", files: ["/p/a.cs"] });
const dispose = installLaunchHandling();
await vi.waitFor(() => expect(listen).toHaveBeenCalledOnce());
dispose();
registered.resolve();
await startupLaunchHandled();
expect(unlisten).toHaveBeenCalledOnce();
expect(windowTakeLaunch).not.toHaveBeenCalled();
expect(opened).toEqual([]);
});
it("serializes launch events while their project is opening", async () => {
const openedProject = deferred();
openProject.mockImplementationOnce(async (path) => {
await openedProject.promise;
const state = projectState(path);
useProject.setState({ ...state, lightEdit: false } as never);
return state.project;
});
let onLaunch: (() => void) | undefined;
listen.mockImplementationOnce(async (_event, handler: () => void) => {
onLaunch = handler;
return () => {};
});
windowTakeLaunch
.mockResolvedValueOnce({ project: "/p", files: ["/p/a.cs"] })
.mockResolvedValueOnce({ files: ["/p/b.cs"], positions: [{ path: "/p/b.cs", line: 10, column: 3 }] });
const dispose = installLaunchHandling();
try {
await vi.waitFor(() => expect(openProject).toHaveBeenCalledOnce());
onLaunch!();
openedProject.resolve();
await startupLaunchHandled();
await consumeLaunch();
expect(lightEditOpen).not.toHaveBeenCalled();
expect(opened).toEqual(["/p/a.cs (focus)", "/p/b.cs (focus) @10:3"]);
expect(openProject).toHaveBeenCalledOnce();
} finally {
openedProject.resolve();
await startupLaunchHandled();
dispose();
}
});
it("waits for an existing project restore before opening a received file", async () => {
useProject.setState({ opening: true, openingPath: "/p" });
windowTakeLaunch.mockResolvedValueOnce({
files: ["/p/a.cs"],
positions: [{ path: "/p/a.cs", line: 8, column: 2 }],
});
const request = consumeLaunch();
try {
await vi.waitFor(() => expect(windowTakeLaunch).toHaveBeenCalledOnce());
await new Promise((resolve) => setTimeout(resolve, 0));
expect(opened).toEqual([]);
expect(lightEditOpen).not.toHaveBeenCalled();
expect(windowCompleteLaunch).not.toHaveBeenCalled();
} finally {
useProject.setState({ ...projectState("/p"), opening: false, openingPath: null } as never);
await request;
}
expect(openProject).not.toHaveBeenCalled();
expect(lightEditOpen).not.toHaveBeenCalled();
expect(opened).toEqual(["/p/a.cs (focus) @8:2"]);
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
});
it("keeps the open project and applies later locations in order", async () => {
useProject.setState(projectState("/p") as never);
for (const line of [5, 8, 12]) {
windowTakeLaunch.mockResolvedValueOnce({
project: "/p",
files: ["/p/a.cs"],
positions: [{ path: "/p/a.cs", line, column: 0 }],
});
}
await Promise.all([consumeLaunch(), consumeLaunch(), consumeLaunch()]);
expect(openProject).not.toHaveBeenCalled();
expect(opened).toEqual(["/p/a.cs (focus) @5:0", "/p/a.cs (focus) @8:0", "/p/a.cs (focus) @12:0"]);
});
it("reports a missing file and still handles the next launch", async () => {
useProject.setState(projectState("/p") as never);
openEditorFile.mockRejectedValueOnce(new Error("File not found"));
windowTakeLaunch.mockResolvedValueOnce({ files: ["/p/missing.cs"] }).mockResolvedValueOnce({ files: ["/p/a.cs"] });
await Promise.all([consumeLaunch(), consumeLaunch()]);
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "File not found" }));
expect(opened).toEqual(["/p/a.cs (focus)"]);
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
});
it.each([
new Error("Project unavailable"),
new IpcError({ kind: "cancelled", message: "Project opening cancelled" }),
])("completes a failed or cancelled project launch and handles the next: %s", async (error) => {
openProject.mockRejectedValueOnce(error);
windowTakeLaunch
.mockResolvedValueOnce({ project: "/p", files: ["/p/a.cs"] })
.mockResolvedValueOnce({ project: "/q", files: ["/q/b.cs"] });
await Promise.all([consumeLaunch(), consumeLaunch()]);
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
expect(opened).toEqual(["/q/b.cs (focus)"]);
expect(useProject.getState().project?.root).toBe("/q");
});
it("keeps handling launches after completing a launch fails", async () => {
useProject.setState(projectState("/p") as never);
windowCompleteLaunch.mockRejectedValueOnce(new Error("Connection interrupted"));
windowTakeLaunch.mockResolvedValueOnce({ files: ["/p/a.cs"] }).mockResolvedValueOnce({ files: ["/p/b.cs"] });
const first = consumeLaunch();
const second = consumeLaunch();
await expect(first).rejects.toThrow("Connection interrupted");
await second;
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
expect(opened).toEqual(["/p/a.cs (focus)", "/p/b.cs (focus)"]);
});
it("opens the pending project once", async () => {
windowTakeLaunch.mockResolvedValueOnce({ project: "/p/launch", files: [] }).mockResolvedValueOnce(null);
await consumeLaunch();
await consumeLaunch();
expect(openProject).toHaveBeenCalledTimes(1);
expect(openProject).toHaveBeenCalledWith("/p/launch");
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
});
it("opens launched files in LightEdit without a project", async () => {
@@ -310,6 +480,7 @@ describe("launch", () => {
windowTakeLaunch.mockResolvedValueOnce({ project: null, files: [], diff: { left: "/x/a.txt", right: "/x/b.txt" } });
await consumeLaunch();
expect(lightEditOpen).toHaveBeenCalledWith("/x/b.txt");
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
expect(diffs).toEqual([
{
path: "/x/b.txt",
@@ -324,6 +495,7 @@ describe("launch", () => {
windowTakeLaunch.mockResolvedValueOnce({ project: null, files: [], diff: { left: "/p/a.txt", right: "/p/b.txt" } });
await consumeLaunch();
expect(lightEditOpen).not.toHaveBeenCalled();
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
expect(diffs).toEqual([
{
path: "/p/b.txt",
@@ -332,6 +504,90 @@ describe("launch", () => {
},
]);
});
it("completes a failed CLI diff and handles the next file launch", async () => {
useProject.setState(projectState("/p") as never);
openDiff.mockRejectedValueOnce(new Error("Diff file unavailable"));
windowTakeLaunch
.mockResolvedValueOnce({ files: [], diff: { left: "/p/a.txt", right: "/p/b.txt" } })
.mockResolvedValueOnce({ files: ["/p/next.cs"], positions: [{ path: "/p/next.cs", line: 8, column: 2 }] });
const first = consumeLaunch();
const next = consumeLaunch();
await expect(first).rejects.toThrow("Diff file unavailable");
await next;
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
expect(opened).toEqual(["/p/next.cs (focus) @8:2"]);
});
it("applies a later source location after a pending diff", async () => {
useProject.setState(projectState("/p") as never);
windowTakeLaunch
.mockResolvedValueOnce({ files: [], diff: { left: "/p/a.txt", right: "/p/b.txt" } })
.mockResolvedValueOnce({ files: ["/p/next.cs"], positions: [{ path: "/p/next.cs", line: 8, column: 2 }] });
await Promise.all([consumeLaunch(), consumeLaunch()]);
expect(diffs).toHaveLength(1);
expect(opened).toEqual(["/p/next.cs (focus) @8:2"]);
expect(openDiff.mock.invocationCallOrder[0]).toBeLessThan(openEditorFile.mock.invocationCallOrder[0]!);
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
});
it.each([
{ project: null, diffBeforeFiles: false },
{ project: "/p", diffBeforeFiles: false },
{ project: null, diffBeforeFiles: true },
{ project: "/p", diffBeforeFiles: true },
])(
"preserves the last request's focus for $project (diff first: $diffBeforeFiles)",
async ({ project, diffBeforeFiles }) => {
windowTakeLaunch.mockResolvedValueOnce({
project,
diffBeforeFiles,
files: ["/p/a.cs"],
positions: [{ path: "/p/a.cs", line: 8, column: 2 }],
diff: { left: "/p/left.txt", right: "/p/right.txt" },
});
await consumeLaunch();
expect(opened).toEqual(["/p/a.cs (focus) @8:2"]);
expect(diffs).toHaveLength(1);
const fileCall = openEditorFile.mock.invocationCallOrder[0]!;
const diffCall = openDiff.mock.invocationCallOrder[0]!;
expect(diffBeforeFiles ? diffCall : fileCall).toBeLessThan(diffBeforeFiles ? fileCall : diffCall);
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
},
);
it("opens later files when their preceding diff fails", async () => {
useProject.setState(projectState("/p") as never);
openDiff.mockRejectedValueOnce(new Error("Diff file unavailable"));
windowTakeLaunch.mockResolvedValueOnce({
files: ["/p/next.cs"],
positions: [{ path: "/p/next.cs", line: 8, column: 2 }],
diff: { left: "/p/a.txt", right: "/p/b.txt" },
diffBeforeFiles: true,
});
await consumeLaunch();
expect(opened).toEqual(["/p/next.cs (focus) @8:2"]);
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "Diff file unavailable" }));
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
});
it.each([false, true])(
"does not open a diff when its project launch is cancelled (diff first: %s)",
async (diffBeforeFiles) => {
openProject.mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Project opening cancelled" }));
windowTakeLaunch.mockResolvedValueOnce({
project: "/p",
diffBeforeFiles,
files: ["/p/a.cs"],
diff: { left: "/p/left.txt", right: "/p/right.txt" },
});
await consumeLaunch();
expect(opened).toEqual([]);
expect(diffs).toEqual([]);
expect(lightEditOpen).not.toHaveBeenCalled();
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
},
);
});
describe("Attach", () => {
+58 -25
Переглянути файл
@@ -65,10 +65,10 @@ async function openHere(path: string): Promise<boolean> {
}
}
/** Opens `files` as editor tabs of this window, focusing the last. */
/** Caret positions of files opened from the command line (`--line` / `--column`), 0-based. */
type Positions = ReadonlyArray<{ path: string; line: number; column: number }>;
/** Opens `files` as editor tabs of this window, focusing the last. */
async function openInEditor(files: readonly string[], positions: Positions = []): Promise<void> {
for (const [i, path] of files.entries()) {
const at = positions.find((p) => p.path === path);
@@ -77,7 +77,7 @@ async function openInEditor(files: readonly string[], positions: Positions = [])
focus: i === files.length - 1,
...(at ? { selection: { line: at.line, col: at.column } } : {}),
})
.catch((e) => console.warn(`could not open ${path}`, e));
.catch((e) => openFailed(path, e));
}
}
@@ -213,25 +213,53 @@ async function pickFiles(title: string): Promise<string[]> {
}
/** Takes this window's pending launch (if any) and opens its project, files or diff pair. */
export async function consumeLaunch(): Promise<void> {
let launchQueue: Promise<void> = Promise.resolve();
export function consumeLaunch(): Promise<void> {
const request = launchQueue.then(consumePendingLaunch);
launchQueue = request.catch(() => {});
return request;
}
async function consumePendingLaunch(): Promise<void> {
if (!isTauri()) return;
const launch = await commands.windowTakeLaunch().catch(() => null);
const files = launch?.files ?? [];
const positions = launch?.positions ?? [];
if (launch?.project) {
if (await openHere(launch.project)) await openInEditor(files, positions);
} else if (files.length) await openFilesHere(files, positions);
else if (launch?.diff) await openCliDiff(launch.diff);
else if (launch?.remote) {
const { target, path } = launch.remote;
await connectRemote(target, path).catch((e) =>
notifications().notify({
level: "error",
title: t("app.window.openFailed", { name: basename(path) }),
body: errorText(e),
key: `app.open:${path}`,
}),
);
if (!launch) return;
try {
// Session restoration may already be opening this window's project.
if (useProject.getState().opening) {
await new Promise<void>((resolve) => {
const off = useProject.subscribe((state) => {
if (!state.opening) {
off();
resolve();
}
});
});
}
const files = launch.files ?? [];
const positions = launch.positions ?? [];
if (launch.project && !(await openHere(launch.project))) return;
if (launch.diff && launch.diffBeforeFiles) {
const diff = launch.diff;
await openCliDiff(diff).catch((e) => openFailed(diff.right, e));
}
if (launch.project) {
await openInEditor(files, positions);
} else if (files.length) await openFilesHere(files, positions);
else if (launch.remote) {
const { target, path } = launch.remote;
await connectRemote(target, path).catch((e) =>
notifications().notify({
level: "error",
title: t("app.window.openFailed", { name: basename(path) }),
body: errorText(e),
key: `app.open:${path}`,
}),
);
}
if (launch.diff && !launch.diffBeforeFiles) await openCliDiff(launch.diff);
} finally {
await call(commands.windowCompleteLaunch());
}
}
@@ -517,14 +545,19 @@ export function installLaunchHandling(): () => void {
if (!isTauri()) return () => {};
let disposed = false;
let unlisten: (() => void) | undefined;
const launch = consumeLaunch();
const launch = import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => {
const off = await getCurrentWebviewWindow().listen(LAUNCH_EVENT, () => {
if (!disposed) void consumeLaunch().catch(console.warn);
});
if (disposed) off();
else {
unlisten = off;
// Subscribe before taking pending files so launches during startup aren't missed.
await consumeLaunch();
}
});
provideStartupLaunch(launch);
holdSplash(launch);
void import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => {
const off = await getCurrentWebviewWindow().listen(LAUNCH_EVENT, () => void consumeLaunch());
if (disposed) off();
else unlisten = off;
});
return () => {
disposed = true;
unlisten?.();
+5 -4
Переглянути файл
@@ -6,6 +6,7 @@
import { onEditorEvent, registerEditorContribution } from "@/editor/api";
import { executeAction, registerActions } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { isGradleBuildInput } from "@/platform/buildFiles";
import { onIdeEvent, type BuildModel, type BuildTool } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import {
@@ -58,8 +59,8 @@ export const MAVEN_WHEN = "projectOpen && build.maven";
export const GRADLE_WHEN = "projectOpen && build.gradle";
/** Build files whose creation / change / removal re-reads the model. */
const BUILD_FILE =
/(?:^|\/)(?:pom\.xml|(?:build|settings)\.gradle(?:\.kts)?|mvnw(?:\.cmd)?|gradlew(?:\.bat)?|gradle\.properties|gradle-wrapper\.properties|[^/]+\.versions\.toml)$/;
const isBuildFile = (path: string) =>
isGradleBuildInput(path) || /(?:^|[\\/])(?:pom\.xml|mvnw(?:\.cmd)?|gradlew(?:\.bat)?)$/.test(path);
function expandAll(tool: BuildTool) {
const { model, configs } = useBuild.getState();
@@ -234,10 +235,10 @@ export function activate(): () => void {
if (s.project) void loadModel();
}),
onEditorEvent((e) => {
if (e.type === "docSaved" && BUILD_FILE.test(e.path)) noteIdeSave(e.path);
if (e.type === "docSaved" && isBuildFile(e.path)) noteIdeSave(e.path);
}),
onIdeEvent("fsChanged", (e) => {
const changed = [...e.created, ...e.modified, ...e.removed].filter((p) => BUILD_FILE.test(p));
const changed = [...e.created, ...e.modified, ...e.removed].filter(isBuildFile);
if (!changed.length) return;
// Changes the IDE's own saves didn't make came from outside (a VCS update, another tool),
// also for a build file open in a tab.
+17
Переглянути файл
@@ -3,6 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
import { executeAction, registerAction, allActions, isActionEnabled } from "@/platform/actions";
import { setContext } from "@/platform/context";
import type { BuildModel, GradleModel, ProjectInfo, RunConfig } from "@/platform/ipc";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { GradleView, MavenView } from "./BuildToolView";
import { activate } from "./index";
@@ -112,6 +113,22 @@ afterEach(() => {
setContext("projectOpen", false);
});
it("re-reads the build model when an applied Groovy or Kotlin script changes", async () => {
vi.useFakeTimers();
try {
for (const path of ["/p/gradle/dependencies.gradle", "/p/gradle/dependencies.gradle.kts"]) {
const calls = mocks.model.mock.calls.length;
await act(async () => {
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [path], removed: [] });
await vi.advanceTimersByTimeAsync(300);
});
expect(mocks.model).toHaveBeenCalledTimes(calls + 1);
}
} finally {
vi.useRealTimers();
}
});
it("offers unlink on a root's context menu and persists a confirmed project setting", async () => {
render(<MavenView />);
fireEvent.contextMenu(screen.getByText("project-a"));
+6 -4
Переглянути файл
@@ -1,7 +1,7 @@
/** Plugin colors use the same native picker and provider-supplied replacement strings. */
import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
import { GutterMarker, ViewPlugin, gutter, type EditorView, type ViewUpdate } from "@codemirror/view";
import { type EditorDocContext } from "@/editor/api";
import { shownAgain, type EditorDocContext } from "@/editor/api";
import { rangeToOffsets } from "@/editor/lsp/positions";
import { pluginVisuals } from "@/editor/lsp/pluginVisuals";
import { onNavigationProvidersChanged } from "@/editor/navigationProviders";
@@ -118,6 +118,7 @@ export function pluginColorPreview(ctx: EditorDocContext): Extension {
new (class {
timer: ReturnType<typeof setTimeout> | undefined;
generation = 0;
skipped = false;
off: () => void;
constructor() {
this.off = onNavigationProvidersChanged(() => this.schedule());
@@ -129,15 +130,16 @@ export function pluginColorPreview(ctx: EditorDocContext): Extension {
this.timer = setTimeout(() => void this.run(), 300);
}
update(u: ViewUpdate) {
if (u.docChanged) this.schedule();
if (u.docChanged || (this.skipped && shownAgain(u))) this.schedule();
}
async run() {
const gen = this.generation;
const text = view.state.doc;
try {
const r = await pluginVisuals(view, ctx);
if (gen === this.generation && view.state.doc === text && view.dom.isConnected)
view.dispatch({ effects: setColors.of(r.colors) });
if (gen !== this.generation || view.state.doc !== text) return;
this.skipped = !view.dom.isConnected;
if (!this.skipped) view.dispatch({ effects: setColors.of(r.colors) });
} catch {
if (gen === this.generation && view.dom.isConnected) view.dispatch({ effects: setColors.of([]) });
}
+51
Переглянути файл
@@ -0,0 +1,51 @@
.view {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-3);
overflow: auto;
height: 100%;
color: var(--fg);
}
.view label {
display: flex;
flex-direction: column;
gap: var(--space-2);
min-width: 0;
}
.view select {
color: var(--fg);
background: var(--bg-elev);
border: 1px solid var(--border);
padding: var(--space-2);
max-width: 100%;
}
.toolbar {
display: flex;
gap: var(--space-2);
flex-wrap: wrap;
}
.list {
padding: 0;
margin: var(--space-2) 0;
list-style: none;
}
.list li {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
padding: var(--space-2) 0;
}
.list li span {
flex: 1 1 100%;
overflow-wrap: anywhere;
}
.error {
color: var(--danger);
white-space: pre-wrap;
}
.output {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
+225
Переглянути файл
@@ -0,0 +1,225 @@
import { executeAction } from "@/platform/actions";
import { useState } from "react";
import { useProject } from "@/platform/project";
import { useTx } from "@/platform/i18n";
import { Button, Input } from "@/ui";
import { useDotnet } from "./store";
import styles from "./Dotnet.module.css";
export function DotnetView() {
const s = useDotnet();
const tx = useTx();
const root = useProject((state) => state.project?.root ?? "");
const relative = (path: string) => (root && path.startsWith(root + "/") ? path.slice(root.length + 1) : path);
const [versions, setVersions] = useState<Record<string, string>>({});
const results = new Map<string, string[]>();
for (const p of s.found) results.set(p.id, [...new Set([...(results.get(p.id) ?? []), p.version])]);
const project = s.model.projects.find((p) => p.path === s.selected);
const action = (id: string, arg?: unknown) => void executeAction(`dotnet.${id}`, arg);
return (
<div className={styles.view}>
<div className={styles.toolbar}>
<Button disabled={s.busy} onClick={() => action("reload")}>
{tx("Reload .NET Workspace")}
</Button>
{s.busy && <Button onClick={() => action("cancel")}>{tx("Cancel")}</Button>}
</div>
{s.error && (
<div role="alert" className={styles.error}>
{s.error}
</div>
)}
{s.model.errors?.map((error) => (
<details key={error} className={styles.error}>
<summary>{tx("Project evaluation failed")}</summary>
{error}
</details>
))}
{s.model.solutions.map((solution) => (
<details key={solution.path}>
<summary>{solution.path.split("/").at(-1)}</summary>
{solution.projects.map((path) => (
<Button key={path} title={path} disabled={s.busy} onClick={() => action("select", { path })}>
{relative(path)}
</Button>
))}
</details>
))}
<label>
{tx(".NET project")}
<select
aria-label={tx(".NET project")}
value={s.selected}
disabled={s.busy}
onChange={(e) => action("select", { path: e.target.value })}
>
{!project && <option value="">{tx("Select a .NET project")}</option>}
{s.model.projects.map((p) => (
<option key={p.path} value={p.path}>
{relative(p.path)}
</option>
))}
</select>
</label>
{project && (
<>
<div className={styles.toolbar}>
<label>
{tx("Configuration")}
<select
aria-label={tx("Configuration")}
disabled={s.busy}
value={s.configuration}
onChange={(e) =>
action("select", { path: s.selected, configuration: e.target.value, framework: s.framework })
}
>
{project.configurations.map((c) => (
<option key={c}>{c}</option>
))}
</select>
</label>
<label>
{tx("Target framework")}
<select
aria-label={tx("Target framework")}
disabled={s.busy}
value={s.framework}
onChange={(e) =>
action("select", { path: s.selected, configuration: s.configuration, framework: e.target.value })
}
>
{project.frameworks.map((f) => (
<option key={f}>{f}</option>
))}
</select>
</label>
</div>
<div className={styles.toolbar}>
{["build", "restore", "clean"].map((op) => (
<Button key={op} disabled={s.busy} onClick={() => action(op)}>
{tx(op === "build" ? "Build" : op === "restore" ? "Restore" : "Clean")}
</Button>
))}
</div>
<details open>
<summary>{tx("Project references")}</summary>
{project.references.map((path) => (
<Button
key={path}
disabled={s.busy || !s.model.projects.some((p) => p.path === path)}
onClick={() => action("select", { path })}
>
{relative(path)}
</Button>
))}
</details>
<details open>
<summary>{tx("NuGet packages")}</summary>
<Button disabled={s.busy} onClick={() => action("packages")}>
{tx("Refresh packages")}
</Button>
<form
className={styles.toolbar}
onSubmit={(e) => {
e.preventDefault();
action("search", { query: s.query });
}}
>
<Input
aria-label={tx("Search NuGet packages")}
value={s.query}
onChange={(e) => useDotnet.setState({ query: e.target.value })}
/>
<Button type="submit" disabled={s.busy || !s.query.trim()}>
{tx("Search")}
</Button>
</form>
<ul className={styles.list}>
{[...results].map(([id, available]) => {
const version = available.includes(versions[id] ?? "") ? versions[id]! : available[0]!;
return (
<li key={id}>
<span>{id}</span>
<select
aria-label={tx("Version")}
value={version}
disabled={s.busy}
onChange={(e) => setVersions({ ...versions, [id]: e.target.value })}
>
{available.map((v) => (
<option key={v}>{v}</option>
))}
</select>
<Button disabled={s.busy} onClick={() => action("packageChange", { id, version })}>
{tx("Install / Update")}
</Button>
<Button disabled={s.busy} onClick={() => action("search", { query: id, exact: true })}>
{tx("Versions")}
</Button>
</li>
);
})}
</ul>
<ul className={styles.list}>
{s.packages.map((p) => (
<li key={`${p.id}:${p.version}`}>
<span>
{p.id} {p.version} {p.transitive ? tx("Transitive") : ""}
</span>
{!p.transitive && (
<>
<Button disabled={s.busy} onClick={() => action("search", { query: p.id, exact: true })}>
{tx("Versions")}
</Button>
<Button disabled={s.busy} onClick={() => action("packageChange", { id: p.id, version: null })}>
{tx("Remove")}
</Button>
</>
)}
</li>
))}
</ul>
</details>
{project.test && (
<details open>
<summary>{tx("Tests")}</summary>
<div className={styles.toolbar}>
<Button disabled={s.busy} onClick={() => action("discover")}>
{tx("Discover .NET Tests")}
</Button>
<Button disabled={s.busy} onClick={() => action("test")}>
{tx("Run all tests")}
</Button>
</div>
{project.runner !== "vstest" && !project.trx && (
<div>
{tx("Install the TRX reporting extension to show MTP results in the test panel.")}
<Button disabled={s.busy} onClick={() => action("installTrx")}>
{tx("Install TRX reporting")}
</Button>
</div>
)}
<ul className={styles.list}>
{s.tests.map((test) => (
<li key={test}>
<span>{test}</span>
<Button disabled={s.busy} onClick={() => action("test", test)}>
{tx("Run test")}
</Button>
</li>
))}
</ul>
</details>
)}
</>
)}
{s.output && (
<details>
<summary>{tx("Output")}</summary>
<pre className={styles.output}>{s.output}</pre>
</details>
)}
</div>
);
}
+125
Переглянути файл
@@ -0,0 +1,125 @@
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { registerToolWindow, toolWindowService } from "@/workbench/contributions";
import { DotnetView } from "./DotnetView";
import {
buildDotnet,
cancelDotnet,
changePackage,
discoverTests,
installTrx,
listPackages,
reloadDotnet,
resetDotnet,
runTests,
searchPackages,
selectDotnet,
} from "./store";
export function activate() {
const offWindow = registerToolWindow({
id: "dotnet",
title: ".NET",
icon: "file-csharp",
anchor: "right",
stripe: "onUse",
component: DotnetView,
});
const show = () => toolWindowService().show("dotnet", true);
const offActions = registerActions([
{
id: "dotnet.show",
title: ".NET Workspace",
category: "Build",
when: "projectOpen",
run: () => {
show();
return reloadDotnet();
},
},
{
id: "dotnet.reload",
title: "Reload .NET Workspace",
category: "Build",
when: "projectOpen",
run: () => reloadDotnet(),
},
{ id: "dotnet.cancel", title: "Cancel .NET Operation", category: "Build", run: () => cancelDotnet() },
{
id: "dotnet.select",
title: "Select .NET Project",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { path: string; configuration?: string; framework?: string };
return selectDotnet(a.path, a.configuration, a.framework);
},
},
...(["build", "restore", "clean"] as const).map((op) => ({
id: `dotnet.${op}`,
title: op === "build" ? "Build .NET Project" : op === "restore" ? "Restore .NET Project" : "Clean .NET Project",
category: "Build",
when: "projectOpen",
run: () => buildDotnet(op),
})),
{
id: "dotnet.packages",
title: "Refresh NuGet Packages",
category: "Build",
when: "projectOpen",
run: () => listPackages(),
},
{
id: "dotnet.search",
title: "Search NuGet Packages",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { query: string; exact?: boolean };
return searchPackages(a.query, a.exact);
},
},
{
id: "dotnet.packageChange",
title: "Change NuGet Package",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { id: string; version: string | null };
return changePackage(a.id, a.version);
},
},
{
id: "dotnet.discover",
title: "Discover .NET Tests",
category: "Run",
when: "projectOpen",
run: () => discoverTests(),
},
{
id: "dotnet.test",
title: "Run .NET Tests",
category: "Run",
when: "projectOpen",
run: async ({ arg }) => {
await runTests(typeof arg === "string" ? arg : undefined);
},
},
{
id: "dotnet.installTrx",
title: "Install TRX reporting",
category: "Build",
when: "projectOpen",
run: () => installTrx(),
},
]);
const offProject = useProject.subscribe((s, old) => {
if (s.project?.root !== old.project?.root) resetDotnet();
});
return () => {
resetDotnet();
offProject();
offActions();
offWindow();
};
}
+97
Переглянути файл
@@ -0,0 +1,97 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cancelDotnet, discoveredTests, packageList, selectDotnet, resetDotnet, useDotnet } from "./store";
import * as platform from "@/platform/dotnet";
afterEach(() => {
resetDotnet();
vi.restoreAllMocks();
});
it("recovers a project that failed the initial workspace scan", async () => {
const project: platform.DotnetProject = {
path: "/repo/Test.csproj",
name: "Test",
frameworks: ["net9.0"],
configurations: ["Debug"],
references: [],
packages: [],
test: true,
runner: "vstest",
adapter: "mstest",
trx: false,
};
vi.spyOn(platform, "evaluateProject").mockResolvedValue(project);
useDotnet.setState({ model: { projects: [], solutions: [], errors: [`${project.path}: failed`] } });
await selectDotnet(project.path);
expect(useDotnet.getState().model).toEqual({ projects: [project], solutions: [], errors: [] });
});
it("ignores an evaluation completed after switching workspaces", async () => {
let complete!: (p: platform.DotnetProject) => void;
vi.spyOn(platform, "evaluateProject").mockImplementation(
() =>
new Promise((resolve) => {
complete = resolve;
}),
);
const pending = selectDotnet("/repo/Test.csproj");
resetDotnet();
complete({ path: "/repo/Test.csproj", frameworks: ["net9.0"] } as platform.DotnetProject);
await pending;
expect(useDotnet.getState().selected).toBe("");
expect(useDotnet.getState().busy).toBe(false);
});
it("ignores an evaluation completed after cancellation", async () => {
let complete!: (p: platform.DotnetProject) => void;
vi.spyOn(platform, "evaluateProject").mockImplementation(
() =>
new Promise((resolve) => {
complete = resolve;
}),
);
const pending = selectDotnet("/repo/Test.csproj");
cancelDotnet();
complete({ path: "/repo/Test.csproj", frameworks: ["net9.0"] } as platform.DotnetProject);
await pending;
expect(useDotnet.getState().selected).toBe("");
expect(useDotnet.getState().busy).toBe(false);
expect(useDotnet.getState().error).toBe("");
});
describe("real dotnet discovery output", () => {
it.each([
"The following Tests are available:\n Passes\n Parameterized (1)\n\nProcess finished with exit code 0",
"The following Tests are available:\nPasses\nParameterized (1)\nTests succeeded: 'Tests.dll' [net9.0|x64]",
"Discovering tests from Tests.dll (net10.0|x64)\nDiscovered 2 tests in assembly - Tests.dll (net10.0|x64)\n Passes\n Parameterized (1)\n\nDiscovered 2 tests.",
])("extracts names without host and runner summaries", (output) => {
expect(discoveredTests(output)).toEqual(["Passes", "Parameterized (1)"]);
});
it("merges target frameworks and assemblies without duplicating names", () => {
expect(
discoveredTests(
"The following Tests are available:\n A.Tests.One\n\nThe following Tests are available:\n A.Tests.One\n B.Tests.Two\n",
),
).toEqual(["A.Tests.One", "B.Tests.Two"]);
});
it("keeps direct and transitive dependencies across frameworks", () => {
expect(
packageList({
projects: [
{
frameworks: [
{
topLevelPackages: [{ id: "Direct", resolvedVersion: "1.0" }],
transitivePackages: [{ id: "Child", resolvedVersion: "2.0" }],
},
{ transitivePackages: [{ id: "Direct", resolvedVersion: "1.0" }] },
],
},
],
}),
).toEqual([
{ id: "Direct", version: "1.0", transitive: false, latest: undefined },
{ id: "Child", version: "2.0", transitive: true, latest: undefined },
]);
});
});
+315
Переглянути файл
@@ -0,0 +1,315 @@
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import {
dotnet,
dotnetWorkspace,
evaluateProject,
dotnetTestArgs,
jsonOutput,
type DotnetWorkspace,
} from "@/platform/dotnet";
import { dirname, useProject } from "@/platform/project";
import type { RunConfig } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
export interface Package {
id: string;
version: string;
latest?: string;
transitive?: boolean;
}
interface State {
model: DotnetWorkspace;
selected: string;
framework: string;
configuration: string;
busy: boolean;
error: string;
output: string;
query: string;
packages: Package[];
found: Package[];
tests: string[];
}
const initial: State = {
model: { projects: [], solutions: [] },
selected: "",
framework: "",
configuration: "Debug",
busy: false,
error: "",
output: "",
query: "",
packages: [],
found: [],
tests: [],
};
export const useDotnet = create<State>(() => initial);
let controller: AbortController | undefined;
let generation = 0;
export function resetDotnet() {
generation++;
controller?.abort();
useDotnet.setState(initial);
}
export const selectedProject = () =>
useDotnet.getState().model.projects.find((p) => p.path === useDotnet.getState().selected);
async function task(work: (signal: AbortSignal) => Promise<Partial<State>>) {
controller?.abort();
const current = ++generation;
const abort = new AbortController();
controller = abort;
useDotnet.setState({ busy: true, error: "" });
try {
const patch = await work(abort.signal);
if (current === generation && !abort.signal.aborted) useDotnet.setState(patch);
} catch (e) {
if (current === generation && !abort.signal.aborted) useDotnet.setState({ error: String(e) });
} finally {
if (current === generation) {
controller = undefined;
useDotnet.setState({ busy: false });
}
}
}
export function cancelDotnet() {
controller?.abort();
}
export function reloadDotnet() {
const root = useProject.getState().project?.root;
if (!root) return;
return task(async (signal) => {
const model = await dotnetWorkspace(root, signal);
const old = useDotnet.getState();
const project = model.projects.find((p) => p.path === old.selected) ?? model.projects[0];
return {
model,
selected: project?.path ?? "",
configuration: "Debug",
framework: project?.frameworks[0] ?? "",
packages: [],
found: [],
tests: [],
};
});
}
export function selectDotnet(path: string, configuration?: string, framework?: string) {
const state = useDotnet.getState();
return task(async (signal) => {
const project = await evaluateProject(path, configuration ?? state.configuration, framework ?? "", signal);
return {
selected: path,
configuration: configuration ?? state.configuration,
framework: framework ?? project.frameworks[0] ?? "",
model: {
...state.model,
projects: state.model.projects.some((p) => p.path === path)
? state.model.projects.map((p) => (p.path === path ? project : p))
: [...state.model.projects, project],
errors: state.model.errors?.filter((error) => !error.startsWith(`${path}:`)),
},
packages: [],
found: [],
tests: [],
};
});
}
export function buildDotnet(operation: "build" | "restore" | "clean") {
const p = selectedProject();
if (!p) return;
const { framework, configuration } = useDotnet.getState();
return task(async (signal) => {
const output = await dotnet(
[
operation,
p.path,
...(operation === "restore"
? [`-p:Configuration=${configuration}`]
: ["--configuration", configuration, ...(framework ? ["--framework", framework] : [])]),
],
dirname(p.path),
signal,
);
const project = await evaluateProject(p.path, configuration, framework, signal);
const model = useDotnet.getState().model;
return {
output,
model: { ...model, projects: model.projects.map((item) => (item.path === p.path ? project : item)) },
};
});
}
interface PackageJson {
id: string;
resolvedVersion?: string;
requestedVersion?: string;
latestVersion?: string;
}
interface PackagesJson {
projects?: Array<{ frameworks?: Array<{ topLevelPackages?: PackageJson[]; transitivePackages?: PackageJson[] }> }>;
}
export function packageList(data: PackagesJson): Package[] {
const result = new Map<string, Package>();
for (const p of data.projects ?? [])
for (const f of p.frameworks ?? []) {
for (const [key, transitive] of [
["topLevelPackages", false],
["transitivePackages", true],
] as const)
for (const pkg of f[key] ?? [])
result.set(`${pkg.id}:${pkg.resolvedVersion}`, {
id: pkg.id,
version: pkg.resolvedVersion ?? pkg.requestedVersion ?? "",
latest: pkg.latestVersion,
transitive: transitive && result.get(`${pkg.id}:${pkg.resolvedVersion}`)?.transitive !== false,
});
}
return [...result.values()];
}
export function listPackages() {
const p = selectedProject();
if (!p) return;
return task(async (signal) => ({
packages: packageList(
jsonOutput(
await dotnet(["list", p.path, "package", "--include-transitive", "--format", "json"], dirname(p.path), signal),
),
),
}));
}
export function searchPackages(query: string, exact = false) {
const p = selectedProject();
if (!p || !query.trim()) return;
return task(async (signal) => {
const result = jsonOutput<{
problems?: Array<{ text?: string }>;
searchResult?: Array<{ packages?: Array<{ id: string; latestVersion?: string; version?: string }> }>;
}>(
await dotnet(
["package", "search", query.trim(), "--format", "json", "--take", "30", ...(exact ? ["--exact-match"] : [])],
dirname(p.path),
signal,
),
);
const found = (result.searchResult ?? []).flatMap((source) =>
(source.packages ?? []).map((pkg) => ({ id: pkg.id, version: pkg.latestVersion ?? pkg.version ?? "" })),
);
if (result.problems?.length) throw new Error(JSON.stringify(result.problems));
if (exact) found.reverse();
return { found };
});
}
export function changePackage(id: string, version: string | null) {
const p = selectedProject();
if (!p || !id) return;
return task(async (signal) => {
if (id === "Microsoft.Testing.Extensions.TrxReport" && version === "") {
await dotnet(["restore", p.path], dirname(p.path), signal);
const restored = await evaluateProject(
p.path,
useDotnet.getState().configuration,
useDotnet.getState().framework,
signal,
);
if (!restored.platformVersion)
throw new Error(tx("Microsoft.Testing.Platform was not found in the restored project."));
version = restored.platformVersion;
}
const output = await dotnet(
version === null
? ["remove", p.path, "package", id]
: ["add", p.path, "package", id, ...(version ? ["--version", version] : [])],
dirname(p.path),
signal,
);
if (version === null) await dotnet(["restore", p.path], dirname(p.path), signal);
const project = await evaluateProject(
p.path,
useDotnet.getState().configuration,
useDotnet.getState().framework,
signal,
);
const packages = packageList(
jsonOutput(
await dotnet(["list", p.path, "package", "--include-transitive", "--format", "json"], dirname(p.path), signal),
),
);
return {
output,
packages,
model: {
...useDotnet.getState().model,
projects: useDotnet.getState().model.projects.map((x) => (x.path === p.path ? project : x)),
},
};
});
}
export function discoveredTests(output: string): string[] {
const lines = output.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g"), "").split(/\r?\n/);
const tests = new Set<string>();
let listing = false;
for (const line of lines) {
if (/following Tests are available|Discovered tests:|Discovered \d+ tests? in assembly/i.test(line)) {
listing = true;
continue;
}
if (!listing) continue;
const name = line.trim();
if (
!name ||
/^(?:Process finished|Tests succeeded:|Tests failed:|Test run summary:|Discovered \d+ tests?\.|Total:)/.test(name)
) {
listing = false;
continue;
}
if (!/^(?:at |\[|.*\.dll\b)/.test(name)) tests.add(name);
}
return [...tests];
}
export function discoverTests() {
const p = selectedProject();
if (!p) return;
const s = useDotnet.getState();
return task(async (signal) => {
const output = await dotnet(
dotnetTestArgs(p, s.framework, ["--list-tests"], s.configuration),
dirname(p.path),
signal,
);
return { output, tests: discoveredTests(output) };
});
}
export function runTests(test?: string) {
const p = selectedProject();
if (!p) return;
const s = useDotnet.getState();
const method = test?.replace(/\(.*$/, "").trim();
const config: RunConfig = {
id: `dotnet:${p.path}:tests`,
name: test ?? p.name,
kind: "dotnet-test",
command: "dotnet",
args: [],
cwd: dirname(p.path),
env: {},
detected: true,
isTest: true,
debugAdapter: null,
params: {
project: p.path,
framework: s.framework,
configuration: s.configuration,
runner: p.runner,
adapter: p.adapter,
programArgs: "",
...(method ? { testMethods: JSON.stringify([method]) } : {}),
},
};
return executeAction("run.runConfig", config);
}
export function installTrx() {
return changePackage("Microsoft.Testing.Extensions.TrxReport", "");
}
+2
Переглянути файл
@@ -21,6 +21,7 @@ import {
} from "./vcs";
import { activate as terminal } from "./terminal";
import { activate as run } from "./run";
import { activate as dotnet } from "./dotnet";
import { activate as runAnything } from "./run-anything";
import { activate as macros } from "./macros";
import { activate as debuggerFeature } from "./debugger";
@@ -70,6 +71,7 @@ const features: Array<[string, Activate]> = [
["vcs", vcs],
["terminal", terminal],
["run", run],
["dotnet", dotnet],
["run-anything", runAnything],
["macros", macros],
["debugger", debuggerFeature],
+2 -1
Переглянути файл
@@ -9,6 +9,7 @@
import { Channel } from "@tauri-apps/api/core";
import { commands, type LibraryGroup, type RequestId } from "@/bindings";
import { mergeLibraryGroups } from "@/platform/libraries";
import { isGradleBuildInput } from "@/platform/buildFiles";
import { registerActions } from "@/platform/actions";
import { setLibraryRoots } from "@/editor/api";
import { call, isCancelled, isTauri, nextRequestId, onIdeEvent } from "@/platform/ipc";
@@ -73,7 +74,7 @@ export function touchesManifest(paths: readonly string[]): boolean {
return paths.some(
(p) =>
!/[\\/]node_modules[\\/]/.test(p) &&
MANIFESTS.has(p.slice(Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\")) + 1)),
(isGradleBuildInput(p) || MANIFESTS.has(p.slice(Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\")) + 1))),
);
}
+7
Переглянути файл
@@ -78,6 +78,13 @@ describe("External Libraries", () => {
expect(touchesManifest(["/p/src/package.json.bak", "/p/README.md"])).toBe(false);
});
it("refreshes when an applied Gradle script or properties file changes", () => {
expect(touchesManifest(["/p/gradle/dependencies.gradle"])).toBe(true);
expect(touchesManifest(["C:\\p\\gradle\\dependencies.gradle.kts"])).toBe(true);
expect(touchesManifest(["/p/gradle.properties"])).toBe(true);
expect(touchesManifest(["/p/node_modules/tool/dependencies.gradle"])).toBe(false);
});
it("marks files below library roots for read-only editors", () => {
dispose = setLibraryRoots("test", ["/py/lib/python3.12"]);
expect(isLibraryPath("/py/lib/python3.12/os.py")).toBe(true);
+6 -3
Переглянути файл
@@ -19,7 +19,7 @@ import {
} from "@codemirror/view";
import { highlightingFor } from "@codemirror/language";
import { highlightTree } from "@lezer/highlight";
import { type EditorDocContext } from "@/editor/api";
import { shownAgain, type EditorDocContext } from "@/editor/api";
import { rangeToOffsets } from "@/editor/lsp/positions";
import { pluginVisuals } from "@/editor/lsp/pluginVisuals";
import { findLanguageDescription, languageInfo, loadSupport } from "@/editor/core/cm/languages";
@@ -123,6 +123,7 @@ export function pluginLanguageVisuals(ctx: EditorDocContext): Extension {
timer: ReturnType<typeof setTimeout> | undefined;
generation = 0;
shown = false;
skipped = false;
off: () => void;
constructor() {
const a = onNavigationProvidersChanged(() => this.schedule(true));
@@ -147,7 +148,7 @@ export function pluginLanguageVisuals(ctx: EditorDocContext): Extension {
this.timer = setTimeout(() => void this.run(), 300);
}
update(u: ViewUpdate) {
if (u.docChanged) this.schedule();
if (u.docChanged || (this.skipped && shownAgain(u))) this.schedule();
}
async run() {
const generation = this.generation;
@@ -163,7 +164,9 @@ export function pluginLanguageVisuals(ctx: EditorDocContext): Extension {
marker: new ActionMarker(plugin, { ...a, icon: await resolveMarkerIcon(plugin, a.icon) }, ctx),
})),
);
if (generation !== this.generation || view.state.doc !== text || !view.dom.isConnected) return;
if (generation !== this.generation || view.state.doc !== text) return;
this.skipped = !view.dom.isConnected;
if (this.skipped) return;
this.shown = !!placed.length;
view.dispatch({
effects: [
+6 -3
Переглянути файл
@@ -6,7 +6,7 @@
*/
import { Compartment, RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { shownAgain, type EditorDocContext } from "@/editor/api";
import { navigationButton } from "./navigationButton";
import { pluginsBackend } from "./backend";
import { commands, type LineMarkerInfo } from "@/platform/ipc";
@@ -79,6 +79,7 @@ class PluginMarker extends GutterMarker {
class MarkersPlugin {
private timer: ReturnType<typeof setTimeout> | null = null;
private generation = 0;
private skipped = false;
private shown = false;
private off: () => void;
@@ -106,7 +107,7 @@ class MarkersPlugin {
}
update(u: ViewUpdate) {
if (u.docChanged) this.schedule();
if (u.docChanged || (this.skipped && shownAgain(u))) this.schedule();
}
private schedule() {
@@ -128,7 +129,9 @@ class MarkersPlugin {
icon: await resolveMarkerIcon(marker.pluginId, marker.icon),
})),
);
if (gen !== this.generation || this.view.state.doc !== text || !this.view.dom.isConnected) return;
if (gen !== this.generation || this.view.state.doc !== text) return;
this.skipped = !this.view.dom.isConnected;
if (this.skipped) return;
const placed = placeMarkers(text, resolved);
if (!placed.length && !this.view.state.field(markersField).length) return;
const effects: StateEffect<unknown>[] = [setMarkers.of(placed)];
+13
Переглянути файл
@@ -498,6 +498,19 @@ export function ConsoleView({
const items = virtualizer.getVirtualItems();
return (
<div className={styles.consoleWrap}>
{/* A console whose find bar is not driven by a toolbar (a stack-trace tab, say) still
needs a visible way in: the same Find the Run toolbar offers, over the output. */}
{controlledFindOpen === undefined && !findOpen && (
<button
type="button"
className={styles.consoleFindOpen}
title="Find…"
aria-label="Find in console"
onClick={() => setFindOpen(true)}
>
<Icon name="search" size={14} />
</button>
)}
{findOpen && (
<ConsoleFindBar
query={query}
+25
Переглянути файл
@@ -81,7 +81,32 @@
/* Console */
.consoleFindOpen {
position: absolute;
top: 6px;
right: 14px;
z-index: 2;
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
padding: 0;
border: none;
border-radius: 4px;
color: var(--fg-secondary);
background: var(--bg-toolbar);
opacity: 0.6;
}
.consoleFindOpen:hover,
.consoleFindOpen:focus-visible {
opacity: 1;
color: var(--fg-primary);
}
.consoleWrap {
position: relative;
flex: 1;
display: flex;
flex-direction: column;
+23 -2
Переглянути файл
@@ -12,11 +12,14 @@ import { isWindows } from "./jvmTypes";
import { typeFor } from "./types";
import { runTemplate } from "./runTemplates";
import { appendScriptArgs } from "./scriptArgs";
import { csharpTargets } from "./csharpTargets";
export type FileRole = "test" | "main" | "script" | null;
/** `django`: a Django project, whose default test module is `tests.py` (elsewhere a script). */
export function fileRole(relPath: string, content?: string, windows = isWindows(), django = false): FileRole {
if (/\.cs$/i.test(relPath) && content && csharpTargets(content).some((target) => target.kind === "test"))
return "test";
const name = relPath.split("/").pop() ?? relPath;
if (
/\.(test|spec)\.[cm]?[jt]sx?$/.test(name) ||
@@ -44,6 +47,7 @@ const stem = (p: string) => (p.split("/").pop() ?? p).replace(/\.[^.]+$/, "");
/** Kinds whose test configs can run a file of this extension. */
function testKinds(relPath: string): string[] {
if (/\.cs$/i.test(relPath)) return ["dotnet-test"];
if (/\.[cm]?[jt]sx?$/.test(relPath)) return ["npm", "deno", "bun"];
if (/\.py$/.test(relPath)) return ["pytest", "python", "django-test"];
if (/\.php$/.test(relPath)) return ["phpunit"];
@@ -57,6 +61,8 @@ function testKinds(relPath: string): string[] {
/** The module owning a configuration's targets, relative to the project root. */
export function configScope(config: RunConfig): string {
if (config.kind === "dotnet" || config.kind === "dotnet-test")
return dirOf((config.params?.project || "").replace(/\\/g, "/"));
return (
config.kind === "go"
? (config.params?.module ?? config.module ?? config.cwd ?? "")
@@ -210,11 +216,26 @@ export function testBasesFor(relPath: string, configs: RunConfig[]): RunConfig[]
* File-level test configuration for `relPath` (the closest matching test config,
* or `base`, narrowed to the file).
*/
export function testConfigFor(relPath: string, configs: RunConfig[], base?: RunConfig): RunConfig | null {
export function testConfigFor(
relPath: string,
configs: RunConfig[],
base?: RunConfig,
content?: string,
): RunConfig | null {
base ??= testBasesFor(relPath, configs)[0];
if (!base) return null;
const file = relToCwd(relPath, base);
switch (base.kind) {
case "dotnet-test": {
const methods = csharpTargets(content ?? "")
.filter((t) => t.kind === "test")
.map((t) => t.path.join("."));
return methods.length
? derived(base, relPath, {
params: { ...base.params, testMethods: JSON.stringify(methods) },
})
: null;
}
case "npm":
case "bun": {
const args = appendScriptArgs(base.command, base.args, [file]);
@@ -409,7 +430,7 @@ export function contextConfig(
windows = isWindows(),
): RunConfig | null {
const role = fileRole(relPath, content, windows, hasDjangoTests(configs));
if (role === "test") return testConfigFor(relPath, configs);
if (role === "test") return testConfigFor(relPath, configs, undefined, content);
if (role === "main") return mainConfigFor(relPath, configs) ?? scriptConfigFor(relPath, configs, windows, content);
if (role === "script") return scriptConfigFor(relPath, configs, windows, content);
return null;
+106
Переглянути файл
@@ -0,0 +1,106 @@
import { describe, expect, it } from "vitest";
import { csharpTargets } from "./csharpTargets";
import { targetConfig } from "./targets";
import { produceContext, produceFile, OPTIMISTIC } from "./producers";
import { dotnetTestType } from "./dotnetTypes";
import type { RunConfig } from "@/platform/ipc";
const config = (project: string): RunConfig => ({
id: project,
name: project,
command: "dotnet",
args: ["test", project],
kind: "dotnet-test",
params: { project, framework: "net9.0" },
cwd: null,
env: {},
detected: true,
isTest: true,
debugAdapter: null,
});
const source = `namespace Demo.Tests;
public class Calculator {
// [Fact] public void NotATest() {}
[Xunit.Fact]
public void Adds() { var s = "}"; }
[Theory, InlineData(1)]
public async Task Values(int n) { }
public class Nested {
[TestMethod] public void Child() {}
}
}`;
describe("C# editor test targets", () => {
it("tracks lines across multiline tokens and separate test classes", () => {
const text = `namespace Demo {
/* a comment
across lines */
class First {
[Fact]
void One(
) {}
}
class Second {
[TestCase(
1)]
void Two(int value) {}
}
}`;
expect(csharpTargets(text).map((t) => [t.line, t.path])).toEqual([
[3, ["Demo.First"]],
[5, ["Demo.First", "One"]],
[8, ["Demo.Second"]],
[11, ["Demo.Second", "Two"]],
]);
});
it("runs only methods declared in the chosen file", () => {
const result = produceFile(
{ path: "/repo/two/Tests.cs", root: "/repo", content: source, configs: [config("/repo/two/Two.csproj")] },
OPTIMISTIC,
);
expect(JSON.parse(result!.config!.params!.testMethods!)).toEqual([
"Demo.Tests.Calculator.Adds",
"Demo.Tests.Calculator.Values",
"Demo.Tests.Calculator+Nested.Child",
]);
});
it("finds qualified and multiline attributes, nested types, and skips literals/comments", () => {
expect(
csharpTargets(source)
.filter((t) => t.kind === "test")
.map((t) => [t.line, t.path]),
).toEqual([
[4, ["Demo.Tests.Calculator", "Adds"]],
[6, ["Demo.Tests.Calculator", "Values"]],
[8, ["Demo.Tests.Calculator+Nested", "Child"]],
]);
expect(csharpTargets("namespace A { namespace B { class C { [Test] void T() {} } } }").at(-1)?.path).toEqual([
"A.B.C",
"T",
]);
});
it("selects the owning project when same-named tests exist in sibling projects", () => {
const targets = csharpTargets(source);
const configs = [config("one/One.csproj"), config("two/Two.csproj")];
const result = targetConfig(
targets.find((t) => t.name === "Adds")!,
"two/Tests.cs",
configs,
source,
)!;
expect(result.params?.project).toBe("two/Two.csproj");
expect(dotnetTestType.commandLine(result.params!)?.args).toContain("FullyQualifiedName=Demo.Tests.Calculator.Adds");
});
it("normalizes absolute workspace project paths for caret/gutter launch", () => {
const result = produceContext(
{
path: "/repo/two/Tests.cs",
root: "/repo",
content: source,
line: 4,
configs: [config("/repo/one/One.csproj"), config("/repo/two/Two.csproj")],
},
OPTIMISTIC,
);
expect(result?.config?.params?.project).toBe("two/Two.csproj");
});
});
+64
Переглянути файл
@@ -0,0 +1,64 @@
import type { RunTarget } from "./targets";
/** Mask comments/literals without changing UTF-16 offsets or line breaks. */
export function csharpTargets(text: string): RunTarget[] {
const code = text.replace(
/\/\*[\s\S]*?\*\/|\/\/[^\n]*|@"(?:""|[^"])*"|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g,
(value) => value.replace(/[^\r\n]/g, " "),
);
const tokens =
/\bnamespace\s+([\w.]+)\s*([;{])|\b(?:class|record|struct)\s+(\w+)[^;{}]*\{|\[([^\]]*)\]|\b(\w+)\s*\([^;{}]*\)\s*(?=\{|=>)|[{};]/g;
const scopes: Array<{ name: string; depth: number; line: number; kind: "namespace" | "class" }> = [];
const out: RunTarget[] = [];
const suites = new Set<string>();
let depth = 0;
let line = 0;
let offset = 0;
let fileNamespace = "";
let test = false;
for (const match of code.matchAll(tokens)) {
const value = match[0];
while (offset < match.index) {
if (code.charCodeAt(offset) === 10) line++;
offset++;
}
if (match[1]) {
if (match[2] === ";") fileNamespace = match[1];
else scopes.push({ name: match[1], depth: ++depth, line, kind: "namespace" });
} else if (match[3]) {
scopes.push({ name: match[3], depth: ++depth, line, kind: "class" });
test = false;
} else if (match[4] !== undefined) {
test ||=
/(?:^|[.,\s])(?:Fact|Theory|Test|TestCase|TestCaseSource|TestMethod|DataTestMethod)(?:Attribute)?\b/.test(
match[4],
);
} else if (match[5]) {
if (test && scopes.some((s) => s.kind === "class")) {
const className = [
fileNamespace,
...scopes.filter((s) => s.kind === "namespace").map((s) => s.name),
scopes
.filter((s) => s.kind === "class")
.map((s) => s.name)
.join("+"),
]
.filter(Boolean)
.join(".");
const owner = scopes.filter((s) => s.kind === "class").at(-1)!;
if (!suites.has(className)) {
suites.add(className);
out.push({ line: owner.line, kind: "suite", name: owner.name, path: [className] });
}
out.push({ line, kind: "test", name: match[5], path: [className, match[5]] });
}
test = false;
} else if (value === "{") depth++;
else if (value === "}") {
depth--;
while (scopes.length && scopes.at(-1)!.depth > depth) scopes.pop();
test = false;
} else test = false;
}
return out;
}
+44 -2
Переглянути файл
@@ -2,6 +2,7 @@ import { call, commands, type RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import type { RunConfigTypeContribution } from "@/workbench/contributions";
import { parseArgs } from "./configs";
import { prepareDotnetTest } from "@/platform/dotnet";
function profile(p: Readonly<Record<string, string>>): {
applicationUrl?: string;
@@ -20,6 +21,7 @@ export function dotnetCommand(p: Readonly<Record<string, string>>, test = false)
args: [
...(test ? ["test", p.project || ""] : ["run", "--project", p.project || ""]),
...(p.framework ? ["--framework", p.framework] : []),
...(p.configuration ? ["--configuration", p.configuration] : []),
...(!test ? (p.launchProfile ? ["--launch-profile", p.launchProfile] : ["--no-launch-profile"]) : []),
...(p.programArgs?.trim() ? ["--", ...parseArgs(p.programArgs)] : []),
],
@@ -125,10 +127,50 @@ export const dotnetTestType: RunConfigTypeContribution = {
fields: [...dotnetProjectType.fields.slice(0, 2), { key: "programArgs", label: "Test arguments", mono: true }],
commandLine(p) {
const line = dotnetCommand({ ...p, programArgs: "" }, true);
return { ...line, args: [...line.args, ...parseArgs(p.programArgs || "")] };
if (p.runner === "mtp") line.args.splice(1, 0, "--project");
if (p.runner === "mtp-legacy")
line.args.push("-p:TestingPlatformCaptureOutput=false", "-p:TestingPlatformDotnetTestSupport=true");
let extra = parseArgs(p.programArgs || "");
if (p.runner === "mtp-legacy") {
const boundary = extra.indexOf("--");
if (boundary >= 0) {
line.args.push(...extra.slice(0, boundary));
extra = extra.slice(boundary + 1);
} else {
const runner: string[] = [];
const options = new Set(["--configuration", "-c", "--framework", "-f", "--runtime", "-r", "--verbosity", "-v"]);
for (let i = 0; i < extra.length; i++) {
const arg = extra[i]!;
if (options.has(arg)) line.args.push(arg, extra[++i] ?? "");
else if (/^(?:--no-build$|--no-restore$|-p:|-property:|--property:)/.test(arg)) line.args.push(arg);
else runner.push(arg);
}
extra = runner;
}
}
if (p.testMethods) {
const methods = JSON.parse(p.testMethods) as string[];
const flags = new Set(["--filter", "--filter-method"]);
extra = extra.filter((a, i, all) => !flags.has(a) && !flags.has(all[i - 1] ?? "") && !a.startsWith("--filter="));
const selection =
p.runner !== "vstest" && p.runner && p.adapter === "xunit"
? methods.flatMap((m) => ["--filter-method", m.includes(".") ? m : `*.${m}`])
: [
"--filter",
methods
.map((m) => `${m.includes(".") ? "FullyQualifiedName" : "Name"}=${m.replace(/[\\()&|=!~]/g, "\\$&")}`)
.join("|"),
];
const boundary = extra.indexOf("--");
extra.splice(boundary < 0 ? extra.length : boundary, 0, ...selection);
}
return {
...line,
args: [...line.args, ...(p.runner === "mtp-legacy" && extra[0] !== "--" ? ["--"] : []), ...extra],
};
},
async prepareLaunch(config) {
const resolved = await call(commands.runDotnetResolve(config, false));
const resolved = await prepareDotnetTest(await call(commands.runDotnetResolve(config, false)));
return { ...resolved, ...dotnetTestType.commandLine(resolved.params ?? {}) };
},
};
+7
Переглянути файл
@@ -44,6 +44,13 @@ function markCount(container: HTMLElement) {
}
describe("Run console find", () => {
it("offers a visible Find entry in a console without a toolbar (stack traces)", () => {
setup();
fireEvent.click(screen.getByRole("button", { name: "Find in console" }));
expect(screen.getByRole("search")).toBeInTheDocument();
expect(input()).toHaveFocus();
});
it("opens on ⌘F, searches as you type and highlights every match", () => {
const { log, view } = setup();
const bar = openFind(log);
+5 -2
Переглянути файл
@@ -126,6 +126,9 @@ function scopedInput<T extends Pick<ContextInput, "root" | "configs">>(input: T)
...c,
cwd: c.cwd == null ? c.cwd : relative(c.cwd),
...(c.module == null ? {} : { module: relative(c.module) }),
...(c.kind.startsWith("dotnet") && c.params?.project
? { params: { ...c.params, project: relative(c.params.project) } }
: {}),
...(c.kind === "go" && c.params?.module != null
? { params: { ...c.params, module: relative(c.params.module) } }
: {}),
@@ -743,7 +746,7 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
// Project-aware: test files through the project's test runner, Cargo / Go / Gradle / Maven mains.
const role = fileRole(rel, input.content, undefined, hasDjangoTests(configs));
if (role === "test") {
const found = testConfigFor(rel, configs);
const found = testConfigFor(rel, configs, undefined, input.content);
const test = found && goTestNamed(found, input);
if (test) return { name: test.name, scope: "file", config: test };
}
@@ -1102,7 +1105,7 @@ export function produceContextChoices(input: ContextInput, env: ToolEnv): Produc
for (const base of bases) {
const found = element
? targetConfig(element, rel, [...input.configs], input.content, base)
: testConfigFor(rel, [...input.configs], base);
: testConfigFor(rel, [...input.configs], base, input.content);
const config = found && goTestNamed(found, input, element?.name);
if (!config || out.some((o) => o.config?.id === config.id)) continue;
out.push({ name: config.name, scope: produced.scope, config, detail: base.name });
+19 -1
Переглянути файл
@@ -45,6 +45,7 @@ import {
} from "./testing";
import { PluginTestOutput } from "./testing/plugin";
import { GoTestOutput } from "./testing/go";
import { DotnetReports } from "./testing/dotnet";
import { moveToReportedClasses } from "./testing/jvm";
import { RubyTestOutput } from "./testing/ruby";
import { TeamcityOutput } from "./testing/teamcity";
@@ -94,6 +95,7 @@ export interface RunSession {
}
interface SessionRuntime {
dotnetReports?: DotnetReports;
resolveRequest?: { id: RequestId; controller: AbortController };
console: ConsoleModel;
tests: TestResults | null;
@@ -653,6 +655,7 @@ function newRuntime(config: RunConfig): SessionRuntime {
if (pluginTests && kind !== "system") pluginTests.feed(text);
if (parser && tests && kind !== "system" && !(kind === "stdout" && stdout)) tests.apply(parser.feed(text));
if (kind !== "system") for (const l of runtime.lineListeners) l(text);
if (kind !== "system") runtime.dotnetReports?.feed(text);
},
}),
queue: [],
@@ -894,12 +897,16 @@ export async function startRun(
if ((options.launch || launch.isTest) && launch.emulateTerminal) launch = { ...launch, emulateTerminal: false };
if (launch.emulateTerminal) rt.terminal = new TerminalOutput();
patchSession(sessionId, { terminal: !!launch.emulateTerminal });
const started =
let started =
launch.params?.framework === "plugin"
? launch
: launch.isTest
? await gradleTestLaunch(withTestReporting(launch))
: await gradleBootLaunch(launch);
if (launch.isTest && frameworkFor(launch) === "dotnet" && launch.params?.framework !== "plugin") {
rt.dotnetReports = new DotnetReports();
started = rt.dotnetReports.launch(started);
}
if (runtimes.get(sessionId)?.generation !== generation) return getSession(sessionId) ?? null;
const processStarted = performance.now();
const info = await startWithRemedies(started, () => call(commands.runStart(started, channel)));
@@ -1028,6 +1035,15 @@ function finishSession(sessionId: string, code: number | null) {
if (runtimes.get(sessionId) !== rt) return;
if (rt.tests && (rt.parser || rt.pluginTests)) {
rt.tests.apply(rt.parser?.end?.() ?? []);
if (rt.dotnetReports) {
try {
const events = await rt.dotnetReports.read((path) => call(commands.fsReadText(path)));
if (runtimes.get(sessionId) !== rt) return;
rt.tests.apply(events);
} catch (e) {
rt.console.append({ kind: "system", text: tx`Could not read .NET test results: ${String(e)}\n` });
}
}
// Surefire / Gradle print only failures and class totals: per-test results come from the XML reports.
if (frameworkFor(session.config) === "jvm") {
const reports = await jvmReports(session);
@@ -1120,6 +1136,8 @@ export function onRunExited(runId: RunId, code: number | null) {
const session = useRun.getState().sessions.find((s) => s.runId === runId);
if (!session) {
pendingExits.set(runId, code);
// Background project queries also use the process host without attaching a Run tab.
if (pendingExits.size > 128) pendingExits.delete(pendingExits.keys().next().value!);
return;
}
finishSession(session.id, code);
+15 -2
Переглянути файл
@@ -7,6 +7,7 @@
* one target derived from the project's detected test configurations.
*/
import { goTargets } from "./goTargets";
import { csharpTargets } from "./csharpTargets";
import { formatArgs } from "./configs";
import type { RunConfig } from "@/platform/ipc";
import { applicationConfig, jvmTestConfig } from "./application";
@@ -43,9 +44,10 @@ export interface RunTarget {
/** Above this size we skip detection (generated / minified files). */
export const MAX_SCAN = 400_000;
type Lang = "rust" | "js" | "python" | "php" | "go" | "jvm" | "ruby" | null;
type Lang = "rust" | "js" | "python" | "php" | "go" | "jvm" | "ruby" | "csharp" | null;
export function targetLanguage(relPath: string): Lang {
if (/\.cs$/i.test(relPath)) return "csharp";
if (/\.rs$/.test(relPath)) return "rust";
if (/\.[cm]?[jt]sx?$/.test(relPath)) return "js";
if (/\.py$/.test(relPath)) return "python";
@@ -355,6 +357,8 @@ export function detectRunTargets(text: string, relPath: string, django = false):
if (text.length > MAX_SCAN) return [];
const lines = text.split("\n");
switch (targetLanguage(relPath)) {
case "csharp":
return csharpTargets(text);
case "rust":
return rustTargets(lines, relPath);
case "js":
@@ -409,7 +413,7 @@ export function targetConfig(
return applicationConfig({ className: target.className, spring: target.spring }, relPath, configs);
return contextConfig(relPath, configs, content);
}
const file = testConfigFor(relPath, configs, base);
const file = testConfigFor(relPath, configs, base, content);
if (!file) return null;
if (target.className && (file.kind === "maven" || file.kind === "gradle"))
return jvmTestConfig(
@@ -427,6 +431,15 @@ export function targetConfig(
detected: true,
});
switch (file.kind) {
case "dotnet-test": {
const methods =
target.kind === "suite" && content
? csharpTargets(content)
.filter((t) => t.kind === "test" && t.path[0] === target.path[0])
.map((t) => t.path.join("."))
: [target.path.join(".")];
return { ...named(file.args), params: { ...file.params, testMethods: JSON.stringify(methods) } };
}
case "npm":
case "bun":
case "deno":
+146
Переглянути файл
@@ -0,0 +1,146 @@
import { describe, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { DotnetReports, trxEvents } from "./dotnet";
import { frameworkFor, TestResults } from "./index";
import { failedTestPaths, rerunFailedConfig } from "./rerun";
import { dotnetTestType } from "../dotnetTypes";
import xunitReport from "./fixtures/xunit.trx?raw";
import nunitReport from "./fixtures/nunit.trx?raw";
import mstestReport from "./fixtures/mstest.trx?raw";
import mtpReport from "./fixtures/mtp.trx?raw";
const config: RunConfig = {
id: "dotnet:tests",
name: "Tests",
kind: "dotnet-test",
command: "dotnet",
args: ["test", "Tests.csproj"],
cwd: null,
env: {},
detected: true,
isTest: true,
debugAdapter: null,
params: {
project: "Tests.csproj",
framework: "net9.0",
programArgs: "--filter Category=Unit --no-restore -- RunConfiguration.MaxCpuCount=1",
},
};
function report(adapter: string, source = "C:/My Project/bin/net9.0/Tests.dll") {
return `<TestRun xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Results>
<UnitTestResult testId="a" testName="adds (1)" outcome="Passed" duration="00:00:00.0015"/>
<UnitTestResult testId="b" testName="adds (2)" outcome="Failed" duration="00:01:02.5"><Output><ErrorInfo>
<Message>Expected &lt;3&gt;</Message><StackTrace>at Sample.Tests.Adds(Int32 value) in C:\\My Project\\Tests.cs:line 12</StackTrace>
</ErrorInfo><StdOut>captured output</StdOut></Output></UnitTestResult>
<UnitTestResult testId="c" testName="skipped" outcome="NotExecuted"/>
</Results>
<TestDefinitions>
<UnitTest id="a"><TestMethod codeBase="${source}" adapterTypeName="${adapter}" className="Sample.Tests" name="Adds"/></UnitTest>
<UnitTest id="b"><TestMethod codeBase="${source}" adapterTypeName="${adapter}" className="Sample.Tests" name="Adds"/></UnitTest>
<UnitTest id="c"><TestMethod codeBase="${source}" adapterTypeName="${adapter}" className="Sample.Tests" name="Skipped"/></UnitTest>
</TestDefinitions>
</TestRun>`;
}
describe(".NET test reports", () => {
it("finds source locations in MTP stack traces without the VSTest line prefix", () => {
expect(trxEvents(mtpReport)).toContainEqual(
expect.objectContaining({
type: "location",
location: { path: "C:\\Fixture\\Native\\Test1.cs", line: 5, resolve: "path" },
}),
);
});
it.each([xunitReport, nunitReport, mstestReport, mtpReport])(
"reads actual VSTest reports and selects failed methods",
async (xml) => {
const results = new TestResults();
results.apply(trxEvents(xml));
expect(results.counts()).toEqual({ passed: 2, failed: 2, skipped: 1, running: 0, total: 5 });
const rerun = await rerunFailedConfig(config, failedTestPaths(results));
const args = dotnetTestType.commandLine(rerun!.params!)!.args;
expect(args[args.indexOf("--filter") + 1]!.split("|").sort()).toEqual([
"FullyQualifiedName=Sample.CalculatorTests.Fails",
"FullyQualifiedName=Sample.CalculatorTests.Parameterized",
]);
},
);
it.each([
"executor://xunit/VsTestRunner2/netcoreapp",
"executor://nunit3testexecutor/",
"executor://mstestadapter/v2",
])("reads outcomes, parameterized names, duration and source from %s", (adapter) => {
const results = new TestResults();
results.apply(trxEvents(report(adapter)));
expect(results.counts()).toEqual({ passed: 1, failed: 1, skipped: 1, running: 0, total: 3 });
const failed = results.firstFailure()!;
expect(failed.name).toBe("adds (2)");
expect(failed.durationMs).toBe(62500);
expect(failed.output).toContain("Expected <3>");
expect(failed.output).toContain("captured output");
expect(failed.location).toEqual({ path: "C:\\My Project\\Tests.cs", line: 12, resolve: "path" });
});
it("keeps assemblies and target frameworks separate", () => {
const results = new TestResults();
for (const source of ["/a/bin/net9.0/Tests.dll", "/a/bin/net8.0/Tests.dll", "/b/bin/net9.0/Tests.dll"])
results.apply(trxEvents(report("adapter", source)));
expect(results.roots).toHaveLength(3);
expect(results.counts().total).toBe(9);
});
it("rejects incomplete reports", () => {
expect(() => trxEvents("<TestRun>")).toThrow("Invalid TRX");
expect(() => trxEvents("<html/>")).toThrow("Invalid TRX");
});
it("inserts the logger before runsettings and reads only this invocation's announced paths", async () => {
const reports = new DotnetReports();
const launched = reports.launch({ ...config, args: ["test", "Tests.csproj", "--", "x=y"] });
expect(launched.args).toEqual([
"test",
"Tests.csproj",
"--logger",
`trx;LogFilePrefix=${reports.prefix}`,
"--",
"x=y",
]);
const windows = `C:\\My Project\\TestResults\\${reports.prefix}_net9.0.trx`;
const unix = `/tmp/My Project/${reports.prefix}_net8.0.trx`;
reports.feed("Results File: C:\\old.trx");
reports.feed(`结果文件: ${windows}`);
reports.feed(`Results File: ${windows}`);
reports.feed(`Results File: ${unix}`);
const read = vi.fn().mockResolvedValue(report("adapter"));
expect(await reports.read(read)).not.toHaveLength(0);
expect(read.mock.calls).toEqual([[windows], [unix]]);
});
it("detects typed configurations and direct dotnet test commands", () => {
expect(frameworkFor(config)).toBe("dotnet");
expect(frameworkFor({ ...config, kind: "shell", command: "C:\\Program Files\\dotnet\\dotnet.exe" })).toBe("dotnet");
expect(frameworkFor({ ...config, kind: "shell", args: ["build"] })).toBe("auto");
});
it("keeps a method filter through .NET command regeneration and preserves runsettings", async () => {
const results = new TestResults();
results.apply(trxEvents(report("adapter")));
const selected = await rerunFailedConfig(config, failedTestPaths(results));
expect(selected).not.toBeNull();
const line = dotnetTestType.commandLine(selected!.params!);
expect(line?.args).toEqual([
"test",
"Tests.csproj",
"--framework",
"net9.0",
"--no-restore",
"--filter",
"FullyQualifiedName=Sample.Tests.Adds",
"--",
"RunConfiguration.MaxCpuCount=1",
]);
expect(config.params?.programArgs).toContain("Category=Unit");
});
});
+95
Переглянути файл
@@ -0,0 +1,95 @@
import type { RunConfig } from "@/platform/ipc";
import type { TestEvent } from "./types";
/** Only this invocation's reports are read, including each target framework's report. */
export class DotnetReports {
readonly prefix = `openidea-${crypto.randomUUID()}`;
private readonly paths = new Set<string>();
private mtp = false;
launch(config: RunConfig): RunConfig {
this.mtp = config.params?.runner === "mtp" || config.params?.runner === "mtp-legacy";
if (this.mtp) {
if (config.params?.trx === "false") return config;
const args = [...config.args];
if (config.params?.runner === "mtp-legacy" && !args.includes("--")) args.push("--");
if (!args.includes("--report-trx")) args.push("--report-trx");
return { ...config, args };
}
const boundary = config.args.indexOf("--");
const at = boundary < 0 ? config.args.length : boundary;
return {
...config,
args: [...config.args.slice(0, at), "--logger", `trx;LogFilePrefix=${this.prefix}`, ...config.args.slice(at)],
};
}
feed(line: string) {
// Match the absolute report path, independently of VSTest's UI language.
const path = /(?:[A-Za-z]:[\\/]|\/).*\.trx\s*$/i.exec(line)?.[0].trim();
if (path && (this.mtp || path.replace(/\\/g, "/").split("/").at(-1)?.startsWith(this.prefix))) this.paths.add(path);
}
async read(readText: (path: string) => Promise<string>): Promise<TestEvent[]> {
const events: TestEvent[] = [];
for (const path of this.paths) events.push(...trxEvents(await readText(path)));
return events;
}
}
const elements = (node: Document | Element, name: string) => Array.from(node.getElementsByTagNameNS("*", name));
const attr = (node: Element, name: string) => node.getAttribute(name) ?? "";
export function trxEvents(xml: string): TestEvent[] {
const doc = new DOMParser().parseFromString(xml, "application/xml");
if (elements(doc, "parsererror").length || doc.documentElement.localName !== "TestRun")
throw new Error("Invalid TRX report");
const definitions = new Map(
elements(doc, "UnitTest").map((test) => [attr(test, "id"), elements(test, "TestMethod")[0]]),
);
const events: TestEvent[] = [];
for (const result of elements(doc, "UnitTestResult")) {
const method = definitions.get(attr(result, "testId"));
if (!method) continue;
const className = attr(method, "className").split(",")[0]!;
const name = attr(method, "name").replace(/\(.*$/s, "").trim();
const source = attr(method, "codeBase").replace(/\\/g, "/");
if (!className || !name || !source) continue;
const display = (attr(result, "testName") || name).replace(
new RegExp(`^${className.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.`),
"",
);
const path = [source, className, name, ...(display === name ? [] : [display])];
const outcome = attr(result, "outcome");
const status =
outcome === "Passed" ? "passed" : /^(NotExecuted|Inconclusive|Pending)$/.test(outcome) ? "skipped" : "failed";
const duration = /^(\d+):(\d+):(\d+(?:\.\d+)?)$/.exec(attr(result, "duration"));
const durationMs = duration
? (Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 1000
: undefined;
events.push({ type: "result", path, status, durationMs });
for (const tag of ["Message", "StackTrace", "StdOut", "StdErr"]) {
for (const node of elements(result, tag)) {
for (const line of (node.textContent ?? "").split(/\r?\n/).slice(0, 200)) {
events.push({ type: "output", path, line });
const location = /\bin (.+\.(?:cs|fs|vb)):(?:line )?(\d+)/.exec(line);
if (location)
events.push({
type: "location",
path,
location: { path: location[1]!, line: Number(location[2]), resolve: "path" },
});
}
}
}
}
return events;
}
/** A parameterized case reruns its method, using adapter-independent TRX method identities. */
export function dotnetFilter(paths: string[][]): string | null {
if (paths.some((path) => path.length < 3)) return null;
const names = [...new Set(paths.map((path) => `${path[1]}.${path[2]}`))];
if (!names.length) return null;
return names.map((name) => `FullyQualifiedName=${name.replace(/[\\()&|=!~]/g, "\\$&")}`).join("|");
}
+81
Переглянути файл
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="utf-8"?>
<TestRun id="4f4d0116-da34-4a70-b983-520ff35f1ee3" name="user@host 2026-11-09 15:30:22" runUser="host\user" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Times creation="2026-11-09T15:30:22.0343603+08:00" queuing="2026-11-09T15:30:22.0343604+08:00" start="2026-11-09T15:30:21.6172521+08:00" finish="2026-11-09T15:30:22.0381244+08:00" />
<TestSettings name="default" id="efc46603-0a80-4af5-84e8-99efe216b685">
<Deployment runDeploymentRoot="user_host_2026-11-09_15_30_22" />
</TestSettings>
<Results>
<UnitTestResult executionId="a6aaf02e-b817-4528-8a65-a90a48fabb66" testId="3b2113bb-4c9e-76f3-cc23-ab79647789d4" testName="Parameterized (1)" computerName="host" duration="00:00:00.0001506" startTime="2026-11-09T15:30:21.9384780+08:00" endTime="2026-11-09T15:30:21.9479967+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Passed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="a6aaf02e-b817-4528-8a65-a90a48fabb66" />
<UnitTestResult executionId="dc9367d9-629b-429e-b893-948d6bdc6f71" testId="c5910b1b-ff19-2b97-141e-56e6f6c34aae" testName="Skipped" computerName="host" startTime="2026-11-09T15:30:21.9385124+08:00" endTime="2026-11-09T15:30:21.9406618+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="NotExecuted" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="dc9367d9-629b-429e-b893-948d6bdc6f71">
<Output>
<ErrorInfo>
<Message>demonstration</Message>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult executionId="b8788804-9f8a-4cdd-81d6-d00dcf77c3dc" testId="7d19e91c-5580-3412-cbca-804c6c9aad48" testName="Fails" computerName="host" duration="00:00:00.0242319" startTime="2026-11-09T15:30:21.9384945+08:00" endTime="2026-11-09T15:30:21.9692535+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Failed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="b8788804-9f8a-4cdd-81d6-d00dcf77c3dc">
<Output>
<ErrorInfo>
<Message>Assert.AreEqual failed. Expected:&lt;3&gt;. Actual:&lt;2&gt;. </Message>
<StackTrace> at Sample.CalculatorTests.Fails() in C:\fixtures\Mstest\Test1.cs:line 5&#xD;
at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)&#xD;
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)&#xD;
</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult executionId="7d898d82-c3eb-4c65-b0b4-d79e5a456e6e" testId="82759888-07e6-a8c5-f14e-7d93542bd7f7" testName="Parameterized (2)" computerName="host" duration="00:00:00.0225438" startTime="2026-11-09T15:30:21.9384879+08:00" endTime="2026-11-09T15:30:21.9692510+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Failed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="7d898d82-c3eb-4c65-b0b4-d79e5a456e6e">
<Output>
<ErrorInfo>
<Message>Assert.AreEqual failed. Expected:&lt;1&gt;. Actual:&lt;2&gt;. </Message>
<StackTrace> at Sample.CalculatorTests.Parameterized(Int32 value) in C:\fixtures\Mstest\Test1.cs:line 7&#xD;
at InvokeStub_CalculatorTests.Parameterized(Object, Span`1)&#xD;
at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)&#xD;
</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult executionId="6b8a19a3-e077-49cf-ae6a-ed568e077b51" testId="bfa6ea7d-3483-2c06-6e5a-cf49d98a6463" testName="Passes" computerName="host" duration="00:00:00.0018384" startTime="2026-11-09T15:30:21.9385027+08:00" endTime="2026-11-09T15:30:21.9479924+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Passed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="6b8a19a3-e077-49cf-ae6a-ed568e077b51" />
</Results>
<TestDefinitions>
<UnitTest name="Fails" storage="C:\fixtures\mstest\bin\debug\net9.0\openidea.mstest.tests.dll" id="7d19e91c-5580-3412-cbca-804c6c9aad48">
<Execution id="b8788804-9f8a-4cdd-81d6-d00dcf77c3dc" />
<TestMethod codeBase="C:\fixtures\Mstest\bin\Debug\net9.0\OpenIdea.Mstest.Tests.dll" adapterTypeName="executor://mstestadapter/v2" className="Sample.CalculatorTests" name="Fails" />
</UnitTest>
<UnitTest name="Passes" storage="C:\fixtures\mstest\bin\debug\net9.0\openidea.mstest.tests.dll" id="bfa6ea7d-3483-2c06-6e5a-cf49d98a6463">
<Execution id="6b8a19a3-e077-49cf-ae6a-ed568e077b51" />
<TestMethod codeBase="C:\fixtures\Mstest\bin\Debug\net9.0\OpenIdea.Mstest.Tests.dll" adapterTypeName="executor://mstestadapter/v2" className="Sample.CalculatorTests" name="Passes" />
</UnitTest>
<UnitTest name="Parameterized (2)" storage="C:\fixtures\mstest\bin\debug\net9.0\openidea.mstest.tests.dll" id="82759888-07e6-a8c5-f14e-7d93542bd7f7">
<Execution id="7d898d82-c3eb-4c65-b0b4-d79e5a456e6e" />
<TestMethod codeBase="C:\fixtures\Mstest\bin\Debug\net9.0\OpenIdea.Mstest.Tests.dll" adapterTypeName="executor://mstestadapter/v2" className="Sample.CalculatorTests" name="Parameterized" />
</UnitTest>
<UnitTest name="Parameterized (1)" storage="C:\fixtures\mstest\bin\debug\net9.0\openidea.mstest.tests.dll" id="3b2113bb-4c9e-76f3-cc23-ab79647789d4">
<Execution id="a6aaf02e-b817-4528-8a65-a90a48fabb66" />
<TestMethod codeBase="C:\fixtures\Mstest\bin\Debug\net9.0\OpenIdea.Mstest.Tests.dll" adapterTypeName="executor://mstestadapter/v2" className="Sample.CalculatorTests" name="Parameterized" />
</UnitTest>
<UnitTest name="Skipped" storage="C:\fixtures\mstest\bin\debug\net9.0\openidea.mstest.tests.dll" id="c5910b1b-ff19-2b97-141e-56e6f6c34aae">
<Execution id="dc9367d9-629b-429e-b893-948d6bdc6f71" />
<TestMethod codeBase="C:\fixtures\Mstest\bin\Debug\net9.0\OpenIdea.Mstest.Tests.dll" adapterTypeName="executor://mstestadapter/v2" className="Sample.CalculatorTests" name="Skipped" />
</UnitTest>
</TestDefinitions>
<TestEntries>
<TestEntry testId="3b2113bb-4c9e-76f3-cc23-ab79647789d4" executionId="a6aaf02e-b817-4528-8a65-a90a48fabb66" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="c5910b1b-ff19-2b97-141e-56e6f6c34aae" executionId="dc9367d9-629b-429e-b893-948d6bdc6f71" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="7d19e91c-5580-3412-cbca-804c6c9aad48" executionId="b8788804-9f8a-4cdd-81d6-d00dcf77c3dc" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="82759888-07e6-a8c5-f14e-7d93542bd7f7" executionId="7d898d82-c3eb-4c65-b0b4-d79e5a456e6e" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="bfa6ea7d-3483-2c06-6e5a-cf49d98a6463" executionId="6b8a19a3-e077-49cf-ae6a-ed568e077b51" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
</TestEntries>
<TestLists>
<TestList name="Results Not in a List" id="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestList name="All Loaded Results" id="19431567-8539-422a-85d7-44ee4e166bda" />
</TestLists>
<ResultSummary outcome="Failed">
<Counters total="5" executed="4" passed="2" failed="2" error="0" timeout="0" aborted="0" inconclusive="0" passedButRunAborted="0" notRunnable="0" notExecuted="0" disconnected="0" warning="0" completed="0" inProgress="0" pending="0" />
<Output>
<StdOut>Test Parallelization enabled for C:\fixtures\Mstest\bin\Debug\net9.0\OpenIdea.Mstest.Tests.dll (Workers: 32, Scope: MethodLevel)&#xD;
Test 'Skipped' was skipped in the test run.&#xD;
</StdOut>
</Output>
</ResultSummary>
</TestRun>
+85
Переглянути файл
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="utf-8"?>
<TestRun id="7ba330b2-4d2b-4252-bff2-c830b4419419" name="tester@testerS 2026-11-09 08:20:26.5318025" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Times creation="2026-11-09T08:20:26.4131456Z" queuing="2026-11-09T08:20:26.4131456Z" start="2026-11-09T08:20:26.4131456Z" finish="2026-11-09T08:20:26.532145Z" />
<TestSettings name="default" id="b2c5ea89-0c8e-4215-bf21-255314713779">
<Deployment runDeploymentRoot="tester_testerS_2026-11-09_08_20_26.5318025" />
</TestSettings>
<Results>
<UnitTestResult executionId="ba20361c-0fd9-4459-91ba-dd3fce5113ee" testId="1a494a91-d607-8a83-ba91-8f7c369bcf4b" testName="Passes" computerName="testerS" duration="00:00:00.0039472" startTime="2026-11-09T08:20:26.4953435+00:00" endTime="2026-11-09T08:20:26.5104697+00:00" testType="13CDC9D9-DDB5-4fa4-A97D-D965CCFC6D4B" outcome="Passed" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" relativeResultsDirectory="ba20361c-0fd9-4459-91ba-dd3fce5113ee" />
<UnitTestResult executionId="5a3992a8-81b9-4792-bba3-d11b23a7f817" testId="1b2eb6ed-b075-83ed-89ca-7b681a892bfe" testName="Fails" computerName="testerS" duration="00:00:00.0084826" startTime="2026-11-09T08:20:26.5132704+00:00" endTime="2026-11-09T08:20:26.5220913+00:00" testType="13CDC9D9-DDB5-4fa4-A97D-D965CCFC6D4B" outcome="Failed" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" relativeResultsDirectory="5a3992a8-81b9-4792-bba3-d11b23a7f817">
<Output>
<ErrorInfo>
<Message>Assert.AreEqual failed. Expected:&lt;3&gt;. Actual:&lt;2&gt;. 'expected' expression: '3', 'actual' expression: '1 + 1'.</Message>
<StackTrace> at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowAssertAreEqualFailed(Object expected, Object actual, String userMessage) in /_/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs:line 665
at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual[T](T expected, T actual, IEqualityComparer`1 comparer, String message, String expectedExpression, String actualExpression) in /_/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs:line 492
at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual[T](T expected, T actual, String message, String expectedExpression, String actualExpression) in /_/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs:line 405
at Sample.CalculatorTests.Fails() in C:\Fixture\Native\Test1.cs:line 5
at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult executionId="75ac56ba-d7ad-462c-b299-71d9d0f33569" testId="1cb231b0-d0fa-81b3-ab3e-bc60f4639b8c" testName="Skipped" computerName="testerS" duration="00:00:00.0000000" startTime="2026-11-09T08:20:26.5222673+00:00" endTime="2026-11-09T08:20:26.5224786+00:00" testType="13CDC9D9-DDB5-4fa4-A97D-D965CCFC6D4B" outcome="NotExecuted" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" relativeResultsDirectory="75ac56ba-d7ad-462c-b299-71d9d0f33569">
<Output>
<ErrorInfo>
<Message>demonstration</Message>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult executionId="1e66e9bf-4efd-4aad-9432-a2275cd88bfe" testId="139db31e-318e-8f04-91bc-5a0a5b61f929" testName="Parameterized (1)" computerName="testerS" duration="00:00:00.0000465" startTime="2026-11-09T08:20:26.5227177+00:00" endTime="2026-11-09T08:20:26.5240179+00:00" testType="13CDC9D9-DDB5-4fa4-A97D-D965CCFC6D4B" outcome="Passed" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" relativeResultsDirectory="1e66e9bf-4efd-4aad-9432-a2275cd88bfe" />
<UnitTestResult executionId="edda94ba-80df-4d23-b753-c01400520c31" testId="1ab155a7-5304-8dd0-a469-414f028392a5" testName="Parameterized (2)" computerName="testerS" duration="00:00:00.0003644" startTime="2026-11-09T08:20:26.5240566+00:00" endTime="2026-11-09T08:20:26.5252897+00:00" testType="13CDC9D9-DDB5-4fa4-A97D-D965CCFC6D4B" outcome="Failed" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" relativeResultsDirectory="edda94ba-80df-4d23-b753-c01400520c31">
<Output>
<ErrorInfo>
<Message>Assert.AreEqual failed. Expected:&lt;1&gt;. Actual:&lt;2&gt;. 'expected' expression: '1', 'actual' expression: 'value'.</Message>
<StackTrace> at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowAssertAreEqualFailed(Object expected, Object actual, String userMessage) in /_/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs:line 665
at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual[T](T expected, T actual, IEqualityComparer`1 comparer, String message, String expectedExpression, String actualExpression) in /_/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs:line 492
at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual[T](T expected, T actual, String message, String expectedExpression, String actualExpression) in /_/src/TestFramework/TestFramework/Assertions/Assert.AreEqual.cs:line 405
at Sample.CalculatorTests.Parameterized(Int32 value) in C:\Fixture\Native\Test1.cs:line 7
at InvokeStub_CalculatorTests.Parameterized(Object, Span`1)
at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
</Results>
<TestDefinitions>
<UnitTest name="Passes" storage="C:\Fixture\native\bin\debug\net10.0\native.dll" id="1a494a91-d607-8a83-ba91-8f7c369bcf4b">
<Execution id="ba20361c-0fd9-4459-91ba-dd3fce5113ee" />
<TestMethod codeBase="C:\Fixture\Native\bin\Debug\net10.0\Native.dll" adapterTypeName="executor://MSTestExtension/4.0.0" className="Sample.CalculatorTests" name="Passes" />
</UnitTest>
<UnitTest name="Fails" storage="C:\Fixture\native\bin\debug\net10.0\native.dll" id="1b2eb6ed-b075-83ed-89ca-7b681a892bfe">
<Execution id="5a3992a8-81b9-4792-bba3-d11b23a7f817" />
<TestMethod codeBase="C:\Fixture\Native\bin\Debug\net10.0\Native.dll" adapterTypeName="executor://MSTestExtension/4.0.0" className="Sample.CalculatorTests" name="Fails" />
</UnitTest>
<UnitTest name="Skipped" storage="C:\Fixture\native\bin\debug\net10.0\native.dll" id="1cb231b0-d0fa-81b3-ab3e-bc60f4639b8c">
<Execution id="75ac56ba-d7ad-462c-b299-71d9d0f33569" />
<TestMethod codeBase="C:\Fixture\Native\bin\Debug\net10.0\Native.dll" adapterTypeName="executor://MSTestExtension/4.0.0" className="Sample.CalculatorTests" name="Skipped" />
</UnitTest>
<UnitTest name="Parameterized (1)" storage="C:\Fixture\native\bin\debug\net10.0\native.dll" id="139db31e-318e-8f04-91bc-5a0a5b61f929">
<Execution id="1e66e9bf-4efd-4aad-9432-a2275cd88bfe" />
<TestMethod codeBase="C:\Fixture\Native\bin\Debug\net10.0\Native.dll" adapterTypeName="executor://MSTestExtension/4.0.0" className="Sample.CalculatorTests" name="Parameterized (1)" />
</UnitTest>
<UnitTest name="Parameterized (2)" storage="C:\Fixture\native\bin\debug\net10.0\native.dll" id="1ab155a7-5304-8dd0-a469-414f028392a5">
<Execution id="edda94ba-80df-4d23-b753-c01400520c31" />
<TestMethod codeBase="C:\Fixture\Native\bin\Debug\net10.0\Native.dll" adapterTypeName="executor://MSTestExtension/4.0.0" className="Sample.CalculatorTests" name="Parameterized (2)" />
</UnitTest>
</TestDefinitions>
<TestEntries>
<TestEntry testId="1a494a91-d607-8a83-ba91-8f7c369bcf4b" executionId="ba20361c-0fd9-4459-91ba-dd3fce5113ee" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" />
<TestEntry testId="1b2eb6ed-b075-83ed-89ca-7b681a892bfe" executionId="5a3992a8-81b9-4792-bba3-d11b23a7f817" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" />
<TestEntry testId="1cb231b0-d0fa-81b3-ab3e-bc60f4639b8c" executionId="75ac56ba-d7ad-462c-b299-71d9d0f33569" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" />
<TestEntry testId="139db31e-318e-8f04-91bc-5a0a5b61f929" executionId="1e66e9bf-4efd-4aad-9432-a2275cd88bfe" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" />
<TestEntry testId="1ab155a7-5304-8dd0-a469-414f028392a5" executionId="edda94ba-80df-4d23-b753-c01400520c31" testListId="8C84FA94-04C1-424b-9868-57A2D4851A1D" />
</TestEntries>
<TestLists>
<TestList name="Results Not in a List" id="8C84FA94-04C1-424b-9868-57A2D4851A1D" />
<TestList name="All Loaded Results" id="19431567-8539-422a-85d7-44ee4e166bda" />
</TestLists>
<ResultSummary outcome="Failed">
<Counters total="5" executed="4" passed="2" failed="2" error="0" timeout="0" aborted="0" inconclusive="0" passedButRunAborted="0" notRunnable="0" notExecuted="1" disconnected="0" warning="0" completed="0" inProgress="0" pending="0" />
<RunInfos>
<RunInfo computerName="testerS" outcome="Error" timestamp="2026-11-09T08:20:26.5377983">
<Text>Exit code indicates failure: '2'. Please refer to https://aka.ms/testingplatform/exitcodes for more information.</Text>
</RunInfo>
</RunInfos>
</ResultSummary>
</TestRun>
+96
Переглянути файл
@@ -0,0 +1,96 @@
<?xml version="1.0" encoding="utf-8"?>
<TestRun id="90ac1e90-367b-4ef0-9626-f509a293b66f" name="user@host 2026-11-09 15:29:36" runUser="host\user" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Times creation="2026-11-09T15:29:36.6222274+08:00" queuing="2026-11-09T15:29:36.6222276+08:00" start="2026-11-09T15:29:35.9112000+08:00" finish="2026-11-09T15:29:36.6258453+08:00" />
<TestSettings name="default" id="c4a8bf0e-5e08-4b32-a8fc-8bac196f28bf">
<Deployment runDeploymentRoot="user_host_2026-11-09_15_29_36" />
</TestSettings>
<Results>
<UnitTestResult executionId="3a5c8c54-b5a7-4b63-99c5-6aa007b68f06" testId="02a81555-5865-e7f8-12f4-5fc78b67a49c" testName="Parameterized(2)" computerName="host" duration="00:00:00.0003440" startTime="2026-11-09T15:29:36.5471392+08:00" endTime="2026-11-09T15:29:36.5474827+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Failed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="3a5c8c54-b5a7-4b63-99c5-6aa007b68f06">
<Output>
<ErrorInfo>
<Message> Assert.That(value, NUnit.Framework.Is.EqualTo(1))&#xD;
Expected: 1&#xD;
But was: 2&#xD;
</Message>
<StackTrace> at Sample.CalculatorTests.Parameterized(Int32 value) in C:\fixtures\Nunit\UnitTest1.cs:line 6&#xD;
at InvokeStub_CalculatorTests.Parameterized(Object, Span`1)&#xD;
1) at Sample.CalculatorTests.Parameterized(Int32 value) in C:\fixtures\Nunit\UnitTest1.cs:line 6&#xD;
at InvokeStub_CalculatorTests.Parameterized(Object, Span`1)&#xD;
</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult executionId="cd0ce076-d902-4bc5-8eb6-efac66f22f76" testId="4662c40d-3831-20b9-b93f-3d46f4c3745e" testName="Fails" computerName="host" duration="00:00:00.0197860" startTime="2026-11-09T15:29:36.5267595+08:00" endTime="2026-11-09T15:29:36.5465230+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Failed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="cd0ce076-d902-4bc5-8eb6-efac66f22f76">
<Output>
<ErrorInfo>
<Message> Assert.That(1 + 1, NUnit.Framework.Is.EqualTo(3))&#xD;
Expected: 3&#xD;
But was: 2&#xD;
</Message>
<StackTrace> at Sample.CalculatorTests.Fails() in C:\fixtures\Nunit\UnitTest1.cs:line 4&#xD;
1) at Sample.CalculatorTests.Fails() in C:\fixtures\Nunit\UnitTest1.cs:line 4&#xD;
</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult executionId="08316b31-c9f2-4e05-82d9-a6ac58f1bc7c" testId="2025c34d-a3f9-811e-8437-7eef0caa4776" testName="Passes" computerName="host" duration="00:00:00.0000550" startTime="2026-11-09T15:29:36.5479936+08:00" endTime="2026-11-09T15:29:36.5480483+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Passed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="08316b31-c9f2-4e05-82d9-a6ac58f1bc7c" />
<UnitTestResult executionId="41afb0d9-6a86-4345-b814-57bbe8e235a6" testId="c67f2006-84d4-f2e9-b3a1-3d8a46e07d6c" testName="Parameterized(1)" computerName="host" duration="00:00:00.0001110" startTime="2026-11-09T15:29:36.5470161+08:00" endTime="2026-11-09T15:29:36.5471267+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Passed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="41afb0d9-6a86-4345-b814-57bbe8e235a6" />
<UnitTestResult executionId="cab1aa72-f4f8-418d-b66a-353c4d14cbc9" testId="09a0e53e-a28a-d7cb-4241-5e576bbe92bd" testName="Skipped" computerName="host" duration="00:00:00.0000780" startTime="2026-11-09T15:29:36.5480515+08:00" endTime="2026-11-09T15:29:36.5481298+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="NotExecuted" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="cab1aa72-f4f8-418d-b66a-353c4d14cbc9">
<Output>
<StdOut>demonstration</StdOut>
<ErrorInfo>
<Message>demonstration</Message>
</ErrorInfo>
</Output>
</UnitTestResult>
</Results>
<TestDefinitions>
<UnitTest name="Skipped" storage="C:\fixtures\nunit\bin\debug\net9.0\openidea.nunit.tests.dll" id="09a0e53e-a28a-d7cb-4241-5e576bbe92bd">
<Execution id="cab1aa72-f4f8-418d-b66a-353c4d14cbc9" />
<TestMethod codeBase="C:\fixtures\Nunit\bin\Debug\net9.0\OpenIdea.Nunit.Tests.dll" adapterTypeName="executor://nunit3testexecutor/" className="Sample.CalculatorTests" name="Skipped" />
</UnitTest>
<UnitTest name="Parameterized(1)" storage="C:\fixtures\nunit\bin\debug\net9.0\openidea.nunit.tests.dll" id="c67f2006-84d4-f2e9-b3a1-3d8a46e07d6c">
<Execution id="41afb0d9-6a86-4345-b814-57bbe8e235a6" />
<TestMethod codeBase="C:\fixtures\Nunit\bin\Debug\net9.0\OpenIdea.Nunit.Tests.dll" adapterTypeName="executor://nunit3testexecutor/" className="Sample.CalculatorTests" name="Parameterized(1)" />
</UnitTest>
<UnitTest name="Parameterized(2)" storage="C:\fixtures\nunit\bin\debug\net9.0\openidea.nunit.tests.dll" id="02a81555-5865-e7f8-12f4-5fc78b67a49c">
<Execution id="3a5c8c54-b5a7-4b63-99c5-6aa007b68f06" />
<TestMethod codeBase="C:\fixtures\Nunit\bin\Debug\net9.0\OpenIdea.Nunit.Tests.dll" adapterTypeName="executor://nunit3testexecutor/" className="Sample.CalculatorTests" name="Parameterized(2)" />
</UnitTest>
<UnitTest name="Fails" storage="C:\fixtures\nunit\bin\debug\net9.0\openidea.nunit.tests.dll" id="4662c40d-3831-20b9-b93f-3d46f4c3745e">
<Execution id="cd0ce076-d902-4bc5-8eb6-efac66f22f76" />
<TestMethod codeBase="C:\fixtures\Nunit\bin\Debug\net9.0\OpenIdea.Nunit.Tests.dll" adapterTypeName="executor://nunit3testexecutor/" className="Sample.CalculatorTests" name="Fails" />
</UnitTest>
<UnitTest name="Passes" storage="C:\fixtures\nunit\bin\debug\net9.0\openidea.nunit.tests.dll" id="2025c34d-a3f9-811e-8437-7eef0caa4776">
<Execution id="08316b31-c9f2-4e05-82d9-a6ac58f1bc7c" />
<TestMethod codeBase="C:\fixtures\Nunit\bin\Debug\net9.0\OpenIdea.Nunit.Tests.dll" adapterTypeName="executor://nunit3testexecutor/" className="Sample.CalculatorTests" name="Passes" />
</UnitTest>
</TestDefinitions>
<TestEntries>
<TestEntry testId="02a81555-5865-e7f8-12f4-5fc78b67a49c" executionId="3a5c8c54-b5a7-4b63-99c5-6aa007b68f06" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="4662c40d-3831-20b9-b93f-3d46f4c3745e" executionId="cd0ce076-d902-4bc5-8eb6-efac66f22f76" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="2025c34d-a3f9-811e-8437-7eef0caa4776" executionId="08316b31-c9f2-4e05-82d9-a6ac58f1bc7c" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="c67f2006-84d4-f2e9-b3a1-3d8a46e07d6c" executionId="41afb0d9-6a86-4345-b814-57bbe8e235a6" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="09a0e53e-a28a-d7cb-4241-5e576bbe92bd" executionId="cab1aa72-f4f8-418d-b66a-353c4d14cbc9" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
</TestEntries>
<TestLists>
<TestList name="Results Not in a List" id="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestList name="All Loaded Results" id="19431567-8539-422a-85d7-44ee4e166bda" />
</TestLists>
<ResultSummary outcome="Failed">
<Counters total="5" executed="4" passed="2" failed="2" error="0" timeout="0" aborted="0" inconclusive="0" passedButRunAborted="0" notRunnable="0" notExecuted="0" disconnected="0" warning="0" completed="0" inProgress="0" pending="0" />
<Output>
<StdOut>NUnit Adapter 4.6.0.0: Test execution started&#xD;
Running all tests in C:\fixtures\Nunit\bin\Debug\net9.0\OpenIdea.Nunit.Tests.dll&#xD;
NUnit3TestExecutor discovered 5 of 5 NUnit test cases using Current Discovery mode, Non-Explicit run&#xD;
Skipped: demonstration&#xD;
NUnit Adapter 4.6.0.0: Test execution complete&#xD;
Test 'Skipped' was skipped in the test run.&#xD;
</StdOut>
</Output>
</ResultSummary>
</TestRun>
+113
Переглянути файл
@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="utf-8"?>
<TestRun id="6730bf1d-c08d-4929-bb05-3e13f571e02b" name="user@host 2026-11-09 15:31:14" runUser="host\user" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Times creation="2026-11-09T15:31:14.9191388+08:00" queuing="2026-11-09T15:31:14.9191389+08:00" start="2026-11-09T15:31:14.3506101+08:00" finish="2026-11-09T15:31:14.9238336+08:00" />
<TestSettings name="default" id="3df9757c-2b02-4a46-b1db-4ee1a8fa15dd">
<Deployment runDeploymentRoot="user_host_2026-11-09_15_31_14" />
</TestSettings>
<Results>
<UnitTestResult executionId="45bed8c3-6316-465f-9ebd-b1ce3e829452" testId="f52bc9c9-8df9-6fd9-934e-9b7c2f64f597" testName="Sample.CalculatorTests.Passes" computerName="host" duration="00:00:00.0000540" startTime="2026-11-09T15:31:14.8478668+08:00" endTime="2026-11-09T15:31:14.8478669+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Passed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="45bed8c3-6316-465f-9ebd-b1ce3e829452" />
<UnitTestResult executionId="b092dfdf-2c5c-48fd-b642-21df8c45636d" testId="7c64262f-2dfc-ba5e-c769-0c95cf182a76" testName="Sample.CalculatorTests.Fails" computerName="host" duration="00:00:00.0001171" startTime="2026-11-09T15:31:14.8483013+08:00" endTime="2026-11-09T15:31:14.8483014+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Failed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="b092dfdf-2c5c-48fd-b642-21df8c45636d">
<Output>
<ErrorInfo>
<Message>Assert.Equal() Failure: Values differ&#xD;
Expected: 3&#xD;
Actual: 2</Message>
<StackTrace> at Sample.CalculatorTests.Fails() in C:\fixtures\Xunit\UnitTest1.cs:line 4&#xD;
at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)&#xD;
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult executionId="cd875b78-eac0-4818-8568-9f94369a9f82" testId="0352e892-15b1-279b-751c-4ef8fa3b78a4" testName="Sample.CalculatorTests.Parameterized(value: 1)" computerName="host" duration="00:00:00.0008224" startTime="2026-11-09T15:31:14.8477406+08:00" endTime="2026-11-09T15:31:14.8477407+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Passed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="cd875b78-eac0-4818-8568-9f94369a9f82" />
<UnitTestResult executionId="d881161e-8fea-4081-be74-367b5a2b1cdd" testId="dba96a25-d6a4-9ba0-5868-d87d247475d6" testName="Sample.CalculatorTests.Skipped" computerName="host" duration="00:00:00.0010000" startTime="2026-11-09T15:31:14.8488028+08:00" endTime="2026-11-09T15:31:14.8488029+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="NotExecuted" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="d881161e-8fea-4081-be74-367b5a2b1cdd">
<Output>
<ErrorInfo>
<Message>demonstration</Message>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult executionId="4f7a68de-fbed-4a0f-bb49-d33262b6b321" testId="342fa793-ffa3-5734-772a-79a8f289629f" testName="Sample.CalculatorTests.Parameterized(value: 2)" computerName="host" duration="00:00:00.0592671" startTime="2026-11-09T15:31:14.8455506+08:00" endTime="2026-11-09T15:31:14.8455607+08:00" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" outcome="Failed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" relativeResultsDirectory="4f7a68de-fbed-4a0f-bb49-d33262b6b321">
<Output>
<ErrorInfo>
<Message>Assert.Equal() Failure: Values differ&#xD;
Expected: 1&#xD;
Actual: 2</Message>
<StackTrace> at Sample.CalculatorTests.Parameterized(Int32 value) in C:\fixtures\Xunit\UnitTest1.cs:line 6&#xD;
at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)&#xD;
at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
</Results>
<TestDefinitions>
<UnitTest name="Sample.CalculatorTests.Parameterized(value: 2)" storage="C:\fixtures\xunit\bin\debug\net9.0\openidea.xunit.tests.dll" id="342fa793-ffa3-5734-772a-79a8f289629f">
<Execution id="4f7a68de-fbed-4a0f-bb49-d33262b6b321" />
<TestMethod codeBase="C:\fixtures\Xunit\bin\Debug\net9.0\OpenIdea.Xunit.Tests.dll" adapterTypeName="executor://xunit/VsTestRunner2/netcoreapp" className="Sample.CalculatorTests" name="Parameterized" />
</UnitTest>
<UnitTest name="Sample.CalculatorTests.Skipped" storage="C:\fixtures\xunit\bin\debug\net9.0\openidea.xunit.tests.dll" id="dba96a25-d6a4-9ba0-5868-d87d247475d6">
<Execution id="d881161e-8fea-4081-be74-367b5a2b1cdd" />
<TestMethod codeBase="C:\fixtures\Xunit\bin\Debug\net9.0\OpenIdea.Xunit.Tests.dll" adapterTypeName="executor://xunit/VsTestRunner2/netcoreapp" className="Sample.CalculatorTests" name="Skipped" />
</UnitTest>
<UnitTest name="Sample.CalculatorTests.Passes" storage="C:\fixtures\xunit\bin\debug\net9.0\openidea.xunit.tests.dll" id="f52bc9c9-8df9-6fd9-934e-9b7c2f64f597">
<Execution id="45bed8c3-6316-465f-9ebd-b1ce3e829452" />
<TestMethod codeBase="C:\fixtures\Xunit\bin\Debug\net9.0\OpenIdea.Xunit.Tests.dll" adapterTypeName="executor://xunit/VsTestRunner2/netcoreapp" className="Sample.CalculatorTests" name="Passes" />
</UnitTest>
<UnitTest name="Sample.CalculatorTests.Parameterized(value: 1)" storage="C:\fixtures\xunit\bin\debug\net9.0\openidea.xunit.tests.dll" id="0352e892-15b1-279b-751c-4ef8fa3b78a4">
<Execution id="cd875b78-eac0-4818-8568-9f94369a9f82" />
<TestMethod codeBase="C:\fixtures\Xunit\bin\Debug\net9.0\OpenIdea.Xunit.Tests.dll" adapterTypeName="executor://xunit/VsTestRunner2/netcoreapp" className="Sample.CalculatorTests" name="Parameterized" />
</UnitTest>
<UnitTest name="Sample.CalculatorTests.Fails" storage="C:\fixtures\xunit\bin\debug\net9.0\openidea.xunit.tests.dll" id="7c64262f-2dfc-ba5e-c769-0c95cf182a76">
<Execution id="b092dfdf-2c5c-48fd-b642-21df8c45636d" />
<TestMethod codeBase="C:\fixtures\Xunit\bin\Debug\net9.0\OpenIdea.Xunit.Tests.dll" adapterTypeName="executor://xunit/VsTestRunner2/netcoreapp" className="Sample.CalculatorTests" name="Fails" />
</UnitTest>
</TestDefinitions>
<TestEntries>
<TestEntry testId="f52bc9c9-8df9-6fd9-934e-9b7c2f64f597" executionId="45bed8c3-6316-465f-9ebd-b1ce3e829452" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="7c64262f-2dfc-ba5e-c769-0c95cf182a76" executionId="b092dfdf-2c5c-48fd-b642-21df8c45636d" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="0352e892-15b1-279b-751c-4ef8fa3b78a4" executionId="cd875b78-eac0-4818-8568-9f94369a9f82" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="dba96a25-d6a4-9ba0-5868-d87d247475d6" executionId="d881161e-8fea-4081-be74-367b5a2b1cdd" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestEntry testId="342fa793-ffa3-5734-772a-79a8f289629f" executionId="4f7a68de-fbed-4a0f-bb49-d33262b6b321" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
</TestEntries>
<TestLists>
<TestList name="Results Not in a List" id="8c84fa94-04c1-424b-9868-57a2d4851a1d" />
<TestList name="All Loaded Results" id="19431567-8539-422a-85d7-44ee4e166bda" />
</TestLists>
<ResultSummary outcome="Failed">
<Counters total="5" executed="4" passed="2" failed="2" error="0" timeout="0" aborted="0" inconclusive="0" passedButRunAborted="0" notRunnable="0" notExecuted="0" disconnected="0" warning="0" completed="0" inProgress="0" pending="0" />
<Output>
<StdOut>[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 9.0.17)&#xD;
[xUnit.net 00:00:00.05] Discovering: OpenIdea.Xunit.Tests&#xD;
[xUnit.net 00:00:00.08] Discovered: OpenIdea.Xunit.Tests&#xD;
[xUnit.net 00:00:00.08] Starting: OpenIdea.Xunit.Tests&#xD;
[xUnit.net 00:00:00.17] Assert.Equal() Failure: Values differ&#xD;
[xUnit.net 00:00:00.17] Expected: 1&#xD;
[xUnit.net 00:00:00.17] Actual: 2&#xD;
[xUnit.net 00:00:00.17] Stack Trace:&#xD;
[xUnit.net 00:00:00.17] C:\fixtures\Xunit\UnitTest1.cs(6,0): at Sample.CalculatorTests.Parameterized(Int32 value)&#xD;
[xUnit.net 00:00:00.17] at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)&#xD;
[xUnit.net 00:00:00.17] at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)&#xD;
[xUnit.net 00:00:00.17] Assert.Equal() Failure: Values differ&#xD;
[xUnit.net 00:00:00.17] Expected: 3&#xD;
[xUnit.net 00:00:00.17] Actual: 2&#xD;
[xUnit.net 00:00:00.17] Stack Trace:&#xD;
[xUnit.net 00:00:00.17] C:\fixtures\Xunit\UnitTest1.cs(4,0): at Sample.CalculatorTests.Fails()&#xD;
[xUnit.net 00:00:00.17] at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)&#xD;
[xUnit.net 00:00:00.17] at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)&#xD;
[xUnit.net 00:00:00.17] demonstration&#xD;
[xUnit.net 00:00:00.17] Finished: OpenIdea.Xunit.Tests&#xD;
Test 'Sample.CalculatorTests.Skipped' was skipped in the test run.&#xD;
</StdOut>
</Output>
<RunInfos>
<RunInfo computerName="host" outcome="Error" timestamp="2026-11-09T15:31:14.8441178+08:00">
<Text>[xUnit.net 00:00:00.17] Sample.CalculatorTests.Parameterized(value: 2) [FAIL]</Text>
</RunInfo>
<RunInfo computerName="host" outcome="Error" timestamp="2026-11-09T15:31:14.8482465+08:00">
<Text>[xUnit.net 00:00:00.17] Sample.CalculatorTests.Fails [FAIL]</Text>
</RunInfo>
<RunInfo computerName="host" outcome="Warning" timestamp="2026-11-09T15:31:14.8487414+08:00">
<Text>[xUnit.net 00:00:00.17] Sample.CalculatorTests.Skipped [SKIP]</Text>
</RunInfo>
</RunInfos>
</ResultSummary>
</TestRun>
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more