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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 68ab95a631 fix(debugger): report obsolete methods as a completed hot swap
Treat the obsolete-method response and event as a reload warning. Explain why active frames keep the old code and offer Reset Frame for supported, droppable paused frames while preserving real failures and cancelled-build restart requirements.
2026-11-09 18:06:42 +08:00
Budi Santosoтаboenkkk 8ddf979cfe feat(db): separate procedures and functions into their own schema folders (#2270)
The database tree lists routines in one `routines` folder. A Separate Procedures and Functions option in the Database tool window's menu (off by default, remembered across sessions) lists `procedures` and `functions` folders instead, each holding only routines of that kind, with the same overload-aware keys and object filter. Expanded folders carry over when the option is switched either way.

Co-authored-by: boenkkk <[email protected]>
2026-11-09 18:05:59 +08:00
Qing f3f9fdb1ad fix(run): drop the leftover vue kind from the category table (#2302)
The vue run-configuration kind never shipped upstream — detection is gone
and no type registers it. Its KIND_CATEGORIES row (and the test table row)
are dead data; the plugin-era dev-server story is covered by plain npm
configurations with stable ids.
2026-11-09 18:01:46 +08:00
arookieofc 687471c19e fix(database): table editor focus when the tab opens targets the editor host (#2307) (#2318)
The editor area focuses its own [data-editor-focus] host when a table tab
opens; dbTableEditorFocus only set when focus landed inside
[data-db-table-editor], so Go to Column / Submit / Revert stayed disabled
until a cell was clicked. Treat host focus that wraps a table editor as
table-editor focus too.
2026-11-09 17:58:29 +08:00
yoo hyeong chanтаarookieofc a46d873f6c feat(java): share JDT LS across builds in a project window (#2272)
* feat(java): share JDT LS across builds in a project window

* fix(java): wait for JDT restart before launch requests

* fix(host): give relay final replies ten seconds of EOF grace

relay::tests::final_responses_keep_flowing_after_input_eof flakes on
Windows CI: the target writes one byte per second for seven seconds
after input EOF, but the relay only waits five idle seconds, so a
slow first byte makes the relay return with nothing received.

Raise EOF_GRACE to ten seconds and update the companion test's
server wait and elapsed bound to match.

Refs #2272 (Windows CI failure)

---------

Co-authored-by: arookieofc <[email protected]>
2026-11-09 17:53:59 +08:00
Emanyzwwwтаemanyzwww 5d3432a000 fix(welcome): name the platform's file manager, not Finder (#2265)
On Windows and Linux several places still named macOS's Finder: the recent-project row menu (Show in Finder), Settings › Version Control › Confirmation › When patch is created, the question after a patch is saved, and the reveal error. The wording was an English literal at each call site, one place sniffed the user agent, and the catalogs only had Finder's text. Shared helpers in src/platform/fileManager.ts now name Finder / Explorer / Files from the platform info, and the project view's Reveal action, the editor tab menu, the project tree menu, the welcome page and the patch flow use them, with whole-sentence catalog entries so each locale can translate them.

Co-authored-by: emanyzwww <[email protected]>
2026-11-09 17:51:48 +08:00
ppxb 16ebb6fde8 feat(run): import JetBrains Go Application and Go Test configurations (#2309) 2026-11-09 17:49:59 +08:00
l0ng-ai 0e673c206a fix(editor): keep the saved layout when a session restore meets open tabs (#2325)
A session restore that lands after tabs were already opened (a file launched into LightEdit while the window was still restoring, or a file opened from the CLI into a project window during startup) appended every restored tab to the current pane: saved splits collapsed into one pane, restored pinned tabs landed after unpinned ones, a pane could hold several preview tabs, and the tab limit was skipped. The restore now starts from the saved state and reopens the live tabs into it through the normal tab rules (pin order, one preview per pane, tab limit without evicting the live tabs), keeping their slots and line/column targets; the launched tab ends up active and focused in the saved active pane. An empty window still takes the saved layout as is.

Refs #2229
2026-11-09 17:42:23 +08:00
arookieofc 2680ba8463 fix(agents): notify subscribers when a session report changes the cached provider config (#2308)
* fix(java): pass m2e an effective settings file carrying the configured local repository (#1739)

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.

* fix(agents): notify subscribers when a session report changes the cached provider config (#1490)

Session reports (session/new, session/load, turn updates) and CLI discovery
funnel through Shared::remember_inner, which cached new model lists but never
emitted AgentEvent::Providers. The composer therefore kept showing a stale
model list until the next task's busy-to-idle refresh. Emit Providers when the
cache actually changes; unchanged reports stay silent, and the cache lock is
released before invoking the sink. fetch_settings' unconditional emit is now
covered by remember_discovered and removed.
2026-11-09 17:39:15 +08:00
arookieofc 660587a6fe fix(java): list JDT .classpath libraries and the JDK for manifest-less projects (#2300) (#2304)
* fix(java): list JDT .classpath libraries and the JDK for manifest-less projects (#2300)

External Libraries was empty for a pure-Java project (only .classpath /
.idea/libraries, no pom.xml or build.gradle):

- jdk_groups returned early without a build manifest, so even a
  configured JDK never appeared. It now also treats .classpath, .project,
  .idea, a configured JDK and declared source roots as Java markers.
- The JDT model was never a source of libraries. classpath_groups parses
  each module's .classpath kind="lib" entries (sourcepath preferred when
  it exists) into a per-module group, discovered through the same module
  scan the other ecosystems use.

Adds quick-xml to ide-sdk (already used by ide-run / ide-host) and the
.classpath file to the External Libraries refresh triggers.

* chore: regenerate bindings for classpath library kind
2026-11-09 17:32:07 +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
105 змінених файлів з 5808 додано та 271 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -4746,6 +4746,7 @@ dependencies = [
"ide-run",
"ide-vfs",
"ignore",
"quick-xml 0.42.0",
"serde",
"serde_json",
"specta",
+10 -1
Переглянути файл
@@ -169,8 +169,10 @@ impl Shared {
let commands = config::commands_of(&json!({ "availableCommands": commands }), &spec.id);
let options = config::options_of(&json!({ "configOptions": options }));
let _ = tokio::task::spawn_blocking(move || {
// Notifies subscribers itself when the discovery
// changed the cached config; unchanged results
// stay silent.
shared.remember_discovered(&spec.id, &options, &commands);
shared.emit(AgentEvent::Providers);
})
.await;
}
@@ -253,6 +255,13 @@ impl Shared {
{
tracing::warn!("saving agent settings: {e}");
}
// The cached provider config actually changed (a session report, discovery,
// or a turn update): tell subscribers to re-list, so a changed model list
// reaches the composer without waiting for the next task (#1490). Unchanged
// reports stay silent, so routine session traffic emits nothing. The cache
// lock is released first; the sink never runs under it.
drop(cache);
self.emit(AgentEvent::Providers);
}
}
+43
Переглянути файл
@@ -2146,6 +2146,49 @@ async fn reload_providers_updates_registry_install_clears_stale_probes_and_notif
assert!(probe.error.is_none());
}
/// A session report that changes the cached provider config notifies subscribers,
/// so the composer re-lists models without waiting for the next task (#1490).
/// Reports that change nothing stay silent.
#[tokio::test(flavor = "multi_thread")]
async fn remembered_config_changes_notify_subscribers_once() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
events.lock().clear();
let reported = config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
"options": [{ "value": "default" }, { "value": "custom-opus" }] },
] }));
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
assert!(
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
"a first report changing the cache notifies subscribers"
);
events.lock().clear();
// The same report again: the cache is unchanged, so subscribers hear nothing.
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
assert!(events.lock().is_empty(), "an unchanged report must stay silent");
// A changed model list notifies again, and providers() serves the new list.
let updated = config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
"options": [{ "value": "default" }, { "value": "custom-opus" }, { "value": "custom-sonnet" }] },
] }));
mgr.shared.remember("claude", Some(&updated), None, Some("default"));
assert!(
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
"a changed model list notifies subscribers"
);
let claude = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
let model = claude.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap();
let values: Vec<_> = model.values.iter().map(|v| v.value.as_str()).collect();
assert_eq!(values, ["default", "custom-opus", "custom-sonnet"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
let new = || NewAgentTask {
+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);
+22
Переглянути файл
@@ -896,6 +896,8 @@ pub struct JavaSettings {
/// Extra JVM options for the Java language server (jdtls), space-separated
/// (VS Code's `java.jdt.ls.vmargs`).
pub jdtls_vm_args: String,
/// Share one JDT LS across builds in an ordinary project window; other windows remain separate.
pub jdtls_shared: bool,
/// Build Tools › Maven.
pub maven: MavenSettings,
/// Build Tools › Gradle.
@@ -1477,6 +1479,26 @@ mod maven_linkage_tests {
}
}
#[cfg(test)]
mod java_settings_tests {
use super::*;
#[test]
fn shared_jdtls_defaults_off_and_round_trips() {
for old in [r#"{}"#, r#"{"jdk":"/jdk"}"#] {
let java: JavaSettings = serde_json::from_str(old).unwrap();
assert!(!java.jdtls_shared);
}
for shared in [false, true] {
let java = JavaSettings { jdtls_shared: shared, ..JavaSettings::default() };
let json = serde_json::to_value(&java).unwrap();
assert_eq!(json["jdtlsShared"], serde_json::json!(shared));
assert_eq!(serde_json::from_value::<JavaSettings>(json).unwrap(), java);
}
assert!(serde_json::from_str::<JavaSettings>(r#"{"jdtlsShared":"true"}"#).is_err());
}
}
#[cfg(test)]
mod gradle_settings_tests {
use super::*;
+1 -1
Переглянути файл
@@ -92,7 +92,7 @@ pub struct SequenceInfo {
pub data_type: String,
}
/// A schema's routines and sequences (the tree's `routines` / `sequences` folders).
/// A schema's routines (procedures and functions) and sequences.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbSchemaObjects")]
+11 -1
Переглянути файл
@@ -83,7 +83,7 @@ impl Host {
let opening = self.opening(window);
let _opening = opening.lock();
// Reject a damaged manifest before replacing the currently open project.
ide_workspace::workspace::Workspace::load(&root)?;
let is_workspace = ide_workspace::workspace::Workspace::load(&root)?.is_some();
// The window reloaded (or asked again) for the project it already has: keep
// it, with its warm index, language servers and unsaved documents.
if let Ok(current) = self.project(window)
@@ -137,6 +137,16 @@ impl Host {
lsp.set_execution_allowed(trusted.load(Ordering::Acquire));
lsp.set_content_roots(extra_roots.clone());
let settings = Arc::new(settings);
{
let settings = settings.clone();
// Workspace members have independent settings; target servers have their own path mappings.
lsp.set_jdtls_shared_hook(Box::new(move || {
let effective = settings.effective();
!is_workspace
&& effective.languages.java.jdtls_shared
&& effective.language_server_targets.get("java").is_none_or(|target| target.target.is_empty())
}));
}
{
let settings = settings.clone();
let root = root.clone();
+4 -4
Переглянути файл
@@ -9,7 +9,7 @@ use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const EOF_GRACE: Duration = Duration::from_secs(5);
const EOF_GRACE: Duration = Duration::from_secs(10);
/// `<host> <port>` from the arguments after `--connect`.
pub fn parse_args(args: &[String]) -> Result<(String, u16), String> {
@@ -25,7 +25,7 @@ pub fn parse_args(args: &[String]) -> Result<(String, u16), String> {
/// Connects to `host:port`, copies `input` to it and its replies to `output`, and returns when
/// the target is done (the copy of `input` may still be blocked: the caller exits). Fails only
/// when the connection can't be opened. An input EOF allows five idle seconds for a final reply.
/// when the connection can't be opened. An input EOF allows ten idle seconds for a final reply.
pub fn relay(host: &str, port: u16, mut input: impl Read + Send + 'static, mut output: impl Write) -> io::Result<()> {
let mut from_target = connect(host, port)?;
from_target.set_read_timeout(Some(Duration::from_millis(100)))?;
@@ -140,11 +140,11 @@ mod tests {
let mut request = Vec::new();
socket.read_to_end(&mut request).unwrap();
// Remain open after seeing EOF, like an idle keep-alive server.
wait.recv_timeout(Duration::from_secs(10)).unwrap();
wait.recv_timeout(Duration::from_secs(15)).unwrap();
});
let start = Instant::now();
relay("127.0.0.1", port, io::empty(), io::sink()).unwrap();
assert!(start.elapsed() < Duration::from_secs(8));
assert!(start.elapsed() < Duration::from_secs(13));
done.send(()).unwrap();
server.join().unwrap();
}
+48 -20
Переглянути файл
@@ -627,7 +627,11 @@ impl LspManager {
.docs
.lock()
.values()
.filter(|d| d.language.as_str() == "java" && d.path.starts_with(&server.root))
.filter(|d| {
d.language.as_str() == "java"
&& d.path.is_absolute()
&& d.servers.iter().any(|a| a.server.id == server.id)
})
.map(|d| crate::uri::path_to_uri_string(&d.path))
.collect();
if uris.is_empty() {
@@ -652,26 +656,50 @@ impl LspManager {
/// started if needed and waited for.
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
let java = LanguageId::new("java");
let server = self
.servers_for(&java, path)
.into_iter()
.find(|s| s.name == SERVER)
.ok_or_else(|| IdeError::unavailable("no Java language server (jdtls) is configured"))?;
self.ensure_started(&server);
match cancellable_wait(cancel, server.wait_ready(READY_TIMEOUT)).await? {
Some(run) => Ok((server, run)),
None => {
let status = server.status();
Err(IdeError::unavailable(match status {
ide_core::event::ServerStatus::Missing => {
"jdtls is not installed (Settings › Languages & Frameworks › Language Servers)".to_owned()
}
ide_core::event::ServerStatus::Misconfigured | ide_core::event::ServerStatus::Crashed => {
server.status_message().unwrap_or_else(|| "jdtls cannot start".to_owned())
}
_ => format!("jdtls is not ready ({status:?})"),
}))
let deadline = tokio::time::Instant::now() + READY_TIMEOUT;
loop {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let server = self
.servers_for(&java, path)
.into_iter()
.find(|s| s.name == SERVER)
.ok_or_else(|| IdeError::unavailable("no Java language server (jdtls) is configured"))?;
self.ensure_started(&server);
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if let Some(run) = cancellable_wait(cancel, server.wait_ready(remaining)).await? {
return Ok((server, run));
}
let status = server.status();
if !matches!(
status,
ide_core::event::ServerStatus::Missing
| ide_core::event::ServerStatus::Misconfigured
| ide_core::event::ServerStatus::Crashed
) && tokio::time::Instant::now() < deadline
&& let Ok(_restart) =
cancellable_wait(cancel, tokio::time::timeout_at(deadline, self.reconfigure_lock.lock())).await?
{
// A restart publishes Down while reaping its old JVM. Its successor may
// also have a new identity after changing the shared workspace.
if let Some(current) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER)
&& current.root.is_dir()
&& (current.id != server.id || current.is_starting() || current.running().is_some())
{
continue;
}
}
let status = server.status();
return Err(IdeError::unavailable(match status {
ide_core::event::ServerStatus::Missing => {
"jdtls is not installed (Settings › Languages & Frameworks › Language Servers)".to_owned()
}
ide_core::event::ServerStatus::Misconfigured | ide_core::event::ServerStatus::Crashed => {
server.status_message().unwrap_or_else(|| "jdtls cannot start".to_owned())
}
_ => format!("jdtls is not ready ({status:?})"),
}));
}
}
+233 -45
Переглянути файл
@@ -175,6 +175,20 @@ impl DocSnap {
/// Receives the folders outside the project that servers want watched.
pub type WatchRootsFn = dyn Fn(Vec<PathBuf>) + Send + Sync;
pub type JdtlsSharedFn = dyn Fn() -> bool + Send + Sync;
#[derive(Default)]
struct JdtlsWorkspace {
initialized: bool,
shared: bool,
roots: Vec<PathBuf>,
transitioning: bool,
}
fn is_local_jdtls(config: &LanguageServerConfig) -> bool {
config.name == "jdtls" && config.target_key.is_none() && config.target.is_none()
}
pub struct LspManager {
me: Weak<LspManager>,
project_root: PathBuf,
@@ -195,6 +209,9 @@ pub struct LspManager {
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
excludes_hook: RwLock<Option<Arc<external_project::ExcludesFn>>>,
watch_roots_hook: RwLock<Option<Arc<WatchRootsFn>>>,
jdtls_shared_hook: RwLock<Option<Arc<JdtlsSharedFn>>>,
jdtls_workspace: Mutex<JdtlsWorkspace>,
reconfigure_lock: tokio::sync::Mutex<()>,
shutting_down: AtomicBool,
execution_allowed: AtomicBool,
java_usages_warned: AtomicBool,
@@ -402,6 +419,9 @@ impl LspManager {
candidates_hook: RwLock::new(None),
excludes_hook: RwLock::new(None),
watch_roots_hook: RwLock::new(None),
jdtls_shared_hook: RwLock::new(None),
jdtls_workspace: Mutex::new(Default::default()),
reconfigure_lock: tokio::sync::Mutex::new(()),
shutting_down: AtomicBool::new(false),
execution_allowed: AtomicBool::new(true),
java_usages_warned: AtomicBool::new(false),
@@ -416,7 +436,56 @@ impl LspManager {
// ---- server lookup & lifecycle ----
pub fn set_content_roots(&self, roots: Vec<PathBuf>) {
*self.content_roots.write() = roots;
let changed = {
let mut current = self.content_roots.write();
let changed = *current != roots;
*current = roots;
changed
};
if changed
&& self.desired_jdtls_workspace().0
&& let Some(me) = self.me.upgrade()
{
me.reconfigure_soon();
}
}
/// Shares JDT LS within this manager; callers reconfigure after the hook's value changes.
pub fn set_jdtls_shared_hook(&self, hook: Box<JdtlsSharedFn>) {
*self.jdtls_shared_hook.write() = Some(Arc::from(hook));
}
fn desired_jdtls_workspace(&self) -> (bool, Vec<PathBuf>) {
let shared = self.jdtls_shared_hook.read().as_ref().is_some_and(|hook| hook());
let mut roots = Vec::new();
if shared {
roots.push(self.project_root.clone());
for root in self.content_roots.read().iter() {
if root.is_absolute() && root.is_dir() && !roots.contains(root) {
roots.push(root.clone());
}
}
}
(shared, roots)
}
fn jdtls_workspace_state(&self) -> parking_lot::MutexGuard<'_, JdtlsWorkspace> {
let mut state = self.jdtls_workspace.lock();
if !state.initialized {
(state.shared, state.roots) = self.desired_jdtls_workspace();
state.initialized = true;
}
state
}
fn server_workspace_roots(&self, server: &Server) -> Vec<PathBuf> {
if is_local_jdtls(&server.config) {
let state = self.jdtls_workspace_state();
if state.shared {
return state.roots.clone();
}
}
vec![server.root.clone()]
}
fn project_root_for(&self, path: &Path) -> PathBuf {
@@ -431,16 +500,21 @@ impl LspManager {
}
fn server_for(&self, cfg: &LanguageServerConfig, language: &LanguageId, path: &Path) -> Arc<Server> {
let shared = is_local_jdtls(cfg).then(|| self.jdtls_workspace_state());
let mut servers = self.servers.lock();
let root = launch::find_root(&self.project_root_for(path), path, &cfg.root_markers).unwrap_or_else(|| {
// Outside the project (library sources, …): reuse a running instance.
servers
.iter()
.filter(|s| s.name == cfg.name && s.config.target_key == cfg.target_key)
.min_by_key(|s| s.root != self.project_root)
.map(|s| s.root.clone())
.unwrap_or_else(|| self.project_root.clone())
});
let root = if shared.as_ref().is_some_and(|state| state.shared) {
self.project_root.clone()
} else {
launch::find_root(&self.project_root_for(path), path, &cfg.root_markers).unwrap_or_else(|| {
// Outside the project (library sources, …): reuse a running instance.
servers
.iter()
.filter(|s| s.name == cfg.name && s.config.target_key == cfg.target_key)
.min_by_key(|s| s.root != self.project_root)
.map(|s| s.root.clone())
.unwrap_or_else(|| self.project_root.clone())
})
};
if let Some(s) =
servers.iter().find(|s| s.name == cfg.name && s.root == root && s.config.target_key == cfg.target_key)
{
@@ -490,6 +564,7 @@ impl LspManager {
/// to the open documents (and start them). Also attaches servers newly
/// enabled in settings.
fn attach_fallbacks(&self) {
let _gate = self.injections.gate.lock();
let open: Vec<(DocId, LanguageId, PathBuf)> = self
.docs
.lock()
@@ -538,6 +613,27 @@ impl LspManager {
if self.shutting_down.load(Ordering::Acquire) || !self.execution_allowed.load(Ordering::Acquire) {
return;
}
let workspace = is_local_jdtls(&server.config).then(|| self.jdtls_workspace_state());
if let Some(state) = &workspace {
if state.transitioning || !self.servers.lock().iter().any(|s| s.id == server.id) {
return;
}
let (shared, roots) = self.desired_jdtls_workspace();
if state.shared != shared || (shared && state.roots != roots) {
if let Some(me) = self.me.upgrade() {
me.reconfigure_soon();
}
return;
}
}
let startup = if is_local_jdtls(&server.config) {
match server.startup_lock.clone().try_lock_owned() {
Ok(guard) => Some(guard),
Err(_) => return,
}
} else {
None
};
// `begin_start` only claims Idle servers, so a claimed server is never a
// live one. Its root is the process's working directory: starting with
// one deleted from disk fails (`os error 267` on Windows). Such a
@@ -553,7 +649,10 @@ impl LspManager {
return;
}
let server = server.clone();
self.runtime.spawn(async move { me.run_instance(server, generation).await });
self.runtime.spawn(async move {
let _startup = startup;
me.run_instance(server, generation).await;
});
}
async fn run_instance(self: Arc<Self>, server: Arc<Server>, generation: u64) {
@@ -561,6 +660,7 @@ impl LspManager {
let handler = Arc::new(handler::ClientHandler::new(self.me.clone(), server.clone(), generation));
let me = self.clone();
let tail = server.clone();
let launch_cancel = cancel.clone();
// The settings hook may touch the filesystem (e.g. scanning for JDKs); TCP
// servers may take a while to start listening.
let launched = tokio::task::spawn_blocking(move || {
@@ -568,17 +668,17 @@ impl LspManager {
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
}
let mut cfg = me.configured(&tail);
if !me.execution_allowed.load(Ordering::Acquire) || cancel.is_cancelled() {
if !me.execution_allowed.load(Ordering::Acquire) || launch_cancel.is_cancelled() {
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
}
tail.set_effective_config(generation, cfg.clone());
let prepare = me.prepare_hook.read().clone();
if cfg.target.is_none()
&& !cancel.is_cancelled()
&& !launch_cancel.is_cancelled()
&& me.launcher.available(&cfg, &tail.root)
&& let Some(prepare) = prepare
{
prepare(&cfg, &tail.root, &cancel);
prepare(&cfg, &tail.root, &launch_cancel);
cfg = me.configured(&tail);
}
tail.set_effective_config(generation, cfg.clone());
@@ -588,7 +688,7 @@ impl LspManager {
let missing = cfg.target.is_none() && !me.launcher.available(&cfg, &root);
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
}
if !me.execution_allowed.load(Ordering::Acquire) || cancel.is_cancelled() {
if !me.execution_allowed.load(Ordering::Acquire) || launch_cancel.is_cancelled() {
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
}
me.launcher.launch_resolved(
@@ -596,7 +696,7 @@ impl LspManager {
&root,
handler,
Box::new(move |line| tail.push_stderr(generation, line)),
&cancel,
&launch_cancel,
)
})
.await
@@ -605,7 +705,7 @@ impl LspManager {
let peer = match launched {
Ok((peer, binary)) => {
if !server.set_resolved_binary(generation, binary) {
peer.kill();
Self::kill_peer(&server, &peer).await;
return;
}
peer
@@ -662,9 +762,14 @@ impl LspManager {
init["initializationOptions"]["triggerFiles"] = json!([uri::path_to_uri_string(&path)]);
}
}
let result = tokio::time::timeout(INITIALIZE_TIMEOUT, peer.request::<_, Value>("initialize", init, None))
.await
.unwrap_or(Err(RpcError::Timeout));
let result = tokio::select! {
biased;
() = cancel.cancelled() => {
Self::kill_peer(&server, &peer).await;
return;
}
result = tokio::time::timeout(INITIALIZE_TIMEOUT, peer.request::<_, Value>("initialize", init, Some(cancel.clone()))) => result.unwrap_or(Err(RpcError::Timeout)),
};
let caps = match result {
Ok(result) => {
if let Some(info) = result.get("serverInfo") {
@@ -681,7 +786,7 @@ impl LspManager {
// The server is exiting: let it, so the crash report has its exit code and last output.
let _ = tokio::time::timeout(Duration::from_secs(3), peer.closed()).await;
}
peer.kill();
Self::kill_peer(&server, &peer).await;
// Treated like a crash so transient failures retry with backoff.
self.spawn_supervisor(server, generation, peer);
return;
@@ -690,7 +795,7 @@ impl LspManager {
let run =
Running { generation, peer: peer.clone(), caps: Arc::new(RwLock::new(caps)), watchers: Default::default() };
if !server.set_initializing(run.clone()) {
peer.kill();
Self::kill_peer(&server, &peer).await;
return;
}
if let Err(e) = peer.notify("initialized", json!({})) {
@@ -709,24 +814,30 @@ impl LspManager {
// Publish readiness and (re)open attached documents atomically w.r.t. did_change.
let mut reopened = Vec::new();
{
let ready = {
let mut docs = self.docs.lock();
if !server.mark_ready(generation, run.clone()) {
drop(docs);
peer.kill();
return;
}
let open_close = run.caps.read().open_close;
for (id, d) in docs.iter_mut() {
let params = d.did_open_params();
for a in d.servers.iter_mut().filter(|a| a.server.id == server.id && a.opened_gen != Some(generation)) {
if open_close && let Err(e) = peer.notify("textDocument/didOpen", params.clone()) {
tracing::debug!("{}: didOpen: {e}", server.name);
false
} else {
let open_close = run.caps.read().open_close;
for (id, d) in docs.iter_mut() {
let params = d.did_open_params();
for a in
d.servers.iter_mut().filter(|a| a.server.id == server.id && a.opened_gen != Some(generation))
{
if open_close && let Err(e) = peer.notify("textDocument/didOpen", params.clone()) {
tracing::debug!("{}: didOpen: {e}", server.name);
}
a.opened_gen = Some(generation);
reopened.push(*id);
}
a.opened_gen = Some(generation);
reopened.push(*id);
}
true
}
};
if !ready {
Self::kill_peer(&server, &peer).await;
return;
}
for doc in reopened {
self.schedule_pull(doc, Some(&server), Duration::ZERO);
@@ -767,7 +878,6 @@ impl LspManager {
fn initialize_params(&self, server: &Server) -> Value {
let root_uri = uri::path_to_uri(&server.root);
let name = server.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "root".into());
let cfg = server.effective_config();
let mut init_options =
cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).unwrap_or(Value::Null);
@@ -776,11 +886,24 @@ impl LspManager {
init_options = json!({});
}
init_options["settings"] = handler::all_settings(&cfg);
let shared = is_local_jdtls(&server.config) && self.jdtls_workspace_state().shared;
if shared {
init_options["workspaceFolders"] = json!(
self.server_workspace_roots(server)
.iter()
.map(|root| uri::path_to_uri_string(root))
.collect::<Vec<_>>()
);
}
let triggers: Vec<_> = self
.docs
.lock()
.values()
.filter(|d| d.language.as_str() == "java" && d.path.starts_with(&server.root))
.filter(|d| {
d.language.as_str() == "java"
&& d.path.is_absolute()
&& d.servers.iter().any(|a| a.server.id == server.id)
})
.map(|d| uri::path_to_uri_string(&d.path))
.collect();
if !triggers.is_empty() && init_options.get("triggerFiles").is_none() {
@@ -794,7 +917,7 @@ impl LspManager {
"locale": "en",
"rootPath": server.root.to_string_lossy(),
"rootUri": root_uri,
"workspaceFolders": [{ "uri": root_uri, "name": name }],
"workspaceFolders": self.workspace_folders(server),
"capabilities": caps::client_capabilities(),
"trace": "off",
});
@@ -811,8 +934,16 @@ impl LspManager {
}
pub(crate) fn workspace_folders(&self, server: &Server) -> Value {
let name = server.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "root".into());
json!([{ "uri": uri::path_to_uri(&server.root), "name": name }])
json!(
self.server_workspace_roots(server)
.iter()
.map(|root| {
let name =
root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "root".into());
json!({"uri": uri::path_to_uri(root), "name": name})
})
.collect::<Vec<_>>()
)
}
pub(crate) fn sink(&self) -> &SharedSink {
@@ -862,6 +993,7 @@ impl LspManager {
/// Opens a read-only virtual document (`jdt://…`) on the server that
/// returned its URI (`didOpen` only: it is never changed or saved).
pub fn did_open_virtual(&self, doc: DocId, uri: &str, language: &LanguageId, version: u32, text: &str) {
let _gate = self.injections.gate.lock();
if self.docs.lock().contains_key(&doc) {
self.close_injections(doc);
self.close_document(doc);
@@ -2450,15 +2582,18 @@ impl LspManager {
.into_iter()
.flat_map(|(paths, change)| paths.iter().map(move |p| (p, change)));
let watchers = run.watchers.read();
let roots = self.server_workspace_roots(&s);
let changes: Vec<(&PathBuf, Change)> = if watchers.is_empty() {
let languages = s.languages();
all.filter(|(p, change)| {
p.starts_with(&s.root) && languages.contains(&self.languages.detect(p, None)) && send(p, *change)
roots.iter().any(|root| p.starts_with(root))
&& languages.contains(&self.languages.detect(p, None))
&& send(p, *change)
})
.collect()
} else {
all.chain(excluded_dirs.iter().map(|p| (p, Change::Created)))
.filter(|(p, change)| watchers.wants(&s.root, p, *change) && send(p, *change))
.filter(|(p, change)| roots.iter().any(|root| watchers.wants(root, p, *change)) && send(p, *change))
.collect()
};
drop(watchers);
@@ -3036,7 +3171,8 @@ impl LspManager {
}
}
if allowed && !previous {
for server in self.servers.lock().iter() {
let servers = self.servers.lock().clone();
for server in &servers {
server.reset_for_restart();
self.ensure_started(server);
}
@@ -3053,11 +3189,13 @@ impl LspManager {
}
pub async fn reconfigure(&self) {
let _reconfigure = self.reconfigure_lock.lock().await;
if !self.execution_allowed.load(Ordering::Acquire) {
let servers = self.servers.lock().clone();
join_all(servers.iter().map(|s| self.stop_instance(s, true))).await;
return;
}
self.reconfigure_jdtls_workspace().await;
self.stop_unlisted().await;
let Some(me) = self.me.upgrade() else { return };
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
@@ -3120,6 +3258,39 @@ impl LspManager {
self.injection_providers_changed();
}
async fn reconfigure_jdtls_workspace(&self) {
let (shared, roots) = self.desired_jdtls_workspace();
let retired = {
// Opens attach atomically with root selection; no document can acquire an old
// instance between removing the registry entries and detaching its documents.
let _gate = self.injections.gate.lock();
let mut state = self.jdtls_workspace_state();
if state.shared == shared && (!shared || state.roots == roots) {
return;
}
state.transitioning = true;
state.shared = shared;
state.roots = roots;
let mut servers = self.servers.lock();
let retired: Vec<_> = servers.iter().filter(|s| is_local_jdtls(&s.config)).cloned().collect();
servers.retain(|s| !is_local_jdtls(&s.config));
for doc in self.docs.lock().values_mut() {
doc.servers.retain(|a| !is_local_jdtls(&a.server.config));
}
retired
};
for server in &retired {
self.stop_instance(server, true).await;
}
self.forget(&retired);
self.jdtls_workspace.lock().transitioning = false;
self.attach_fallbacks();
let pending: Vec<_> = self.servers.lock().iter().filter(|s| is_local_jdtls(&s.config)).cloned().collect();
for server in pending {
self.ensure_started(&server);
}
}
/// Detaches fallbacks shadowed by enabled servers and instances whose target
/// no longer matches the document's language. Stop them once unused.
async fn detach_shadowed_servers(&self) {
@@ -3255,6 +3426,7 @@ impl LspManager {
}
pub async fn restart(&self, server: ide_core::ServerId) -> IdeResult<()> {
let _reconfigure = self.reconfigure_lock.lock().await;
let s = self
.servers
.lock()
@@ -3282,7 +3454,12 @@ impl LspManager {
/// Gracefully stops the current instance (`shutdown` + `exit`, then kill).
async fn stop_instance(&self, server: &Arc<Server>, final_stop: bool) {
let Some(run) = server.begin_stop(&self.sink, final_stop) else { return };
let Some(run) = server.begin_stop(&self.sink, final_stop) else {
if is_local_jdtls(&server.config) {
let _startup = server.startup_lock.lock().await;
}
return;
};
let peer = run.peer.clone();
// A server we connected to without starting it (an open Godot editor) is not
// ours to shut down: only the connection closes.
@@ -3302,13 +3479,24 @@ impl LspManager {
peer.kill();
let _ = tokio::time::timeout(Duration::from_secs(2), peer.closed()).await;
}
peer.kill();
Self::kill_peer(server, &peer).await;
if is_local_jdtls(&server.config) {
let _startup = server.startup_lock.lock().await;
}
server.end_stop(run.generation, &self.sink);
self.file_watch_roots_changed();
}
async fn kill_peer(server: &Server, peer: &ide_jsonrpc::Peer) {
peer.kill();
if is_local_jdtls(&server.config) && peer.pid().is_some() {
peer.exited().await;
}
}
pub async fn shutdown_all(&self) {
self.shutting_down.store(true, Ordering::Release);
let _reconfigure = self.reconfigure_lock.lock().await;
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
join_all(servers.iter().map(|s| self.stop_instance(s, true))).await;
}
+7
Переглянути файл
@@ -119,6 +119,8 @@ pub struct Server {
phase_notify: Notify,
transient: Mutex<HashMap<PathBuf, Transient>>,
pub java_build_lock: Arc<tokio::sync::Mutex<()>>,
/// JDT retirement waits for launch and initialization cleanup, even before `Ready`.
pub startup_lock: Arc<tokio::sync::Mutex<()>>,
pub java_autobuild_suspended: std::sync::atomic::AtomicBool,
pub external_project: tokio::sync::Mutex<crate::external_project::State>,
pub external_diagnostics: std::sync::atomic::AtomicBool,
@@ -158,6 +160,7 @@ impl Server {
phase_notify: Notify::new(),
transient: Mutex::new(HashMap::new()),
java_build_lock: Arc::new(tokio::sync::Mutex::new(())),
startup_lock: Arc::new(tokio::sync::Mutex::new(())),
java_autobuild_suspended: std::sync::atomic::AtomicBool::new(false),
external_project: tokio::sync::Mutex::new(Default::default()),
external_diagnostics: std::sync::atomic::AtomicBool::new(false),
@@ -269,6 +272,10 @@ impl Server {
}
}
pub fn is_starting(&self) -> bool {
matches!(self.state.lock().conn, Conn::Starting)
}
/// The instance told `initialized`, ready or not.
pub fn instance(&self) -> Option<Running> {
self.running().or_else(|| self.initializing.lock().clone())
+477 -7
Переглянути файл
@@ -35,6 +35,8 @@ struct MockState {
responder: Mutex<Option<Responder>>,
/// Holds the handling of notifications of this method until the gate opens.
held: Mutex<Option<(String, Arc<Gate>)>>,
initialize_gate: Mutex<Option<Arc<Gate>>>,
launch_gate: Mutex<Option<Arc<Gate>>>,
peer: Mutex<Option<Peer>>,
}
@@ -73,7 +75,9 @@ fn utf16_to_byte(text: &str, line: u64, col: u64) -> usize {
text.len()
}
struct MockHandler(Arc<MockState>);
type MockConnection = Mutex<Option<Peer>>;
struct MockHandler(Arc<MockState>, std::sync::Weak<MockConnection>);
impl Handler for MockHandler {
fn on_notification(&self, method: &str, params: Value) {
@@ -118,8 +122,14 @@ impl Handler for MockHandler {
s.docs.lock().remove(&uri);
}
"exit" => {
if let Some(p) = s.peer.lock().take() {
p.kill();
if let Some(connection) = self.1.upgrade()
&& let Some(peer) = connection.lock().take()
{
peer.kill();
}
let mut latest = s.peer.lock();
if latest.as_ref().is_some_and(Peer::is_closed) {
*latest = None;
}
}
_ => {}
@@ -131,7 +141,13 @@ impl Handler for MockHandler {
let s = &self.0;
s.requests.lock().push((method.to_owned(), params.clone()));
match method {
"initialize" => Ok(json!({ "capabilities": s.caps.lock().clone(), "serverInfo": { "name": "mock" } })),
"initialize" => {
let gate = s.initialize_gate.lock().take();
if let Some(gate) = gate {
gate.hold();
}
Ok(json!({ "capabilities": s.caps.lock().clone(), "serverInfo": { "name": "mock" } }))
}
"shutdown" => Ok(Value::Null),
_ => {
if let Some(error) = s.errors.lock().get(method).cloned() {
@@ -150,6 +166,7 @@ impl Handler for MockHandler {
#[derive(Default)]
struct MockLauncher {
servers: Mutex<HashMap<String, Arc<MockState>>>,
connections: Mutex<Vec<Arc<MockConnection>>>,
}
impl MockLauncher {
@@ -186,10 +203,18 @@ impl Launcher for MockLauncher {
state.docs.lock().clear();
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
let server = Peer::connect(sr, sw, Arc::new(MockHandler(state.clone())));
let connection = Arc::new(Mutex::new(None));
let server = Peer::connect(sr, sw, Arc::new(MockHandler(state.clone(), Arc::downgrade(&connection))));
*connection.lock() = Some(server.clone());
self.connections.lock().push(connection);
*state.peer.lock() = Some(server);
let (cr, cw) = tokio::io::split(client_io);
Ok(Peer::connect(cr, cw, handler))
let client = Peer::connect(cr, cw, handler);
let gate = state.launch_gate.lock().take();
if let Some(gate) = gate {
gate.hold();
}
Ok(client)
}
}
@@ -420,6 +445,451 @@ async fn linked_projects_initialize_separate_language_server_roots() {
h.mgr.shutdown_all().await;
}
fn java_siblings(h: &Harness) -> Vec<PathBuf> {
["first", "second"]
.into_iter()
.map(|name| {
let root = h.root.join(name);
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("mock.toml"), "").unwrap();
let path = root.join("Main.java");
std::fs::write(&path, "class Main {}").unwrap();
path
})
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_is_opt_in_and_keeps_module_requests_on_one_instance() {
for shared in [false, true] {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.mgr.set_jdtls_shared_hook(Box::new(move || shared));
let paths = java_siblings(&h);
std::thread::scope(|scope| {
for path in &paths {
scope.spawn(|| h.mgr.did_open(DocId::next(), path, &h.lang, 1, "class Main {}"));
}
});
let state = h.launcher.state("jdtls");
let count = if shared { 1 } else { 2 };
eventually(|| state.requested("initialize").len() == count).await;
assert_eq!(state.launches.load(Ordering::SeqCst), count);
assert_eq!(h.mgr.servers().len(), count);
for path in &paths {
h.mgr.java_classpath(path.parent().unwrap(), false, &Default::default()).await.unwrap();
}
let requests = state.requested("workspace/executeCommand");
let classpaths: Vec<_> = requests.iter().filter(|r| r["command"] == "java.project.getClasspaths").collect();
assert_eq!(classpaths.len(), 2);
for path in &paths {
assert!(classpaths.iter().any(|r| r["arguments"][0] == uri_of(path.parent().unwrap())));
}
if shared {
let init = &state.requested("initialize")[0];
assert_eq!(init["rootUri"], uri_of(&h.root));
assert_eq!(init["initializationOptions"]["workspaceFolders"], json!([uri_of(&h.root)]));
}
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_toggle_retires_old_instances_and_reopens_every_document() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let shared = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_jdtls_shared_hook(Box::new({
let shared = shared.clone();
move || shared.load(Ordering::SeqCst)
}));
let paths = java_siblings(&h);
for path in &paths {
h.mgr.did_open(DocId::next(), path, &h.lang, 1, "class Main {}");
}
let state = h.launcher.state("jdtls");
eventually(|| state.requested("initialize").len() == 2).await;
eventually(|| {
paths
.iter()
.all(|path| state.notified("textDocument/didOpen").iter().any(|v| v["textDocument"]["uri"] == uri_of(path)))
})
.await;
let old: Vec<_> = h.mgr.servers().into_iter().map(|s| s.id).collect();
shared.store(true, Ordering::SeqCst);
h.mgr.reconfigure().await;
eventually(|| state.launches.load(Ordering::SeqCst) == 3 && state.docs.lock().len() == 2).await;
assert_eq!(h.mgr.servers().len(), 1);
for id in old {
assert!(
h.events
.lock()
.iter()
.any(|event| matches!(event, IdeEvent::LanguageServerRemoved {server} if *server == id))
);
}
shared.store(false, Ordering::SeqCst);
h.mgr.reconfigure().await;
eventually(|| state.launches.load(Ordering::SeqCst) == 5).await;
assert_eq!(h.mgr.servers().len(), 2);
eventually(|| {
paths.iter().all(|path| {
state.notified("textDocument/didOpen").iter().filter(|v| v["textDocument"]["uri"] == uri_of(path)).count()
== 3
})
})
.await;
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_cancels_a_retiring_initialize_before_starting_its_replacement() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let shared = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_jdtls_shared_hook(Box::new({
let shared = shared.clone();
move || shared.load(Ordering::SeqCst)
}));
let state = h.launcher.state("jdtls");
let gate = Arc::new(Gate::default());
*state.initialize_gate.lock() = Some(gate.clone());
let path = java_siblings(&h).remove(0);
h.mgr.did_open(DocId::next(), &path, &h.lang, 1, "class Main {}");
eventually(|| gate.entered()).await;
let old = state.peer();
shared.store(true, Ordering::SeqCst);
let switched = tokio::time::timeout(Duration::from_secs(2), h.mgr.reconfigure()).await;
let closed_before_response = old.is_closed();
gate.open();
switched.expect("initialize cancellation must not wait for its response");
eventually(|| state.requested("initialize").len() == 2).await;
assert!(closed_before_response, "the old transport must close before its initialize response is released");
assert_eq!(h.mgr.servers().len(), 1);
assert_eq!(h.mgr.servers()[0].root.as_ref(), h.root.as_path());
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn shared_java_waits_for_an_abandoned_launcher_before_replacing_the_workspace() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.mgr.set_jdtls_shared_hook(Box::new(|| true));
let state = h.launcher.state("jdtls");
let gate = Arc::new(Gate::default());
*state.launch_gate.lock() = Some(gate.clone());
h.open("Main.java", "class Main {}");
eventually(|| gate.entered()).await;
let old = state.peer();
let id = h.mgr.servers()[0].id;
let external = tempfile::tempdir().unwrap();
h.mgr.set_content_roots(vec![dunce::canonicalize(external.path()).unwrap()]);
eventually(|| h.mgr.servers().iter().all(|s| s.id != id)).await;
h.open("Another.java", "class Another {}");
let mut transition = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.reconfigure().await }
});
let pending = tokio::time::timeout(Duration::from_millis(100), &mut transition).await.is_err();
let launches = state.launches.load(Ordering::SeqCst);
let old_alive = !old.is_closed();
gate.open();
assert!(pending, "retirement must wait for the launcher to return");
assert_eq!(launches, 1, "the retiring launcher still owns its peer");
assert!(old_alive);
transition.await.unwrap();
h.mgr.reconfigure().await;
eventually(|| state.launches.load(Ordering::SeqCst) == 2 && state.docs.lock().len() == 2).await;
assert!(old.is_closed());
assert_eq!(h.mgr.servers().len(), 1);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_classpath_waits_for_a_config_restart_that_is_reaping_startup() {
for (shared, failed) in [(false, false), (true, false), (false, true)] {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let changed = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_jdtls_shared_hook(Box::new({
let changed = changed.clone();
move || shared && changed.load(Ordering::SeqCst)
}));
h.mgr.set_config_hook(Box::new({
let changed = changed.clone();
move |cfg, _| {
let changed = changed.load(Ordering::SeqCst);
cfg.env.insert("MOCK_CONFIG_REVISION".into(), changed.to_string());
if failed && changed {
cfg.launch_error = Some("restart configuration error".into());
}
}
}));
let state = h.launcher.state("jdtls");
let gate = Arc::new(Gate::default());
*state.launch_gate.lock() = Some(gate.clone());
let path = java_siblings(&h).remove(0);
h.mgr.did_open(DocId::next(), &path, &h.lang, 1, "class Main {}");
eventually(|| gate.entered()).await;
let old = h.mgr.servers()[0].id;
changed.store(true, Ordering::SeqCst);
let restarting = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.reconfigure().await }
});
h.wait_status("jdtls", ServerStatus::Stopped).await;
let mut query = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.java_classpath(path.parent().unwrap(), false, &Default::default()).await }
});
let early = tokio::time::timeout(Duration::from_millis(100), &mut query).await;
gate.open();
restarting.await.unwrap();
let result = match early {
Ok(result) => result.unwrap(),
Err(_) => query.await.unwrap(),
};
if failed {
assert!(result.unwrap_err().message.contains("restart configuration error"));
} else {
assert!(result.is_ok(), "a configuration restart is transient: {result:?}");
assert_eq!(state.launches.load(Ordering::SeqCst), 2);
assert_eq!(h.mgr.servers()[0].id != old, shared);
}
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn java_classpath_restart_barrier_wait_remains_cancellable() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let changed = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_config_hook(Box::new({
let changed = changed.clone();
move |cfg, _| {
cfg.env.insert("MOCK_CONFIG_REVISION".into(), changed.load(Ordering::SeqCst).to_string());
}
}));
let state = h.launcher.state("jdtls");
let gate = Arc::new(Gate::default());
*state.launch_gate.lock() = Some(gate.clone());
h.open("Main.java", "class Main {}");
eventually(|| gate.entered()).await;
changed.store(true, Ordering::SeqCst);
let restarting = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.reconfigure().await }
});
h.wait_status("jdtls", ServerStatus::Stopped).await;
let cancel = CancellationToken::new();
let mut query = tokio::spawn({
let manager = h.mgr.clone();
let root = h.root.clone();
let cancel = cancel.clone();
async move { manager.java_classpath(&root, false, &cancel).await }
});
let early = tokio::time::timeout(Duration::from_millis(100), &mut query).await;
let waiting = early.is_err();
cancel.cancel();
let result = match early {
Ok(result) => Ok(result),
Err(_) => tokio::time::timeout(Duration::from_secs(1), query).await,
};
gate.open();
restarting.await.unwrap();
assert!(waiting, "the query must wait behind the restart barrier");
assert_eq!(result.unwrap().unwrap().unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_classpath_does_not_retry_permanently_unavailable_servers() {
for missing in [false, true] {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
if missing {
h.launcher.state("jdtls").missing.store(true, Ordering::SeqCst);
} else {
h.mgr.set_config_hook(Box::new(|cfg, _| {
cfg.launch_error = Some("permanent mock configuration error".into())
}));
}
let result =
tokio::time::timeout(Duration::from_secs(1), h.mgr.java_classpath(&h.root, false, &Default::default()))
.await
.expect("permanent failures must not incur the Java readiness timeout");
let error = result.unwrap_err();
assert!(error.message.contains(if missing { "not installed" } else { "permanent mock configuration error" }));
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn shared_java_external_roots_reach_initialization_queries_and_watches() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.mgr.set_jdtls_shared_hook(Box::new(|| true));
let external = tempfile::tempdir().unwrap();
let external = dunce::canonicalize(external.path()).unwrap();
h.mgr.set_content_roots(vec![external.clone(), external.clone(), h.root.clone()]);
let file = external.join("External.java");
std::fs::write(&file, "class External {}").unwrap();
h.mgr.did_open(DocId::next(), &file, &h.lang, 1, "class External {}");
let state = h.launcher.state("jdtls");
h.wait_status("jdtls", ServerStatus::Ready).await;
let init = &state.requested("initialize")[0];
assert_eq!(init["initializationOptions"]["workspaceFolders"], json!([uri_of(&h.root), uri_of(&external)]));
assert_eq!(init["initializationOptions"]["triggerFiles"], json!([uri_of(&file)]));
let folders: Value = state.peer().request("workspace/workspaceFolders", Value::Null, None).await.unwrap();
assert_eq!(folders, init["workspaceFolders"]);
state.peer().request::<_, Value>("client/registerCapability", json!({"registrations":[{
"id":"external-java", "method":"workspace/didChangeWatchedFiles", "registerOptions":{"watchers":[{"globPattern":"**/*.java"}]}
}]}), None).await.unwrap();
let other = external.join("Other.java");
h.mgr.watched_files_changed(std::slice::from_ref(&other), &[], &[], &[]);
eventually(|| {
state.notified("workspace/didChangeWatchedFiles").iter().any(|v| v["changes"][0]["uri"] == uri_of(&other))
})
.await;
h.mgr.set_content_roots(vec![]);
h.mgr.reconfigure().await;
eventually(|| state.requested("initialize").len() == 2).await;
assert_eq!(state.requested("initialize")[1]["initializationOptions"]["workspaceFolders"], json!([uri_of(&h.root)]));
assert_eq!(h.mgr.servers().len(), 1);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn trusting_an_existing_java_instance_restarts_it_without_locking_the_registry() {
for shared in [false, true] {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
h.mgr.set_jdtls_shared_hook(Box::new(move || shared));
h.open("Main.java", "class Main {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
h.mgr.set_execution_allowed(false);
h.mgr.reconfigure().await;
h.mgr.set_execution_allowed(true);
eventually(|| state.launches.load(Ordering::SeqCst) == 2 && state.docs.lock().len() == 1).await;
assert_eq!(h.mgr.servers().len(), 1);
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_preserves_other_servers_and_marker_scoped_fallbacks() {
for fallback in [false, true] {
let h = harness_for(
"java",
"java",
&[("jdtls", incremental_caps()), ("other", incremental_caps())],
if fallback { &["other"] } else { &[] },
);
h.mgr.set_jdtls_shared_hook(Box::new(|| true));
h.launcher.state("jdtls").missing.store(fallback, Ordering::SeqCst);
for path in java_siblings(&h) {
h.mgr.did_open(DocId::next(), &path, &h.lang, 1, "class Main {}");
}
eventually(|| h.launcher.state("other").requested("initialize").len() == 2).await;
let servers = h.mgr.servers();
assert_eq!(servers.iter().filter(|s| s.name == "jdtls").count(), 1);
assert_eq!(servers.iter().filter(|s| s.name == "other").count(), 2);
assert_eq!(h.launcher.state("jdtls").launches.load(Ordering::SeqCst), usize::from(!fallback));
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sharing_keeps_target_instances_separate_and_preserves_them_on_toggle() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let shared = Arc::new(std::sync::atomic::AtomicBool::new(true));
h.mgr.set_jdtls_shared_hook(Box::new({
let shared = shared.clone();
move || shared.load(Ordering::SeqCst)
}));
h.mgr.set_servers_hook(Box::new(|_, configs| {
let mut target = configs[0].clone();
target.target_key = Some("container".into());
target
.initialization_options
.as_mut()
.unwrap()
.as_table_mut()
.unwrap()
.insert("selectedTarget".into(), toml::Value::Boolean(true));
vec![configs[0].clone(), target]
}));
h.open("Main.java", "class Main {}");
for path in java_siblings(&h) {
h.mgr.did_open(DocId::next(), &path, &h.lang, 1, "class Main {}");
}
let state = h.launcher.state("jdtls");
eventually(|| h.mgr.servers().iter().filter(|s| s.status == ServerStatus::Ready).count() == 4).await;
let initial = state.requested("initialize");
assert_eq!(initial.len(), 4);
let targets: Vec<_> = initial.iter().filter(|v| v["initializationOptions"]["selectedTarget"] == true).collect();
assert_eq!(targets.len(), 3, "target roots retain their marker-based identity");
assert!(targets.iter().all(|v| v["initializationOptions"].get("workspaceFolders").is_none()));
let local = initial.iter().find(|v| v["initializationOptions"]["selectedTarget"] != true).unwrap();
assert_eq!(local["rootUri"], uri_of(&h.root));
assert_eq!(local["initializationOptions"]["workspaceFolders"], json!([uri_of(&h.root)]));
let old: HashSet<_> = h.mgr.servers().into_iter().map(|s| s.id).collect();
shared.store(false, Ordering::SeqCst);
h.mgr.reconfigure().await;
eventually(|| h.mgr.servers().iter().filter(|s| s.status == ServerStatus::Ready).count() == 6).await;
assert_eq!(
h.mgr.servers().iter().filter(|s| old.contains(&s.id)).count(),
3,
"local sharing does not retire targets"
);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn virtual_java_documents_opened_during_a_toggle_attach_to_the_successor() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let shared = Arc::new(std::sync::atomic::AtomicBool::new(false));
h.mgr.set_jdtls_shared_hook(Box::new({
let shared = shared.clone();
move || shared.load(Ordering::SeqCst)
}));
let (doc, _) = h.open("Main.java", "class Main {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
let uris: Vec<_> = (0..16).map(|n| format!("jdt://contents/project/Virtual{n}.class")).collect();
state.respond(
"textDocument/definition",
json!(
uris.iter()
.map(|uri| json!({"uri":uri,"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}}}))
.collect::<Vec<_>>()
),
);
h.mgr.goto(doc, Pos::default(), GotoKind::Definition).await.unwrap();
shared.store(true, Ordering::SeqCst);
let toggle = tokio::spawn({
let manager = h.mgr.clone();
async move { manager.reconfigure().await }
});
let mut opened = Vec::new();
for uri in uris {
let manager = h.mgr.clone();
let language = h.lang.clone();
let doc = DocId::next();
opened.push((
doc,
std::thread::spawn(move || manager.did_open_virtual(doc, &uri, &language, 0, "class Virtual {}")),
));
}
let docs: Vec<_> = opened
.into_iter()
.map(|(doc, thread)| {
thread.join().unwrap();
doc
})
.collect();
toggle.await.unwrap();
eventually(|| state.docs.lock().len() == docs.len() + 1).await;
assert_eq!(h.mgr.servers().len(), 1);
for doc in docs {
h.mgr.hover(doc, Pos::default(), Default::default()).await.unwrap();
}
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn files_changed_on_disk_reach_the_servers_of_their_language() {
let h = harness(&[("mock", incremental_caps())]);
@@ -2730,7 +3200,7 @@ async fn noop_handler_is_usable_for_raw_peers() {
let (a, b) = tokio::io::duplex(1024);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let _server = Peer::connect(br, bw, Arc::new(MockHandler(Arc::default())));
let _server = Peer::connect(br, bw, Arc::new(MockHandler(Arc::default(), std::sync::Weak::new())));
let client = Peer::connect(ar, aw, Arc::new(NoopHandler));
let v: Value = client.request("shutdown", (), None).await.unwrap();
assert_eq!(v, Value::Null);
+98
Переглянути файл
@@ -63,6 +63,104 @@ fn lang(id: &str, ext: &str, server: LanguageServerConfig) -> LanguageConfig {
}
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires OPENIDEA_TEST_JDTLS and OPENIDEA_TEST_GRADLE_HOME, with JDK 21+"]
async fn shared_jdtls_imports_independent_gradle_builds_and_external_root() {
use serde_json::json;
let jdtls = std::env::var("OPENIDEA_TEST_JDTLS").expect("set OPENIDEA_TEST_JDTLS");
let gradle_home = std::env::var("OPENIDEA_TEST_GRADLE_HOME").expect("set OPENIDEA_TEST_GRADLE_HOME");
let dir = tempfile::tempdir().unwrap();
let temp_root = dunce::canonicalize(dir.path()).unwrap();
let root = temp_root.join("workspace");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(root).unwrap();
let external = temp_root.join("external");
let mut files = Vec::new();
for (name, build) in [("alpha", root.join("alpha")), ("beta", root.join("beta")), ("external", external.clone())] {
let source_dir = build.join("app/src/main/java/demo");
std::fs::create_dir_all(&source_dir).unwrap();
std::fs::write(build.join("settings.gradle"), format!("rootProject.name = '{name}'\ninclude 'app'\n")).unwrap();
std::fs::write(build.join("build.gradle"), "").unwrap();
std::fs::write(build.join("app/build.gradle"), "plugins { id 'java' }\n").unwrap();
let source = format!(
"package demo; public class Main {{ public static void main(String[] args) {{ {name}Marker(); }} static void {name}Marker() {{}} }}\n"
);
let path = source_dir.join("Main.java");
std::fs::write(&path, &source).unwrap();
files.push((name, path, source));
}
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
java.language_servers.retain(|s| s.name == "jdtls");
let server = &mut java.language_servers[0];
server.command = jdtls;
server.env.insert("GRADLE_USER_HOME".into(), dir.path().join("gradle-user-home").to_string_lossy().into_owned());
server.args.extend(["-data".into(), dir.path().join("jdtls-data").to_string_lossy().into_owned()]);
let options = server.initialization_options.as_mut().unwrap().as_table_mut().unwrap();
let settings = options.get_mut("settings").unwrap().as_table_mut().unwrap();
let java_settings = settings.get_mut("java").unwrap().as_table_mut().unwrap();
let imports = java_settings.get_mut("import").unwrap().as_table_mut().unwrap();
let gradle = imports.get_mut("gradle").unwrap().as_table_mut().unwrap();
gradle.insert("home".into(), toml::Value::String(gradle_home));
gradle.insert("wrapper".into(), toml::Value::try_from(json!({"enabled": false})).unwrap());
if let Ok(home) = std::env::var("OPENIDEA_TEST_GRADLE_JAVA_HOME") {
gradle.insert("java".into(), toml::Value::try_from(json!({"home": home})).unwrap());
}
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java]));
mgr.set_jdtls_shared_hook(Box::new(|| true));
mgr.set_content_roots(vec![external]);
for (_, path, source) in &files {
mgr.did_open(DocId::next(), path, &LanguageId::new("java"), 1, source);
}
retry("shared jdtls ready", Duration::from_secs(60), || {
let status = last_status(&events, "jdtls");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, message)) = &status {
panic!("shared jdtls failed: {message:?}");
}
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
for (name, path, _) in &files {
let cp = retry(&format!("{name} Gradle classpath"), Duration::from_secs(180), || async {
let cp =
tokio::time::timeout(Duration::from_secs(10), mgr.java_classpath(path, false, &Default::default()))
.await
.ok()?
.ok()?;
cp.class_paths.iter().any(|p| p.contains(&format!("/{name}/app/"))).then_some(cp)
})
.await;
assert!(
cp.class_paths
.iter()
.all(|p| !files.iter().any(|(other, _, _)| other != name && p.contains(&format!("/{other}/app/")))),
"classpath leaked between builds: {cp:?}"
);
let launch = tokio::time::timeout(
Duration::from_secs(30),
mgr.java_launch(path, false, false, false, false, &Default::default()),
)
.await
.expect("launch resolution timed out")
.expect("launch resolution failed");
assert_eq!(launch.class_paths, cp.class_paths, "launch resolved a different build for {name}");
}
let servers = mgr.servers().into_iter().filter(|s| s.name == "jdtls").collect::<Vec<_>>();
assert_eq!(servers.len(), 1, "expected one JDT LS: {servers:?}");
assert!(servers[0].pid.is_some(), "JDT LS process is not running");
for (_, path, _) in [&files[0], &files[2]] {
let bad = path.parent().unwrap().join("Broken.java");
let bad_source = "package demo; class Broken { MissingType x; }";
std::fs::write(&bad, bad_source).unwrap();
mgr.did_open(DocId::next(), &bad, &LanguageId::new("java"), 1, bad_source);
retry("diagnostics from shared JDT LS", Duration::from_secs(120), || {
let found = events.lock().iter().any(|e| matches!(e, IdeEvent::Diagnostics { path, items, .. } if path.0 == bad && items.iter().any(|d| d.message.contains("MissingType"))));
async move { found.then_some(()) }
}).await;
}
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires kmp-lsp on PATH (or OPENIDEA_TEST_KMP_LSP)"]
async fn kmp_lsp_java_end_to_end() {
+84 -2
Переглянути файл
@@ -4,8 +4,8 @@
//! than one place is taken from the first, in that order.
//!
//! Python, Django server, Django tests, pytest, npm, Jest, Vitest, Node.js, Shell Script,
//! Application, Spring Boot and compound configurations become the matching kinds; other types
//! are skipped with their type.
//! Application, Spring Boot, Go Application / Go Test and compound configurations become the
//! matching kinds; other types are skipped with their type.
//! `$PROJECT_DIR$` (and `$MODULE_DIR$`, `$MODULE_WORKING_DIR$`, `$ContentRoot$`,
//! `$ProjectFileDir$`, all the project directory here) and `$USER_HOME$` are replaced; another
//! path variable skips the configuration.
@@ -165,6 +165,8 @@ const SHELL: &str = "ShConfigurationType";
const COMPOUND: &str = "CompoundRunConfigurationType";
const APPLICATION: &str = "Application";
const SPRING_BOOT: &str = "SpringBootApplicationConfigurationType";
const GO_APPLICATION: &str = "GoApplicationRunConfiguration";
const GO_TEST: &str = "GoTestRunConfiguration";
type Res<T> = Result<T, SkipReason>;
@@ -343,6 +345,8 @@ impl Cx<'_> {
SHELL => self.shell(name, c)?,
APPLICATION => self.java_app(name, c, false, &mut ignored)?,
SPRING_BOOT => self.java_app(name, c, true, &mut ignored)?,
GO_APPLICATION => self.go_config(name, c, false, &mut ignored)?,
GO_TEST => self.go_config(name, c, true, &mut ignored)?,
COMPOUND => {
members = c.children_named("toRun").filter_map(|t| t.attr("name")).map(str::to_owned).collect();
config(name, "compound", String::new(), Vec::new(), None)
@@ -353,6 +357,84 @@ impl Cx<'_> {
Ok(Found { config, members, ignored })
}
/// A Go Application (`GoApplicationRunConfiguration`) or Go Test configuration. Both share
/// the kind (package / file / directory), the target node, `go_parameters` (go tool
/// arguments) and envs; a test adds a `pattern` and program arguments go after `-args`.
fn go_config(&self, name: &str, c: &El, test: bool, _ignored: &mut Vec<String>) -> Res<RunConfig> {
let (dir, cwd) = self.cwd(c.value("working_directory"))?;
let scope = match c.value("kind").unwrap_or("PACKAGE") {
"FILE" => "file",
"DIRECTORY" => "directory",
_ => "package",
};
let path_target = |value: Option<&str>| -> Res<Option<String>> {
Ok(self.path(value)?.map(|p| path_from(self.root, p, &dir)).filter(|p| !p.is_empty()))
};
let target = match scope {
"file" => path_target(c.value("filePath"))?
.or(self.text(c.value("package"))?)
.filter(|t| !t.is_empty())
.unwrap_or_else(|| ".".to_owned()),
"directory" => path_target(c.value("directory"))?.unwrap_or_else(|| ".".to_owned()),
_ => self.text(c.value("package"))?.filter(|t| !t.is_empty()).unwrap_or_else(|| ".".to_owned()),
};
let raw_tool = self.text(c.value("go_parameters"))?.unwrap_or_default();
let tool_args = parse_params(&raw_tool, Quotes::Double);
let raw_program = self.text(c.value("parameters"))?.unwrap_or_default();
let program_args = parse_params(&raw_program, Quotes::Double);
let pattern = self.text(c.value("pattern"))?.unwrap_or_default();
let output_dir =
self.path(c.value("output_directory"))?.map(|p| path_from(self.root, p, self.root)).unwrap_or_default();
// The form's module is the working directory relative to the project root.
let module = cwd.as_ref().map(|d| d.to_string_lossy().replace('\\', "/")).unwrap_or_default();
let run_after_build = c.option("run") != Some("false");
let targets: Vec<String> = if scope == "file" {
target.split('|').map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect()
} else {
vec![target.clone()]
};
let mut args = vec![if test { "test".to_owned() } else { "build".to_owned() }];
args.extend(tool_args.clone());
if test {
if !pattern.is_empty() {
args.extend(["-run".to_owned(), pattern.clone()]);
}
args.extend(targets);
if !program_args.is_empty() {
args.push("-args".to_owned());
args.extend(program_args.clone());
}
} else {
args.extend(targets);
}
let mut rc = config(name, "go", "go".into(), args, Some("delve"));
rc.cwd = cwd.map(Into::into);
rc.is_test = test;
let mut params = BTreeMap::from([
("goKind".to_owned(), if test { "test" } else { "build" }.to_owned()),
("scope".to_owned(), scope.to_owned()),
("target".to_owned(), target),
("toolArgs".to_owned(), raw_tool),
("programArgs".to_owned(), raw_program),
("module".to_owned(), module),
]);
if test {
if !pattern.is_empty() {
params.insert("pattern".to_owned(), pattern);
}
} else {
params.insert("outputDir".to_owned(), output_dir);
params.insert("runAfterBuild".to_owned(), run_after_build.to_string());
}
if !program_args.is_empty() {
params.insert("programArgv".to_owned(), serde_json::to_string(&program_args).unwrap_or_default());
}
params.retain(|_, value| !value.is_empty());
rc.extras.params = params;
self.envs(c, &mut rc);
Ok(rc)
}
// ------------------------------------------------------------- Python
/// The interpreter (`SDK_HOME` when the configuration doesn't use the module's), its
+71
Переглянути файл
@@ -1007,3 +1007,74 @@ fn file_urls_expand_module_and_home_macros() {
assert_eq!(cwd(home), Some(PathBuf::from("jobs dir")));
assert!(home.extras.local);
}
#[test]
fn imports_go_application_and_test_configurations() {
let dir = tempfile::tempdir().unwrap();
write(
dir.path(),
".run/build-linux-amd64.run.xml",
&run_file(
"build-linux-amd64",
r#"<configuration default="false" name="NAME" type="GoApplicationRunConfiguration" factoryName="Go Application" folderName="go-build">
<module name="goproject" />
<working_directory value="$PROJECT_DIR$" />
<go_parameters value="-ldflags &quot;-s -w&quot; -o bin/goproject.linux-amd64" />
<envs>
<env name="CGO_ENABLED" value="0" />
<env name="GOARCH" value="amd64" />
<env name="GOOS" value="linux" />
</envs>
<kind value="PACKAGE" />
<package value="goproject" />
<directory value="$PROJECT_DIR$" />
<filePath value="$PROJECT_DIR$/main.go" />
<output_directory value="$PROJECT_DIR$/bin" />
<option name="run" value="false" />
<method v="2" />
</configuration>"#,
),
);
write(
dir.path(),
".run/Test.run.xml",
&run_file(
"Run tests",
r#"<configuration default="false" name="NAME" type="GoTestRunConfiguration" factoryName="Go Test">
<module name="goproject" />
<working_directory value="$PROJECT_DIR$/pkg" />
<go_parameters value="-tags integration" />
<kind value="PACKAGE" />
<package value="example.com/pkg" />
<pattern value="TestLogin" />
<parameters value="-v -count=1" />
<method v="2" />
</configuration>"#,
),
);
let r = import_from(dir.path(), &[]);
let app = get(&r, "build-linux-amd64");
assert_eq!(app.kind, "go");
assert_eq!(app.command, "go");
assert_eq!(app.args, s(&["build", "-ldflags", "-s -w", "-o", "bin/goproject.linux-amd64", "goproject"]));
assert_eq!(app.env["GOOS"], "linux");
assert_eq!(app.extras.params["goKind"], "build");
assert_eq!(app.extras.params["scope"], "package");
assert_eq!(app.extras.params["target"], "goproject");
assert_eq!(app.extras.params["outputDir"], "bin");
assert_eq!(app.extras.params["runAfterBuild"], "false");
assert_eq!(app.extras.folder.as_deref(), Some("go-build"));
let test = get(&r, "Run tests");
assert!(test.is_test);
assert_eq!(test.kind, "go");
assert_eq!(
test.args,
s(&["test", "-tags", "integration", "-run", "TestLogin", "example.com/pkg", "-args", "-v", "-count=1"])
);
assert_eq!(cwd(test), Some(PathBuf::from("pkg")));
assert_eq!(test.extras.params["goKind"], "test");
assert_eq!(test.extras.params["pattern"], "TestLogin");
assert_eq!(test.extras.params["module"], "pkg");
}
+1
Переглянути файл
@@ -12,6 +12,7 @@ ide-core.workspace = true
ide-language.workspace = true
ide-run.workspace = true
ide-vfs.workspace = true
quick-xml = "0.42"
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
+141 -3
Переглянути файл
@@ -14,6 +14,7 @@ use crate::exe;
use crate::exec::{query_in, query_in_cancellable, which};
use ide_core::CancellationToken;
use ide_core::settings::Settings;
use quick_xml::{Reader, XmlVersion, events::Event};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
@@ -27,7 +28,7 @@ use std::time::{Duration, SystemTime};
pub struct LibraryGroup {
/// Display name, e.g. `Python 3.12 (.venv)`.
pub name: String,
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle`.
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`.
pub kind: String,
pub roots: Vec<LibraryRoot>,
}
@@ -148,6 +149,7 @@ pub fn project_libraries_stream(
return Vec::new();
}
let mut groups = dependency_groups(root, &settings, dependencies);
groups.extend(classpath_groups(&roots));
groups.extend(project_structure_groups(root, &settings));
if !cancel.is_cancelled() && !groups.is_empty() {
on_groups(groups.clone());
@@ -433,10 +435,20 @@ fn ruby_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<Lib
// ------------------------------------------------------------------ jdk
fn jdk_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
// Java modules without a build manifest carry `.classpath` / `.project` /
// `.idea` instead; a configured JDK or declared source roots mark one too.
let files = match manifests(root, JAVA_MANIFESTS) {
Some(files) => files,
None if !s.languages.java.jdk.trim().is_empty() || !s.project_structure.source_roots.is_empty() => Vec::new(),
None => return Vec::new(),
None => {
let java = [".classpath", ".project"].iter().any(|f| root.join(f).is_file())
|| root.join(".idea").is_dir()
|| !s.languages.java.jdk.trim().is_empty()
|| !s.project_structure.source_roots.is_empty();
if !java {
return Vec::new();
}
[".classpath", ".project"].iter().map(|f| root.join(f)).collect()
}
};
cached_cancellable(root, "jdk", s.languages.java.jdk.clone(), &files, cancel, || {
let jdk = crate::apply::project_jdk(root, s).or_else(|| {
@@ -470,6 +482,84 @@ fn project_structure_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
out
}
/// JDT libraries of modules without a Maven / Gradle manifest: each `.classpath`
/// in `roots` (the project root and its discovered modules) becomes a group.
fn classpath_groups(roots: &[PathBuf]) -> Vec<LibraryGroup> {
let mut out = Vec::new();
for dir in roots {
let file = dir.join(".classpath");
let Ok(text) = std::fs::read_to_string(&file) else { continue };
let mut seen = std::collections::HashSet::new();
let entries: Vec<LibraryRoot> = classpath_entries(dir, &text)
.into_iter()
.filter(|path| seen.insert(dunce::canonicalize(path).unwrap_or_else(|_| path.clone())))
.filter_map(|path| {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
if path.is_file() {
Some(LibraryRoot { name, path: ide_vfs::archive_root(&path).into() })
} else {
path.is_dir().then(|| LibraryRoot { name, path: path.into() })
}
})
.collect();
if !entries.is_empty() {
let name = dir
.file_name()
.map(|n| format!(".classpath ({})", n.to_string_lossy()))
.unwrap_or_else(|| ".classpath".into());
out.push(LibraryGroup { name, kind: "classpath".into(), roots: entries });
}
}
out
}
/// `path` (or its `sourcepath`, when it exists) of `.classpath` `kind="lib"`
/// entries resolved against the module dir; entries pointing nowhere are dropped.
pub(crate) fn classpath_entries(dir: &Path, text: &str) -> Vec<PathBuf> {
let mut out = Vec::new();
let mut reader = Reader::from_str(text);
loop {
match reader.read_event() {
Ok(Event::Empty(ref tag)) | Ok(Event::Start(ref tag)) => {
if !tag.local_name().as_ref().eq_ignore_ascii_case("classpathentry") {
continue;
}
let (mut kind, mut path, mut srcpath) = (String::new(), String::new(), String::new());
for a in tag.attributes().flatten() {
let Ok(value) = a.normalized_value(XmlVersion::Implicit1_0) else { continue };
match a.key.as_ref() {
"kind" => kind = value.into_owned(),
"path" => path = value.into_owned(),
"sourcepath" => srcpath = value.into_owned(),
_ => {}
}
}
if kind != "lib" {
continue;
}
for p in [&srcpath, &path] {
let p = p.trim_matches('/');
if p.is_empty() {
continue;
}
let candidate = dir.join(p);
if candidate.exists() {
out.push(candidate);
break;
}
}
}
Ok(Event::Eof) => break,
Err(_) => break,
_ => {}
}
}
out
}
/// The JDK home and its sources (`lib/src.zip`, `src.zip` in JDK 8) as library roots.
pub(crate) fn jdk_library(jdk: &crate::java::Jdk) -> Option<LibraryGroup> {
let name = jdk_name(&jdk.home).unwrap_or_else(|| format!("JDK {}", jdk.major));
@@ -1108,4 +1198,52 @@ mod go_cache_tests {
cached(dir.path(), "go", "same".into(), &[], detect);
assert_eq!(count.get(), 2);
}
#[test]
fn classpath_entries_resolve_lib_paths_against_the_module() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("guava.jar"), "").unwrap();
std::fs::create_dir_all(root.join("classes")).unwrap();
std::fs::create_dir_all(root.join("lib")).unwrap();
std::fs::write(root.join("lib/servlet.jar"), "").unwrap();
let text = r#"<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="guava.jar" sourcepath="sources.zip"/>
<classpathentry kind="lib" path="classes"/>
<classpathentry kind="lib" path="/lib/servlet.jar"/>
<classpathentry kind="lib" path="missing.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>"#;
std::fs::write(root.join("sources.zip"), "").unwrap();
assert_eq!(
classpath_entries(root, text),
vec![root.join("sources.zip"), root.join("classes"), root.join("lib/servlet.jar")]
);
}
#[test]
fn classpath_groups_lists_jars_per_module() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join(".classpath"), r#"<classpath><classpathentry kind="lib" path="a.jar"/></classpath>"#)
.unwrap();
std::fs::write(root.join("a.jar"), "").unwrap();
let module = root.join("module-b");
std::fs::create_dir_all(&module).unwrap();
std::fs::write(
module.join(".classpath"),
r#"<classpath><classpathentry kind="lib" path="../shared.jar"/></classpath>"#,
)
.unwrap();
std::fs::write(root.join("shared.jar"), "").unwrap();
let groups = classpath_groups(&[root.to_path_buf(), module]);
assert_eq!(groups.len(), 2);
assert_eq!(groups[0].kind, "classpath");
assert_eq!(groups[0].roots.len(), 1);
assert!(groups[0].roots[0].path.to_string_lossy().ends_with("a.jar!"));
assert_eq!(groups[1].roots.len(), 1);
}
}
+7 -2
Переглянути файл
@@ -6,6 +6,11 @@ wire-compatible products listed in **New ▸ Data Source**. Connections are save
per project in `.openidea/data-sources.toml`; passwords live outside the project
(and never in that file).
The Database tree groups procedures and functions in one `routines` folder by
default. Enable **Separate Procedures and Functions** in the Database window’s
**Options** menu to show `procedures` and `functions` folders instead. This view
option is remembered across sessions.
## Oracle: Oracle Instant Client
Oracle support uses the Oracle Call Interface, so the Oracle client libraries
@@ -50,8 +55,8 @@ search path.
- Schemas = Oracle users (`ALL_USERS`); system accounts (`SYS`, `SYSTEM`,
`XDB`, `MDSYS`…) appear only with **Schemas ▸ Show system**.
- Tables, views, columns, indexes, foreign keys, triggers, routines and
sequences are read from the `ALL_*` views.
- Tables, views, columns, indexes, foreign keys, triggers, procedures, functions
and sequences are read from the `ALL_*` views.
- The query console runs SQL and PL/SQL blocks; `BEGIN … END;` blocks (nested
`;` included) are sent as one statement, and a lone `/` on its own line ends
one as in SQL*Plus.
+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 },
{
+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();
+54 -25
Переглянути файл
@@ -946,10 +946,11 @@ enum ProjectTarget {
}
/// Routes canonical `paths` (with whether each is a folder) over `windows` (the preferred
/// free one first). A folder focuses the window that has it open, else takes a free window,
/// one first). A folder focuses the window that has it open, else takes a free window,
/// else a new one. A file inside a local project being opened (the deepest root if nested)
/// opens in that project's window; the others all join the LightEdit window, else a free
/// window or a new one switches to LightEdit for them.
/// opens in that project's window; the others join the preferred window when it holds a local
/// project or LightEdit, else the LightEdit window, else a free window or a new one switches to
/// LightEdit for them.
pub fn plan_open(paths: Vec<(PathBuf, bool)>, windows: &[(String, Holds)]) -> Vec<OpenStep> {
let mut free = windows.iter().filter(|(_, h)| *h == Holds::Nothing).map(|(l, _)| l.clone());
let (mut dirs, mut files) = (Vec::new(), Vec::new());
@@ -1009,13 +1010,23 @@ pub fn plan_open(paths: Vec<(PathBuf, bool)>, windows: &[(String, Holds)]) -> Ve
None => loose.push(file),
}
}
let preferred = windows.first().filter(|(_, h)| matches!(h, Holds::Project(_) | Holds::LightEdit));
let light = windows.iter().find(|(_, h)| *h == Holds::LightEdit);
match preferred.or(light) {
Some((label, _)) if !loose.is_empty() => {
let files = std::mem::take(&mut loose);
match in_windows.iter_mut().find(|(l, _)| l == label) {
Some((_, list)) => list.extend(files),
None => in_windows.push((label.clone(), files)),
}
}
_ => {}
}
steps.extend(in_windows.into_iter().map(|(label, files)| OpenStep::Files(label, files)));
if !loose.is_empty() {
let light = windows.iter().find(|(_, h)| *h == Holds::LightEdit).map(|(l, _)| l.clone());
steps.push(match (light, free.next()) {
(Some(label), _) => OpenStep::Files(label, loose),
(None, Some(label)) => OpenStep::Launch(label, path_launch_of(None, loose)),
(None, None) => OpenStep::New(None, loose),
steps.push(match free.next() {
Some(label) => OpenStep::Launch(label, path_launch_of(None, loose)),
None => OpenStep::New(None, loose),
});
}
steps
@@ -2023,11 +2034,13 @@ mod tests {
assert_eq!(
steps,
[
OpenStep::Files("main".into(), vec![p("/proj/src/a.rs"), p("/proj/e.rs")]),
// `/projects` is not inside `/proj`; loose files join the focused project window.
OpenStep::Files(
"main".into(),
vec![p("/proj/src/a.rs"), p("/proj/e.rs"), p("/x/b.txt"), p("/projects/d.rs")],
),
// The deepest root wins.
OpenStep::Files("project-2".into(), vec![p("/proj/sub/c.rs")]),
// `/projects` is not inside `/proj`.
OpenStep::Files("project-1".into(), vec![p("/x/b.txt"), p("/projects/d.rs")]),
]
);
}
@@ -2088,18 +2101,13 @@ mod tests {
#[test]
fn files_opened_from_a_window_go_to_their_project_window_else_light_edit() {
let windows = [
w("main", Holds::Nothing),
w("project-1", Holds::Project(p("/proj"))),
w("project-2", Holds::Nothing),
w("project-3", Holds::Other),
];
let files = vec![p("/proj/src/a.rs"), p("/x/b.txt")];
// The Welcome window turns into LightEdit itself; another free window doesn't take the files.
let (steps, here) = plan_open_files("main", files.clone(), &windows);
assert_eq!(steps, [OpenStep::Files("project-1".into(), vec![p("/proj/src/a.rs")])]);
let welcome_only = [w("main", Holds::Nothing), w("project-2", Holds::Nothing), w("project-3", Holds::Other)];
// With no local project or LightEdit window, the Welcome window turns into LightEdit itself.
let (steps, here) = plan_open_files("main", vec![p("/x/b.txt")], &welcome_only);
assert!(steps.is_empty());
assert_eq!(here, [p("/x/b.txt")]);
// A LightEdit window keeps loose files, even with another one open.
let files = vec![p("/proj/src/a.rs"), p("/x/b.txt")];
let light =
[w("main", Holds::LightEdit), w("project-1", Holds::Project(p("/proj"))), w("project-2", Holds::LightEdit)];
let (steps, here) = plan_open_files("main", files.clone(), &light);
@@ -2109,8 +2117,20 @@ mod tests {
let others = [w("main", Holds::Nothing), w("project-2", Holds::LightEdit)];
let (steps, here) = plan_open_files("main", vec![p("/x/b.txt")], &others);
assert_eq!((steps, here), (vec![OpenStep::Files("project-2".into(), vec![p("/x/b.txt")])], vec![]));
// A project window in the background doesn't take them from a Welcome window.
let with_proj = [
w("main", Holds::Nothing),
w("project-1", Holds::Project(p("/proj"))),
w("project-2", Holds::Nothing),
w("project-3", Holds::Other),
];
let (steps, here) = plan_open_files("main", files.clone(), &with_proj);
assert_eq!(steps, [OpenStep::Files("project-1".into(), vec![p("/proj/src/a.rs")])]);
assert_eq!(here, [p("/x/b.txt")]);
// A remote project window gets a new LightEdit window, never a free one or its own.
let (steps, here) = plan_open_files("project-3", files, &windows);
let remote =
[w("project-3", Holds::Other), w("main", Holds::Nothing), w("project-1", Holds::Project(p("/proj")))];
let (steps, here) = plan_open_files("project-3", files, &remote);
assert_eq!(
steps,
[OpenStep::Files("project-1".into(), vec![p("/proj/src/a.rs")]), OpenStep::New(None, vec![p("/x/b.txt")])]
@@ -2119,13 +2139,22 @@ mod tests {
}
#[test]
fn files_opened_while_running_take_a_free_window_else_a_new_one() {
let free = [w("main", Holds::Project(p("/proj"))), w("project-1", Holds::Nothing)];
fn files_opened_while_running_join_the_focused_window_else_a_free_one_else_a_new_one() {
// The focused local project window takes them, even with a LightEdit window open.
let project =
[w("main", Holds::Project(p("/proj"))), w("project-1", Holds::Nothing), w("project-2", Holds::LightEdit)];
assert_eq!(
plan_open(vec![(p("/x/a.txt"), false)], &project),
[OpenStep::Files("main".into(), vec![p("/x/a.txt")])]
);
// A project window in the background doesn't.
let free =
[w("main", Holds::Other), w("project-2", Holds::Project(p("/proj"))), w("project-1", Holds::Nothing)];
assert_eq!(
plan_open(vec![(p("/x/a.txt"), false)], &free),
[OpenStep::Launch("project-1".into(), path_launch_of(None, vec![p("/x/a.txt")]))]
);
let busy = [w("main", Holds::Project(p("/proj"))), w("project-1", Holds::Other)];
let busy = [w("main", Holds::Other)];
assert_eq!(plan_open(vec![(p("/x/a.txt"), false)], &busy), [OpenStep::New(None, vec![p("/x/a.txt")])]);
}
+4 -2
Переглянути файл
@@ -3195,7 +3195,7 @@ export type DbRoutineInfo = {
*/
export type DbRowEdit = { kind: "update"; key: DbCellValue[]; values: DbCellValue[] } | { kind: "insert"; values: DbCellValue[] } | { kind: "delete"; key: DbCellValue[] };
/** A schema's routines and sequences (the tree's `routines` / `sequences` folders). */
/** A schema's routines (procedures and functions) and sequences. */
export type DbSchemaObjects = {
routines: DbRoutineInfo[],
sequences: DbSequenceInfo[],
@@ -5271,6 +5271,8 @@ export type JavaSettings = {
* (VS Code's `java.jdt.ls.vmargs`).
*/
jdtlsVmArgs?: string,
/** Share one JDT LS across builds in an ordinary project window; other windows remain separate. */
jdtlsShared?: boolean,
/** Build Tools › Maven. */
maven?: MavenSettings,
/** Build Tools › Gradle. */
@@ -5552,7 +5554,7 @@ export type LaunchConfig = {
export type LibraryGroup = {
/** Display name, e.g. `Python 3.12 (.venv)`. */
name: string,
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle`. */
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`. */
kind: string,
roots: LibraryRoot[],
};
+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" }),
+45 -33
Переглянути файл
@@ -41,7 +41,7 @@ import { t } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
import { usePlatform } from "@/platform/platformInfo";
import { fileManagerName } from "@/platform/fileManager";
import {
activateTab,
changeSplitOrientation,
@@ -338,8 +338,8 @@ export class EditorController implements SlotHost {
.catch((e) => this.documentError(e))
.then(() => {
if (generation !== this.projectGeneration) return;
if (root) this.restoreSession(root);
else if (s.lightEdit) this.restoreSession(LIGHT_EDIT_SESSION);
if (root) return this.restoreSession(root);
else if (s.lightEdit) return this.restoreSession(LIGHT_EDIT_SESSION);
});
} else if (previous.opening && !s.opening && this.closeCommitted) {
// A failed project open returns to the same project.
@@ -354,7 +354,7 @@ export class EditorController implements SlotHost {
this.upgradeWrappedImageTabs(wrappers);
}),
);
if (prevRoot) this.restoreSession(prevRoot);
if (prevRoot) this.projectTransition = this.restoreSession(prevRoot);
if (this.manager.backend.onFsChanged)
this.disposers.push(this.manager.backend.onFsChanged((e) => this.onFilesRemoved(e.removed)));
const onWindowBlur = () => {
@@ -520,7 +520,7 @@ export class EditorController implements SlotHost {
}
/** Reopens the tabs, splits and carets saved for `root` (after the project opened). */
restoreSession(root: string) {
async restoreSession(root: string) {
this.sessionRoot = root;
const session = loadSession(root);
if (!session) return;
@@ -528,17 +528,29 @@ export class EditorController implements SlotHost {
const kinds = useContributions.getState().editorKinds;
for (const pane of Object.values(state.panes))
pane.tabs = pane.tabs.map((tab) => (documentLifecycle(tab.input, kinds) ? { ...tab, preview: false } : tab));
this.restoredViews = new Map(Object.entries(session.files));
const current = useTabs.getState();
const liveKeys = openKeys(current);
this.restoredViews = new Map(Object.entries(session.files).filter(([path]) => !liveKeys.has(fileKey(path))));
this.restoredTabs = new Set(Object.values(state.panes).flatMap((p) => p.tabs.map((t) => t.id)));
this.restoring = true;
try {
// 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);
useTabs.setState(mergeSessionTabs(current, state), true);
} finally {
this.restoring = false;
}
for (const pane of Object.values(state.panes)) if (pane.active) void this.ensureSlot(pane.active);
if (liveKeys.size)
for (const paneId of paneIds(useTabs.getState())) await this.enforcePaneTabLimit(paneId, undefined, liveKeys);
const next = useTabs.getState();
for (const pane of Object.values(next.panes)) if (pane.active) void this.ensureSlot(pane.active);
if (liveKeys.size) {
const active = this.activeTabOf(next);
if (active) {
await this.ensureSlot(active.id);
if (this.activeTabOf()?.id === active.id) this.focus();
}
}
}
private activeTabOf(s: TabsState = useTabs.getState()): Tab | null {
@@ -1131,24 +1143,7 @@ export class EditorController implements SlotHost {
this.admitting = false;
}
const canFocus = () => this.isCurrentOpening(generation) && this.activeTabOf()?.id === tabId;
const tabPrefs = editorPrefs().tabs;
await this.removeGuarded(
(current) =>
current.panes[paneId]
? enforceTabLimit(
current,
paneId,
tabPrefs.tabLimit,
tabPrefs.closingPolicy,
(tab) =>
inputDirty(tab.input, useContributions.getState().editorKinds) ??
!!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
activate ? tabId : (current.panes[paneId]?.active ?? tabId),
(tab) => inputDirty(tab.input, useContributions.getState().editorKinds) === true,
)
: current,
{ protect: (tab) => inputDirty(tab.input, useContributions.getState().editorKinds) === true },
);
await this.enforcePaneTabLimit(paneId, activate ? tabId : (useTabs.getState().panes[paneId]?.active ?? tabId));
if (!isTextInput(input)) {
if (o.focus !== false)
requestAnimationFrame(() => {
@@ -1184,6 +1179,29 @@ export class EditorController implements SlotHost {
}
}
private enforcePaneTabLimit(paneId: string, keep?: string, liveKeys?: ReadonlySet<string>) {
const prefs = editorPrefs().tabs;
const protect = (tab: Tab) =>
!!liveKeys?.has(tab.input.key) || inputDirty(tab.input, useContributions.getState().editorKinds) === true;
return this.removeGuarded(
(current) =>
current.panes[paneId]
? enforceTabLimit(
current,
paneId,
prefs.tabLimit,
prefs.closingPolicy,
(tab) =>
inputDirty(tab.input, useContributions.getState().editorKinds) ??
!!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
keep ?? current.panes[paneId]?.active ?? undefined,
protect,
)
: current,
{ protect },
);
}
activate(paneId: string, tabId: string, focus = true) {
const restored = restoreMaximizedToolWindow();
++this.activationGeneration;
@@ -1901,7 +1919,7 @@ function openInMenu(path: string): MenuItem {
label: "Open In",
submenu: [
{ kind: "action", action: "navigate.selectIn", arg: { path }, label: "Project View" },
{ kind: "action", action: "project.revealInFinder", arg: path, label: revealLabel() },
{ kind: "action", action: "project.revealInFinder", arg: path, label: fileManagerName() },
{ kind: "action", action: "project.openInTerminal", arg: path, label: "Terminal" },
{ kind: "separator" },
...menuGroupItems("openIn", { paths: [path] }),
@@ -1986,12 +2004,6 @@ export function editorController(): EditorController {
return (controller ??= new EditorController());
}
/** "Finder" / "Explorer" / "Files", like IDEA's Open In submenu. */
function revealLabel(): string {
const os = usePlatform.getState().os;
return os === "macos" ? "Finder" : os === "windows" ? "Explorer" : "Files";
}
function inPopup(target: EventTarget | null): boolean {
return target instanceof Element && !!target.closest("[data-popup]");
}
+176 -3
Переглянути файл
@@ -1,8 +1,8 @@
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 { initialTabsState, openTab, paneIds, togglePin } from "./model/tabs";
import { restoreTabsState, storeSession, type EditorSession } from "./model/session";
import { useProject } from "@/platform/project";
let ctrl: EditorController | null = null;
@@ -15,6 +15,7 @@ afterEach(() => {
useProject.setState({ project: null, lightEdit: false, settings: initialSettings } as never);
try {
localStorage.removeItem(`openidea.editorSession.v1:${LIGHT_EDIT_SESSION}`);
storeSession("/p", null);
} catch {
/* ignore */
}
@@ -55,9 +56,181 @@ describe("lightedit launch (#2229)", () => {
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 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");
});
});
function savedSplit(dir: "row" | "column" = "row"): EditorSession {
return {
version: 1,
layout: {
kind: "split",
dir,
children: [
{
kind: "pane",
tabs: [
{ path: "/p/a.ts", pinned: true },
{ path: "/p/shared.ts", preview: true },
],
active: 1,
},
{ kind: "pane", tabs: [{ path: "/p/c.ts", preview: true }, { path: "/p/shared.ts" }], active: 1 },
],
},
activePane: 1,
files: {},
};
}
function setupRestore() {
ctrl = new EditorController(
createMemoryBackend({
"/p/a.ts": "a",
"/p/b.ts": "b\nsecond",
"/p/c.ts": "c",
"/p/shared.ts": "shared",
}),
);
ctrl.start();
return ctrl;
}
describe.each([LIGHT_EDIT_SESSION, "/p"])("late session restore: %s", (root) => {
it.each(["row", "column"] as const)(
"keeps the saved %s split and intentional copies, with the CLI file active in the saved active pane",
async (dir) => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { selection: { line: 1, col: 2 } });
const live = controller.activeSlot!;
storeSession(root, savedSplit(dir));
await controller.restoreSession(root);
const state = useTabs.getState();
expect(state.layout).toMatchObject({ kind: "split", dir });
expect(paneIds(state)).toHaveLength(2);
expect(state.activePane).toBe(paneIds(state)[1]);
expect(
Object.values(state.panes)
.flatMap((p) => p.tabs)
.filter((t) => t.input.path === "/p/shared.ts"),
).toHaveLength(2);
expect(activePath()).toBe("/p/b.ts");
expect(controller.activeSlot).toBe(live);
expect(live.caret()).toMatchObject({ line: 1, col: 2 });
expect(live.wantsFocus).toBe(true);
},
);
it("keeps pins before regular tabs, including after a subsequent pin and open", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { focus: false });
storeSession(root, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/a.ts", pinned: true }], active: 0 },
activePane: 0,
files: {},
});
await controller.restoreSession(root);
let state = useTabs.getState();
expect(state.panes[state.activePane]!.tabs.map((t) => t.pinned)).toEqual([true, false]);
const pinned = togglePin(state, state.activePane, state.panes[state.activePane]!.active!);
state = openTab(pinned, pinned.activePane, { kind: "file", key: "file:/p/c.ts", path: "/p/c.ts" }).state;
expect(state.panes[state.activePane]!.tabs.map((t) => t.pinned)).toEqual([true, true, false]);
});
it("keeps at most one preview per pane when the live tab and both saved panes have previews", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { preview: true, focus: false });
storeSession(root, savedSplit());
await controller.restoreSession(root);
for (const pane of Object.values(useTabs.getState().panes))
expect(pane.tabs.filter((t) => t.preview).length).toBeLessThanOrEqual(1);
expect(openFilePaths(useTabs.getState())).toContain("/p/b.ts");
});
it("enforces the tab limit without evicting the launched tab", async () => {
useProject.setState({ settings: { editor: { tabs: { tabLimit: 1, closingPolicy: "lru" } } } as never });
const controller = setupRestore();
await controller.openFile("/p/b.ts", { focus: false });
storeSession(root, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/a.ts" }], active: 0 },
activePane: 0,
files: {},
});
await controller.restoreSession(root);
expect(openFilePaths(useTabs.getState())).toEqual(["/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
});
it("keeps the live same-key slot and launch target instead of the saved caret", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { selection: { line: 1, col: 2 } });
const slot = controller.activeSlot!;
storeSession(root, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/b.ts", pinned: true }], active: 0 },
activePane: 0,
files: { "/p/b.ts": { anchor: 0, head: 0 } },
});
await controller.restoreSession(root);
expect(openFilePaths(useTabs.getState())).toEqual(["/p/b.ts"]);
expect(controller.activeSlot).toBe(slot);
expect(slot.caret()).toMatchObject({ line: 1, col: 2 });
expect(useTabs.getState().panes[useTabs.getState().activePane]!.tabs[0]!.pinned).toBe(true);
});
it("moves a saved same-key launch target into the saved active pane without losing the split", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { selection: { line: 1, col: 2 } });
const slot = controller.activeSlot!;
const session = savedSplit();
if (session.layout.kind !== "split") throw new Error("expected split");
session.layout.children[0] = { kind: "pane", tabs: [{ path: "/p/b.ts", pinned: true }], active: 0 };
storeSession(root, session);
await controller.restoreSession(root);
const state = useTabs.getState();
expect(state.layout).toMatchObject({ kind: "split", dir: "row" });
expect(state.activePane).toBe(paneIds(state)[1]);
expect(
Object.values(state.panes)
.flatMap((p) => p.tabs)
.filter((t) => t.input.path === "/p/b.ts"),
).toHaveLength(1);
expect(controller.activeSlot).toBe(slot);
expect(slot.caret()).toMatchObject({ line: 1, col: 2 });
expect(state.panes[state.activePane]!.tabs[0]!.pinned).toBe(true);
});
it("protects every live tab when they already exceed the configured limit", async () => {
const controller = setupRestore();
await controller.openFile("/p/b.ts", { focus: false });
await controller.openFile("/p/c.ts", { preview: true, focus: false });
useProject.setState({ settings: { editor: { tabs: { tabLimit: 1 } } } as never });
storeSession(root, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/a.ts" }], active: 0 },
activePane: 0,
files: {},
});
await controller.restoreSession(root);
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/b.ts", "/p/c.ts"]);
expect(activePath()).toBe("/p/c.ts");
});
it("takes the saved state unchanged when the window is empty", async () => {
const controller = setupRestore();
storeSession(root, savedSplit());
await controller.restoreSession(root);
const saved = restoreTabsState(savedSplit(), (p) => `file:${p}`);
const state = useTabs.getState();
expect(paneIds(state)).toHaveLength(2);
expect(Object.values(state.panes).map((p) => p.tabs.map((t) => [t.input.path, t.pinned, t.preview]))).toEqual(
Object.values(saved.panes).map((p) => p.tabs.map((t) => [t.input.path, t.pinned, t.preview])),
);
expect(activePath()).toBe("/p/shared.ts");
});
});
+22
Переглянути файл
@@ -347,6 +347,28 @@ describe("DocumentManager + slots", () => {
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", () => {
+9 -3
Переглянути файл
@@ -242,9 +242,8 @@ export class EditorSlot {
this.kept = null;
const i = keptSlots.indexOf(this);
if (i >= 0) keptSlots.splice(i, 1);
const top = topLineAt(view, this.scrollPos.top);
this.savedTopLine = top;
this.scroll = EditorView.scrollIntoView(view.state.doc.line(top + 1).from, { y: "start" });
this.savedTopLine = topLineAt(view, this.scrollPos.top);
this.scroll = scrollSnapshotAt(view, this.scrollPos);
this.stored = view.state;
view.destroy();
}
@@ -399,6 +398,13 @@ function topLineOf(view: EditorView): number {
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;
+47 -19
Переглянути файл
@@ -93,27 +93,55 @@ 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.
*/
/** Replays live tabs into the saved layout, retaining their slots and the launch target. */
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);
const live = new Map<string, Tab>();
for (const pane of Object.values(current.panes)) for (const tab of pane.tabs) live.set(tab.input.key, tab);
if (!live.size) return restored;
const active = current.panes[current.activePane]?.tabs.find(
(t) => t.id === current.panes[current.activePane]?.active,
);
if (active) live.set(active.input.key, active);
let next = restored;
for (const tab of live.values()) {
let found = findTab(next, tab.input.key, restored.activePane);
let opening = tab;
// Put the launch target in the saved active pane without collapsing its saved source pane.
if (tab === active && found && found.paneId !== restored.activePane) {
const source = paneOf(next, found.paneId);
const savedId = found.tab.id;
const tabs = source.tabs.filter((t) => t.id !== savedId);
const mru = source.mru.filter((id) => id !== savedId);
next = withPane(next, {
...source,
tabs,
mru,
active: source.active === savedId ? (mru[0] ?? tabs[0]?.id ?? null) : source.active,
});
opening = { ...found.tab, input: tab.input };
found = null;
}
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 });
if (!found) {
const pane = paneOf(next, restored.activePane);
const opened = openTab(next, pane.id, tab.input, {
pinned: opening.pinned,
preview: opening.preview && !pane.tabs.some((t) => t.preview),
preservePreview: true,
activate: false,
});
next = opened.state;
found = { paneId: pane.id, tab: paneOf(next, pane.id).tabs.find((t) => t.id === opened.tabId)! };
}
const pane = paneOf(next, found.paneId);
const savedId = found.tab.id;
next = withPane(next, {
...pane,
tabs: pane.tabs.map((t) => (t.id === savedId ? { ...t, id: tab.id, input: tab.input } : t)),
active: pane.active === savedId ? tab.id : pane.active,
mru: pane.mru.map((id) => (id === savedId ? tab.id : id)),
});
}
return active ? activateTab(next, restored.activePane, active.id) : next;
}
function withPane(s: TabsState, pane: Pane): TabsState {
+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"));
+108
Переглянути файл
@@ -0,0 +1,108 @@
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DatabaseView } from "./DatabaseView";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { registerDatabaseTreeActions } from "./treeActions";
import { tablesKey, useDatabase } from "./store";
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
getTotalSize: () => count * 24,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
scrollToIndex: () => {},
measure: () => {},
}),
}));
let dispose: () => void;
beforeEach(() => {
localStorage.removeItem("openidea.database.viewOptions");
setContext("projectOpen", true);
dispose = registerDatabaseTreeActions();
useDatabase.setState({
loaded: true,
sources: [{ id: "pg", name: "PostgreSQL", driver: "postgres", options: { singleDatabase: true } }],
schemas: { pg: { status: "ok", value: ["public"] } },
tables: { [tablesKey("pg", "public")]: { status: "ok", value: [] } },
objects: {
[tablesKey("pg", "public")]: {
routines: [
{ name: "calculate", kind: "function", arguments: "integer", returns: "integer" },
{ name: "calculate", kind: "function", arguments: "text", returns: "text" },
{ name: "refresh_data", kind: "procedure", arguments: "", returns: null },
],
sequences: [],
},
},
treeFilter: "",
separateProceduresAndFunctions: false,
treeExpanded: new Set(["pg", "pg/public", "pg/public/routines"]),
});
});
afterEach(() => dispose());
describe("routine grouping", () => {
it("keeps an existing expanded routines folder and both overloads by default", () => {
render(<DatabaseView />);
const tree = within(screen.getByRole("tree", { name: "Data sources" }));
expect(tree.getByText("routines").closest('[role="treeitem"]')).toHaveAttribute("aria-expanded", "true");
expect(tree.getAllByText("calculate")).toHaveLength(2);
expect(tree.getByText("refresh_data")).toBeInTheDocument();
expect(tree.queryByText("procedures")).toBeNull();
expect(tree.queryByText("functions")).toBeNull();
fireEvent.mouseDown(tree.getAllByText("calculate")[1]!, { button: 0 });
expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/routines/calculate(text)");
act(() => useDatabase.setState({ treeFilter: "refresh" }));
expect(tree.queryAllByText("calculate")).toHaveLength(0);
expect(tree.getByText("refresh_data")).toBeInTheDocument();
});
it("toggles through the action, persists the option, and restores the old expansion", async () => {
expect(useDatabase.getInitialState().separateProceduresAndFunctions).toBe(false);
render(<DatabaseView />);
const tree = within(screen.getByRole("tree", { name: "Data sources" }));
await act(() => executeAction("db.separateProceduresAndFunctions"));
expect(JSON.parse(localStorage.getItem("openidea.database.viewOptions")!)).toEqual({
separateProceduresAndFunctions: true,
});
expect(tree.queryByText("routines")).toBeNull();
const procedures = tree.getByText("procedures").closest('[role="treeitem"]')!;
const functions = tree.getByText("functions").closest('[role="treeitem"]')!;
expect(within(procedures as HTMLElement).getByText("1")).toBeInTheDocument();
expect(within(functions as HTMLElement).getByText("2")).toBeInTheDocument();
fireEvent.mouseDown(functions.querySelector("[data-tree-toggle]")!, { button: 0 });
expect(tree.getAllByText("calculate")).toHaveLength(2);
fireEvent.mouseDown(tree.getAllByText("calculate")[1]!, { button: 0 });
expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/functions/calculate(text)");
await act(() => executeAction("db.separateProceduresAndFunctions"));
expect(tree.getByText("routines").closest('[role="treeitem"]')).toHaveAttribute("aria-expanded", "true");
expect(tree.getAllByText("calculate")).toHaveLength(2);
expect(tree.getByText("refresh_data")).toBeInTheDocument();
expect(JSON.parse(localStorage.getItem("openidea.database.viewOptions")!)).toEqual({
separateProceduresAndFunctions: false,
});
});
it.each([false, true])("applies object and quick filters before grouping (separate: %s)", (separate) => {
const source = useDatabase.getState().sources[0]!;
useDatabase.setState({
separateProceduresAndFunctions: separate,
sources: [{ ...source, introspection: { objectFilter: "calculate" } }],
treeExpanded: new Set(["pg", "pg/public", "pg/public/routines", "pg/public/functions"]),
});
render(<DatabaseView />);
const tree = within(screen.getByRole("tree", { name: "Data sources" }));
expect(tree.queryByText("procedures")).toBeNull();
expect(tree.queryByText("refresh_data")).toBeNull();
expect(tree.getAllByText("calculate")).toHaveLength(2);
const folder = tree.getByText(separate ? "functions" : "routines").closest('[role="treeitem"]')!;
expect(within(folder as HTMLElement).getByText("2")).toBeInTheDocument();
act(() => useDatabase.setState({ treeFilter: "refresh" }));
expect(tree.queryByText("public")).toBeNull();
expect(tree.queryByText("routines")).toBeNull();
expect(tree.queryByText("functions")).toBeNull();
});
});
+45 -19
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Database tool window (IDEA's layout): data source → database (PostgreSQL) → schema → `tables` /
* `views` / `materialized views` / `routines` / `sequences` folders → table → `columns` / `keys` /
* `foreign keys` / `indexes` / `triggers`,
* `views` / `materialized views` / `routines` (optionally `procedures` / `functions`) / `sequences`
* folders → table → `columns` / `keys` / `foreign keys` / `indexes` / `triggers`,
* with counts and column types, loaded lazily. Double-click a table to open its data, a data
* source to open its query console.
*/
@@ -32,7 +32,15 @@ import {
splitTarget,
targetOf,
} from "./model";
import { nodeTarget, schemaObjectOf, tableFolder, type DbNode as Node, type Folder, type Group } from "./nodes";
import {
nodeTarget,
routineFolder,
schemaObjectOf,
tableFolder,
type DbNode as Node,
type Folder,
type Group,
} from "./nodes";
import {
connect,
detailsKey,
@@ -66,10 +74,20 @@ const FOLDER_LABELS: Record<Folder, string> = {
views: "views",
materializedViews: "materialized views",
routines: "routines",
procedures: "procedures",
functions: "functions",
sequences: "sequences",
};
const FOLDERS: readonly Folder[] = ["tables", "views", "materializedViews", "routines", "sequences"];
const SEPARATE_FOLDERS: readonly Folder[] = [
"tables",
"views",
"materializedViews",
"procedures",
"functions",
"sequences",
];
function status<T>(key: string, l: Loaded<T> | undefined, map: (v: T) => Node[]): Node[] | undefined {
if (!l) return undefined;
@@ -101,6 +119,7 @@ function groupSize(d: DbTableDetails, g: Group): number {
export function DatabaseView() {
const st = useDatabase();
const folders = st.separateProceduresAndFunctions ? SEPARATE_FOLDERS : FOLDERS;
const tree = useRef<TreeHandle>(null);
useEffect(() => {
if (!st.loaded) void loadSources();
@@ -149,9 +168,12 @@ export function DatabaseView() {
(st.objects[tablesKey(id, schema)]?.routines ?? []).filter(shown(id));
const sequencesOf = (id: string, schema: string) =>
(st.objects[tablesKey(id, schema)]?.sequences ?? []).filter(shown(id));
/** Members of a schema folder: tables / views / materialized views, routines or sequences. */
/** Members of a schema folder, after object and quick filtering. */
const folderSize = (id: string, schema: string, folder: Folder): number => {
if (folder === "routines") return routinesOf(id, schema).length;
if (folder === "routines" || folder === "procedures" || folder === "functions")
return routinesOf(id, schema).filter(
(routine) => routineFolder(routine.kind, st.separateProceduresAndFunctions) === folder,
).length;
if (folder === "sequences") return sequencesOf(id, schema).length;
return (tablesOf(id, schema) ?? []).filter((t) => tableFolder(t.kind) === folder).length;
};
@@ -205,24 +227,28 @@ export function DatabaseView() {
return schemasOf(n.key, n.id);
case "schema":
return status(n.key, st.tables[tablesKey(n.id, n.schema)], () =>
FOLDERS.filter((f) => folderSize(n.id, n.schema, f) > 0).map((folder): Node => ({
kind: "folder",
key: `${n.key}/${folder}`,
id: n.id,
schema: n.schema,
folder,
})),
folders
.filter((f) => folderSize(n.id, n.schema, f) > 0)
.map((folder): Node => ({
kind: "folder",
key: `${n.key}/${folder}`,
id: n.id,
schema: n.schema,
folder,
})),
);
case "folder": {
const at = { id: n.id, schema: n.schema };
if (n.folder === "routines")
if (n.folder === "routines" || n.folder === "procedures" || n.folder === "functions")
// Overloads share a name: the key tells them apart by their arguments.
return routinesOf(n.id, n.schema).map((routine) => ({
kind: "routine",
key: `${n.key}/${routine.name}(${routine.arguments})`,
routine,
...at,
}));
return routinesOf(n.id, n.schema)
.filter((routine) => routineFolder(routine.kind, st.separateProceduresAndFunctions) === n.folder)
.map((routine) => ({
kind: "routine",
key: `${n.key}/${routine.name}(${routine.arguments})`,
routine,
...at,
}));
if (n.folder === "sequences")
return sequencesOf(n.id, n.schema).map((sequence) => ({
kind: "sequence",
+7 -1
Переглянути файл
@@ -4,7 +4,7 @@
* results grids, and a table data editor. Connections, introspection and
* statements run in Rust (`ide-db`).
*/
import { lazyComponent, lazyWhen } from "@/ui";
import { lazyComponent, lazyWhen, type MenuItem } from "@/ui";
import { activeEditor, lazyEditorExtension, registerEditorContribution } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { onIdeEvent } from "@/platform/ipc";
@@ -41,6 +41,11 @@ import {
watchIdleConnections,
} from "./store";
function useDatabaseHeaderMenu(): MenuItem[] {
const separate = useDatabase((s) => s.separateProceduresAndFunctions);
return [{ kind: "action", action: "db.separateProceduresAndFunctions", checked: separate }];
}
const useDialogOpen = () => useDatabase((s) => !!s.dialog);
export function activate(): () => void {
@@ -55,6 +60,7 @@ export function activate(): () => void {
anchor: "right",
order: 20,
component: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseView)),
headerMenu: useDatabaseHeaderMenu,
headerActions: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseHeaderActions)),
}),
registerServiceView({
+17
Переглянути файл
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { routineFolder, tableFolder } from "./nodes";
describe("schema folders", () => {
it("combines routines by default and separates them on request", () => {
expect(routineFolder("procedure")).toBe("routines");
expect(routineFolder("function")).toBe("routines");
expect(routineFolder("procedure", true)).toBe("procedures");
expect(routineFolder("function", true)).toBe("functions");
});
it("keeps tables, views and materialized views apart", () => {
expect(tableFolder("table")).toBe("tables");
expect(tableFolder("view")).toBe("views");
expect(tableFolder("materializedView")).toBe("materializedViews");
});
});
+8 -2
Переглянути файл
@@ -15,14 +15,20 @@ import type { DbObjectRef } from "./objects";
export type Group = "columns" | "keys" | "foreignKeys" | "indexes" | "triggers";
/** Folders under a schema: IDEA's `tables`, `views`, `materialized views`, `routines`, `sequences`. */
export type Folder = "tables" | "views" | "materializedViews" | "routines" | "sequences";
/** Schema folders; routines can optionally be separated into procedures and functions. */
export type Folder = "tables" | "views" | "materializedViews" | "routines" | "procedures" | "functions" | "sequences";
/** The folder a table, view or materialized view is listed in. */
export function tableFolder(kind: DbTableKind): Folder {
return kind === "view" ? "views" : kind === "materializedView" ? "materializedViews" : "tables";
}
/** IDEA's *Separate Procedures and Functions* option: the folder a routine is listed in. */
export function routineFolder(kind: DbRoutineInfo["kind"], separate = false): "routines" | "procedures" | "functions" {
if (!separate) return "routines";
return kind === "procedure" ? "procedures" : "functions";
}
/** Where a table-level node lives: connection target, schema, table. */
interface InTable {
id: string;
+22
Переглянути файл
@@ -57,6 +57,7 @@ export const DB_TOOL_WINDOW = "database";
export const RESULTS_VIEW = "dbResults";
const BINDINGS_KEY = "openidea.database.consoles";
const CONSOLE_SCHEMAS_KEY = "openidea.database.consoleSchemas";
const VIEW_OPTIONS_KEY = "openidea.database.viewOptions";
const MAX_TABS = 12;
export interface ResultTab {
@@ -144,6 +145,7 @@ interface DatabaseState {
consoleSchemas: Record<string, string>;
/** The Database tree's quick object filter (empty: everything shows). */
treeFilter: string;
separateProceduresAndFunctions: boolean;
completion: Record<string, DbCompletion>;
results: ResultTab[];
/** Result tab id, or `OUTPUT_TAB`. */
@@ -189,6 +191,15 @@ function readConsoleSchemas(): Record<string, string> {
}
}
function readSeparateProceduresAndFunctions(): boolean {
try {
const raw = localStorage.getItem(VIEW_OPTIONS_KEY);
return raw ? JSON.parse(raw)?.separateProceduresAndFunctions === true : false;
} catch {
return false;
}
}
export const useDatabase = create<DatabaseState>(() => ({
sources: [],
loaded: false,
@@ -201,6 +212,7 @@ export const useDatabase = create<DatabaseState>(() => ({
consoles: readBindings(),
consoleSchemas: readConsoleSchemas(),
treeFilter: "",
separateProceduresAndFunctions: readSeparateProceduresAndFunctions(),
completion: {},
results: [],
activeResult: null,
@@ -218,6 +230,16 @@ export const useDatabase = create<DatabaseState>(() => ({
pendingTx: new Set(),
}));
export function toggleSeparateProceduresAndFunctions() {
const separateProceduresAndFunctions = !useDatabase.getState().separateProceduresAndFunctions;
useDatabase.setState({ separateProceduresAndFunctions });
try {
localStorage.setItem(VIEW_OPTIONS_KEY, JSON.stringify({ separateProceduresAndFunctions }));
} catch {
// Per-viewer convenience only.
}
}
export const tablesKey = (id: string, schema: string) => `${id}\u0000${schema}`;
export const detailsKey = (id: string, schema: string, table: string) => `${id}\u0000${schema}\u0000${table}`;
+25
Переглянути файл
@@ -125,4 +125,29 @@ describe("table editor capabilities", () => {
uninstall();
}
});
it("counts the editor-area host focusing the tab as table-editor focus (#2307)", async () => {
backend.driver = "postgres";
const uninstall = installTableEditorFocus();
try {
let root!: HTMLElement;
await act(async () => {
const r = render(<TableEditor input={tableInput("source", "public", "users")} />);
root = r.container;
});
// Mimic EditorArea wrapping the tab in its focusable host, then focusing the host on open.
const host = root.closest("div")!;
host.setAttribute("data-editor-focus", "");
host.tabIndex = -1;
act(() => host.focus());
expect(getContext()).toMatchObject({ dbTableEditorFocus: true, dbTableEditorChanges: false });
// A later focus inside a text field still turns it off.
const input = document.createElement("input");
root.querySelector("[data-db-table-editor]")!.appendChild(input);
act(() => input.focus());
expect(getContext().dbTableEditorFocus).toBe(false);
} finally {
uninstall();
}
});
});
+5 -1
Переглянути файл
@@ -23,7 +23,11 @@ function update() {
function onFocusIn(event: FocusEvent) {
const target = event.target instanceof Element ? event.target : null;
const root = target?.closest("[data-db-table-editor]");
// The editor area focuses its host `[data-editor-focus]` when the tab opens —
// treat that as focus inside a table editor so ⌘F12 / ⌘↩ work right away.
const root =
target?.closest("[data-db-table-editor]") ??
(target?.hasAttribute("data-editor-focus") ? target.querySelector("[data-db-table-editor]") : null);
active = (root && !isTextField(target!) && handles.get(root)) || null;
update();
}
+6
Переглянути файл
@@ -32,6 +32,7 @@ import {
runSql,
sourceById,
tablesKey,
toggleSeparateProceduresAndFunctions,
useDatabase,
withConnection,
removeSource,
@@ -462,6 +463,11 @@ export function registerDatabaseTreeActions(): () => void {
useDatabase.setState({ newMenuOpen: true });
},
}),
tree({
id: "db.separateProceduresAndFunctions",
title: "Separate Procedures and Functions",
run: toggleSeparateProceduresAndFunctions,
}),
tree({
id: "db.collapseAll",
title: "Collapse All",
+114 -1
Переглянути файл
@@ -1,5 +1,11 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const executeAction = vi.hoisted(() => vi.fn());
vi.mock("@/platform/actions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/actions")>()),
executeAction,
}));
const ipc = vi.hoisted(() => {
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
return {
@@ -18,7 +24,9 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
return { ...real, isTauri: () => true, commands: { ...real.commands, ...cmds } };
});
const notes = vi.hoisted(() => [] as Array<{ level: string; title: string; body?: unknown; actions?: unknown[] }>);
const notes = vi.hoisted(
() => [] as Array<{ level: string; title: string; body?: unknown; actions?: { label: string; run: () => void }[] }>,
);
vi.mock("@/workbench/contributions", async (importOriginal) => {
const real = await importOriginal<typeof import("@/workbench/contributions")>();
return {
@@ -74,6 +82,7 @@ function session(id: number, hotCodeReplace: boolean): DebugSession {
describe("HotSwap", () => {
beforeEach(() => {
notes.length = 0;
executeAction.mockClear();
ipc.cancelRequest.mockClear();
ipc.javaBuildWorkspace.mockClear();
ipc.debugRedefineClasses.mockReset();
@@ -226,6 +235,110 @@ describe("HotSwap", () => {
expect(hotSwapMessage(3, ["boom"])).toMatchObject({ level: "error", body: "boom" });
});
it.each([0, 1, 3])("reports obsolete methods as a reload warning even with %s returned classes", (changed) => {
expect(hotSwapMessage(changed, ["JVM contains obsolete methods"])).toMatchObject({
level: "warning",
title: "Classes reloaded",
body: expect.stringContaining("Active frames keep running the old code"),
});
expect(hotSwapMessage(changed, ["JVM contains obsolete methods"], true).body).toContain(
"bottom frame cannot be reset",
);
});
it.each([
"Failed to redefine classes: add method not implemented",
"Failed to redefine classes: schema change not implemented",
"Failed to redefine classes: JVM contains obsolete methods",
])("keeps a real failure even alongside obsolete methods: %s", (failure) => {
for (const errors of [[failure], ["JVM contains obsolete methods", failure]]) {
expect(hotSwapMessage(1, errors)).toMatchObject({ level: "error", title: "Hot Swap failed" });
}
});
function pausedFrames(names: string[], restartFrame = true): DebugSession {
return {
...session(1, true),
status: "paused",
caps: { hotCodeReplace: true, restartFrame } as DebugCapabilities,
selectedThread: 1,
selectedFrame: 11,
frames: names.map((name, i) => ({
id: 11 + i,
name,
path: "/p/App.java",
line: 11,
column: 0,
presentationHint: null,
})),
};
}
it.each([
[true, ["App.main(String[])"], false],
[false, ["OrderBook.place()", "App.main(String[])"], false],
[true, ["OrderBook.place()", "Native.call()[native method]"], false],
[true, ["Native.call()[native method]", "App.main(String[])"], false],
[true, ["OrderBook.place()", "App.main(String[])"], true],
])("offers Reset Frame only when supported and droppable (%s, %j)", async (supported, names, offered) => {
useDebug.setState({ sessions: { 1: pausedFrames(names, supported) } });
ipc.debugRedefineClasses.mockImplementationOnce(() =>
ipc.ok({ changedClasses: [], errorMessage: "JVM contains obsolete methods" }),
);
await reloadChangedClasses(false);
const note = notes.at(-1)!;
expect(note).toMatchObject({ level: "warning", title: "Classes reloaded" });
expect(note.actions).toHaveLength(offered ? 1 : 0);
if (offered) {
useDebug.setState({ active: 2 });
note.actions![0]!.run();
expect(executeAction).toHaveBeenCalledWith("debug.resetFrame");
expect(useDebug.getState().active).toBe(1);
expect(useDebug.getState().sessions[1]?.selectedFrame).toBe(11);
}
});
it("does not reset a stale frame from an earlier suspension", async () => {
const s = pausedFrames(["OrderBook.place()", "App.main(String[])"]);
useDebug.setState({ sessions: { 1: s } });
ipc.debugRedefineClasses.mockImplementationOnce(() =>
ipc.ok({ changedClasses: [], errorMessage: "JVM contains obsolete methods" }),
);
await reloadChangedClasses(false);
useDebug.setState({ sessions: { 1: { ...s, frames: [...s.frames] } } });
notes.at(-1)!.actions![0]!.run();
expect(executeAction).not.toHaveBeenCalled();
});
it("maps java-debug's obsolete-method ERROR event to the same warning", () => {
useDebug.setState({ sessions: { 1: pausedFrames(["App.main(String[])"]) } });
onHotCodeReplace(1 as DebugSessionId, {
kind: "hotCodeReplace",
changeType: "ERROR",
message: "JVM contains obsolete methods",
});
expect(notes.at(-1)).toMatchObject({
level: "warning",
title: "Classes reloaded",
body: expect.stringContaining("bottom frame cannot be reset"),
actions: [],
});
});
it("does not let the obsolete-method event replace the response's real failure", async () => {
ipc.debugRedefineClasses.mockImplementationOnce(async () => {
onHotCodeReplace(1 as DebugSessionId, {
kind: "hotCodeReplace",
changeType: "ERROR",
message: "JVM contains obsolete methods",
});
return ipc.ok({ changedClasses: [], errorMessage: "Failed to redefine classes: add method not implemented" });
});
await reloadChangedClasses(false);
expect(notes).toHaveLength(1);
expect(notes[0]).toMatchObject({ level: "error", title: "Hot Swap failed" });
});
it("translates the reload count with the sentence", async () => {
await setLocale("zh");
try {
+78 -6
Переглянути файл
@@ -16,8 +16,9 @@ import {
type RequestId,
} from "@/platform/ipc";
import { setContext } from "@/platform/context";
import { executeAction } from "@/platform/actions";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { isLive, useDebug, type DebugSession } from "./state";
import { isLive, selectFrame, selectSession, useDebug, type DebugSession } from "./state";
import { tx } from "@/platform/i18n";
import type { MenuItem } from "@/ui/Menu";
@@ -48,16 +49,61 @@ export function hotSwapMenuItems(paths: readonly string[]): MenuItem[] {
/** "3 classes", translated per count (the sentence around it is translated on its own). */
const classesText = (n: number) => (n === 1 ? tx`${n} class` : tx`${n} classes`);
// java-debug reports this after redefineClasses succeeds, with no changedClasses count.
const obsoleteMethods = (message: string) => message.trim() === "JVM contains obsolete methods";
/** Message for the reload result (IDEA wording). */
export function hotSwapMessage(
changed: number,
errors: string[],
): { level: "info" | "error"; title: string; body?: string } {
if (errors.length) return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
bottomFrame = false,
): { level: "info" | "warning" | "error"; title: string; body?: string } {
if (errors.some((e) => !obsoleteMethods(e)))
return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
if (errors.length)
return {
level: "warning",
title: "Classes reloaded",
body:
tx("Active frames keep running the old code until they return. New calls use the reloaded code.") +
(bottomFrame
? " " +
tx(
"The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.",
)
: ""),
};
if (changed === 0) return { level: "info", title: "Loaded classes are up to date. Nothing to reload." };
return { level: "info", title: tx`${classesText(changed)} reloaded` };
}
function obsoleteFrameActions(sessions: DebugSession[]) {
return sessions.flatMap((s) => {
const frame = s.frames[0];
// java-debug cannot drop the bottom frame or frames involving a native caller.
if (
s.status !== "paused" ||
!s.caps?.restartFrame ||
!frame ||
s.frames.length < 2 ||
s.frames.slice(0, 2).some((f) => f.name.includes("[native method]"))
)
return [];
return [
{
label: sessions.length > 1 ? tx`Reset Frame (${s.name})` : "Reset Frame",
run: () => {
const current = useDebug.getState().sessions[s.id];
if (current?.status !== "paused" || current.frames !== s.frames) return;
selectSession(s.id);
selectFrame(s.id, frame.id, false);
void executeAction("debug.resetFrame");
},
},
];
});
}
/** Compiles (unless `build` is false) and reloads changed classes into every Java debug session. */
export async function reloadChangedClasses(build = true, configId?: string): Promise<void> {
if (reloading) return;
@@ -136,17 +182,31 @@ export async function reloadChangedClasses(build = true, configId?: string): Pro
}
const changed = new Set<string>();
const errors: string[] = [];
const obsolete: DebugSessionId[] = [];
for (const s of sessions) {
try {
const r = await call(commands.debugRedefineClasses(s.id));
r.changedClasses.forEach((c) => changed.add(c));
if (r.errorMessage) errors.push(r.errorMessage);
if (r.errorMessage) {
errors.push(r.errorMessage);
if (obsoleteMethods(r.errorMessage)) obsolete.push(s.id);
}
} catch (e) {
errors.push(e instanceof Error ? e.message : String(e));
}
}
const m = hotSwapMessage(changed.size, errors);
notifications().notify({ group: "run", key: KEY, ...m });
const affected = obsolete.flatMap((id) => useDebug.getState().sessions[id] ?? []);
const m = hotSwapMessage(
changed.size,
errors,
affected.some((s) => s.status === "paused" && s.frames.length === 1),
);
notifications().notify({
group: "run",
key: KEY,
...m,
...(m.level === "warning" ? { sticky: true, actions: obsoleteFrameActions(affected) } : {}),
});
} finally {
reloading = false;
quietUntil = Date.now() + 2_000;
@@ -170,6 +230,18 @@ export function onHotCodeReplace(session: DebugSessionId, event: Extract<DebugEv
break;
case "ERROR":
case "WARNING":
if (obsoleteMethods(event.message)) {
if (reloading) return;
const s = useDebug.getState().sessions[session]!;
notifications().notify({
group: "run",
key: KEY,
...hotSwapMessage(0, [event.message], s.status === "paused" && s.frames.length === 1),
sticky: true,
actions: obsoleteFrameActions([s]),
});
return;
}
notifications().notify({
group: "run",
level: event.changeType === "ERROR" ? "error" : "warning",
+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],
+4 -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";
@@ -28,6 +29,7 @@ const GROUP_ICONS: Record<string, string> = {
goModules: "file-gomod",
maven: "maven-project",
gradle: "file-gradle",
classpath: "file-java",
ruby: "file-ruby",
gems: "file-ruby",
};
@@ -57,6 +59,7 @@ const MANIFESTS = new Set([
"go.mod",
"go.sum",
"go.work",
".classpath",
"pyproject.toml",
"setup.py",
"requirements.txt",
@@ -73,7 +76,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);
+2 -1
Переглянути файл
@@ -2,6 +2,7 @@
import { activeEditor } from "@/editor/api";
import { getAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { revealInFileManagerLabel } from "@/platform/fileManager";
import { dirname, useProject } from "@/platform/project";
import { showContextMenu, type MenuItem } from "@/ui";
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
@@ -388,7 +389,7 @@ export function registerProjectActions(): () => void {
copyPath("source", "project.copySourceRootPath", "Copy Path From Source Root"),
{
id: "project.revealInFinder",
title: tx`Reveal in ${revealLabel()}`,
title: revealInFileManagerLabel(),
category: "Project View",
icon: "external-link",
when: OPEN,
+2 -4
Переглянути файл
@@ -1,5 +1,6 @@
/** Context menu and "New" popup of the project view. */
import { executeAction, getAction } from "@/platform/actions";
import { fileManagerName } from "@/platform/fileManager";
import { formatBinding, hostBinding, isMacHost, shortcutLabel } from "@/platform/keymap";
import { relativePath, useProject } from "@/platform/project";
import { currentDetectedRoots, currentRoots } from "@/platform/projectRoots";
@@ -458,10 +459,7 @@ function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
}
export function revealLabel() {
const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
if (/Win/i.test(ua)) return "Explorer";
if (/Linux/i.test(ua)) return "Files";
return "Finder";
return fileManagerName();
}
/** What contributed menu groups see: the selected (non-placeholder) paths. */
+2 -3
Переглянути файл
@@ -1,10 +1,9 @@
/** Navigate › File Path (⌥⌘F12): the file and its folders, each revealed in the OS file manager. */
import { openPopup } from "@/editor/lsp/popupStore";
import { revealInFileManager } from "@/platform/fileManager";
import { fileManagerName, revealInFileManager } from "@/platform/fileManager";
import { notifications } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { nameOf, parentOf } from "./paths";
import { revealLabel } from "./contextMenu";
const DRIVE_ROOT = /^[A-Za-z]:\/?$/;
@@ -24,7 +23,7 @@ async function reveal(path: string) {
try {
await revealInFileManager(path);
} catch (e) {
const fileManager = revealLabel();
const fileManager = tx(fileManagerName());
notifications().notify({
level: "error",
title: tx`Cannot reveal in ${fileManager}`,
+3 -5
Переглянути файл
@@ -5,7 +5,7 @@
import { createElement, Fragment } from "react";
import { askUsagesDetected, fileUsages, viewUsages } from "@/editor/refactor";
import { executeAction, getAction } from "@/platform/actions";
import { fileManagerPath, revealInFileManager } from "@/platform/fileManager";
import { fileManagerName, fileManagerPath, revealInFileManager } from "@/platform/fileManager";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { ask, confirmChecked } from "@/workbench/messages";
import { osClipboard } from "./clipboard";
@@ -837,10 +837,8 @@ export async function revealInFinder(nodes: ProjectNode[] = selectedNodes()) {
try {
await revealInFileManager(nodes.map((n) => n.path));
} catch (e) {
// Same names as contextMenu.revealLabel (kept local: contextMenu imports
// this module, so importing it back would be a cycle).
const desktop = usePlatform.getState().os;
fail(`Cannot reveal in ${desktop === "windows" ? "Explorer" : desktop === "linux" ? "Files" : "Finder"}`, e);
const fileManager = tx(fileManagerName());
fail(tx`Cannot reveal in ${fileManager}`, e);
}
}
+34
Переглянути файл
@@ -1,6 +1,8 @@
import { afterEach, describe, expect, it } from "vitest";
import { executeAction, getAction, registerActions } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { _resetI18nForTests, setLocale } from "@/platform/i18n";
import { usePlatform } from "@/platform/platformInfo";
import { resolveMenuItems, useContextMenuStore, type MenuItem } from "@/ui";
import { provideEditorService, registerMenuGroup, type EditorService } from "@/workbench/contributions";
import { registerProjectActions, selectInTargets } from "./actions";
@@ -33,6 +35,38 @@ describe("Open in Terminal", () => {
});
describe("Select In (⌥F1)", () => {
it.each([
["macos", "Finder", "Reveal in Finder"],
["windows", "Explorer", "Show in Explorer"],
["linux", "Files", "Show in Files"],
])("uses the platform store for %s menus and action titles", (os, name, title) => {
const previous = usePlatform.getState().os;
try {
usePlatform.setState({ os });
disposers.push(registerProjectActions());
expect(revealLabel()).toBe(name);
expect(labels(selectInTargets("/p/a.ts"))).toContain(name);
expect(getAction("project.revealInFinder")?.title).toBe(title);
} finally {
usePlatform.setState({ os: previous });
}
});
it("retranslates the file manager action after registering in Chinese", async () => {
const previous = usePlatform.getState().os;
try {
usePlatform.setState({ os: "windows" });
await setLocale("zh");
disposers.push(registerProjectActions());
expect(getAction("project.revealInFinder")?.title).toBe("在资源管理器中显示");
await setLocale("en");
expect(getAction("project.revealInFinder")?.title).toBe("Show in Explorer");
} finally {
usePlatform.setState({ os: previous });
_resetI18nForTests();
}
});
it("lists the project view, contributed targets, Finder and the terminal", () => {
disposers.push(
registerMenuGroup({
-1
Переглянути файл
@@ -62,7 +62,6 @@ export const KIND_CATEGORIES: Record<string, string> = {
make: "Build Tools",
just: "Build Tools",
npm: "JavaScript",
vue: "JavaScript",
node: "JavaScript",
bun: "JavaScript",
deno: "JavaScript",
+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 ?? {}) };
},
};
+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 });
-1
Переглянути файл
@@ -382,7 +382,6 @@ describe("add service categories", () => {
it("categorizes every built-in kind; update the table when adding kinds", () => {
const expected: Record<string, string> = {
npm: "JavaScript",
vue: "JavaScript",
node: "JavaScript",
bun: "JavaScript",
deno: "JavaScript",
+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>
+6 -1
Переглянути файл
@@ -23,11 +23,13 @@ export function combinedParser(parsers: TestOutputParser[]): TestOutputParser {
};
}
export type Framework = "cargo" | "js" | "pytest" | "unittest" | "phpunit" | "go" | "jvm" | "ruby" | "auto";
export type Framework = "cargo" | "js" | "pytest" | "unittest" | "phpunit" | "go" | "jvm" | "ruby" | "dotnet" | "auto";
export function frameworkFor(config: Pick<RunConfig, "kind" | "command" | "args">): Framework {
const cmd = [config.command, ...config.args].join(" ");
switch (config.kind) {
case "dotnet-test":
return "dotnet";
case "cargo":
return "cargo";
case "npm":
@@ -53,6 +55,7 @@ export function frameworkFor(config: Pick<RunConfig, "kind" | "command" | "args"
case "rspec":
return "ruby";
}
if (/(^|[/\\])dotnet(?:\.exe)?$/i.test(config.command) && config.args[0] === "test") return "dotnet";
if (/\bcargo\b/.test(cmd)) return "cargo";
if (/\b(jest|vitest|npm|pnpm|yarn|bun|npx|deno)\b/.test(cmd)) return "js";
if (/\bpytest\b/.test(cmd)) return "pytest";
@@ -110,6 +113,8 @@ export function withTestReporting<T extends Pick<RunConfig, "kind" | "command" |
export function createTestParser(config: Pick<RunConfig, "kind" | "command" | "args">): TestOutputParser {
switch (frameworkFor(config)) {
case "dotnet":
return { feed: () => [] };
case "cargo":
return cargoParser();
case "js":
+27 -1
Переглянути файл
@@ -5,11 +5,12 @@
import { selectPluginTests } from "@/workbench/contributions";
import { phpunitArgs, phpunitFilter } from "./phpunit";
import type { RunConfig } from "@/platform/ipc";
import { formatArgs } from "../configs";
import { formatArgs, parseArgs } from "../configs";
import { appendScriptArgs } from "../scriptArgs";
import { djangoTestsOf } from "../djangoTypes";
import { goTestParts, withoutGoSelection } from "../goArguments";
import { frameworkFor } from "./index";
import { dotnetFilter } from "./dotnet";
import { nodeStatus, type TestNode, type TestResults } from "./results";
/** Paths of failed tests: failed leaves, plus failed suites without any failed children reported. */
@@ -67,6 +68,11 @@ function cargoArgs(base: string[], paths: string[][]): string[] | null {
return [...before, "--", ...rest, ...names, "--exact"];
}
function dotnetArgs(base: string[], filter: string): string[] {
const { before, after } = splitDashDash(base);
return [...dropFlag(before, ["--filter"]), "--filter", filter, ...(after ? ["--", ...after] : [])];
}
function jsArgs(config: RunConfig, paths: string[][]): string[] | null {
const base = config.args;
const files = unique(paths.map((p) => p[0]!).filter(Boolean));
@@ -202,6 +208,26 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string):
if (!paths.length) return null;
let args: string[] | null;
switch (frameworkFor(config)) {
case "dotnet": {
const filter = dotnetFilter(paths);
if (!filter) return null;
args = dotnetArgs(config.args, filter);
if (config.kind === "dotnet-test") {
return {
...config,
args,
name,
detected: true,
env: { ...config.env },
params: {
...config.params,
testMethods: JSON.stringify([...new Set(paths.map((p) => `${p[1]}.${p[2]}`))]),
programArgs: formatArgs(dotnetArgs(parseArgs(config.params?.programArgs || ""), filter)),
},
};
}
break;
}
case "cargo":
args = cargoArgs(config.args, paths);
break;
+88
Переглянути файл
@@ -514,6 +514,94 @@ describe("Settings dialog", () => {
expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsVmArgs", '"-Xmx2g"']]);
});
it("stages shared JDT LS in the project and writes it on Apply", async () => {
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).not.toBeChecked();
fireEvent.click(checkbox);
expect(checkbox).toBeChecked();
expect(settingsSet).not.toHaveBeenCalled();
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
expect(settingsSet.mock.calls).toEqual([["project", "languages.java.jdtlsShared", "true"]]);
});
it("keeps the global shared JDT LS preference separate from the project's override", async () => {
global = setAt(global, "languages.java.jdtlsShared", true);
current = setAt(global, "languages.java.jdtlsShared", false);
useProject.setState({ settings: current });
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
expect(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" })).not.toBeChecked();
fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).toBeChecked();
fireEvent.click(checkbox);
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsShared", "false"]]);
});
it("discards a shared JDT LS toggle on Cancel", async () => {
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
fireEvent.click(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" }));
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
expect(settingsSet).not.toHaveBeenCalled();
expect(current.languages?.java?.jdtlsShared).toBe(false);
});
it("disables shared JDT LS only in a native Workspace's project scope", async () => {
useProject.setState((s) => ({
project: { ...s.project!, workspace: { version: 1, name: "Workspace", projects: ["/p/member"] } },
}));
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
expect(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" })).toBeDisabled();
expect(within(dialog).getByText(/Open a workspace member as a project/)).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).toBeEnabled();
fireEvent.click(checkbox);
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsShared", "true"]]);
});
it("disables sharing for a Java language server target only in project scope", async () => {
current = setAt(current, "languageServerTargets", { java: { target: "docker:java", server: "jdtls" } });
useProject.setState({ settings: current });
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).toBeDisabled();
expect(within(dialog).getByText(/Select Local machine for the Java language server/)).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
expect(checkbox).toBeEnabled();
fireEvent.click(checkbox);
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsShared", "true"]]);
});
it.each([{ java: { target: "", server: "jdtls" } }, { python: { target: "docker:python" } }])(
"keeps sharing available when Java runs locally: %j",
async (targets) => {
current = setAt(current, "languageServerTargets", targets);
useProject.setState({ settings: current });
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
expect(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" })).toBeEnabled();
},
);
it("uses a staged project Java language server target before Apply", async () => {
const dialog = await openDialog("languages.java");
fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
expect(checkbox).toBeEnabled();
act(() => stage("languages.servers", "project", "languageServerTargets.java.target", "docker:java"));
expect(checkbox).toBeDisabled();
expect(settingsSet).not.toHaveBeenCalled();
});
it("Settings for New Projects edits the global layer on every page", async () => {
render(<SettingsDialog />);
await act(async () => {
+9
Переглянути файл
@@ -192,6 +192,15 @@ describe("languages settings", () => {
expect(folderRole(ps, "src")).toBeNull();
});
it("defaults shared JDT LS to off and accepts only boolean values", () => {
expect(DEFAULT_LANGUAGES.java.jdtlsShared).toBe(false);
expect(validateLanguages({}).java.jdtlsShared).toBe(false);
expect(validateSettings({ languages: { java: { jdtlsShared: true } } }).languages.java.jdtlsShared).toBe(true);
expect(validateLanguages({ java: { jdtlsShared: false } }).java.jdtlsShared).toBe(false);
for (const invalid of ["true", 1, null, []])
expect(validateLanguages({ java: { jdtlsShared: invalid } }).java.jdtlsShared).toBe(false);
});
it("defaults Java language level to SDK default and keeps only supported levels", () => {
expect(validateLanguages({}).java.languageLevel).toBe("");
expect(validateLanguages({ java: { languageLevel: "8" } }).java.languageLevel).toBe("8");
+21 -2
Переглянути файл
@@ -4,15 +4,16 @@
* use (applied by `ide-sdk` when language servers start and when run configurations load).
*/
import { LanguageServerTargetRows, LanguageServerTargetsPage } from "./LanguageServerTarget";
import { useProject } from "@/platform/project";
import { useRunTargets } from "@/platform/pluginRunTargets";
import { tx } from "@/platform/i18n";
import { useEffect, useId, useMemo, useState } from "react";
import { call, commands, type Sdk } from "@/platform/ipc";
import { call, commands, type LanguageServerTarget, type Sdk } from "@/platform/ipc";
import { IconButton, Input, type SelectOption, T } from "@/ui";
import { JAVA_LANGUAGE_LEVELS, PHP_LANGUAGE_LEVELS } from "@/platform/languageSettings";
import { GlobListEditor, Row, Section, Select, Toggle } from "../components/Form";
import { choosePath } from "./api";
import { useSetting } from "../components/context";
import { usePageContext, useSetting } from "../components/context";
import { SdkField, tildify, useDetected } from "./components";
import styles from "./Sdk.module.css";
@@ -387,6 +388,11 @@ export const JAVA_LEVEL_OPTIONS: SelectOption[] = JAVA_LANGUAGE_LEVELS.map((leve
);
export function JavaPage() {
const [shared, setShared] = useSetting<boolean>("languages.java.jdtlsShared");
const [serverTargets] = useSetting<Record<string, LanguageServerTarget>>("languageServerTargets", "project");
const { scope } = usePageContext();
const workspace = useProject((s) => !!s.project?.workspace);
const sharedDisabled = scope === "project" && (workspace || !!serverTargets?.java?.target);
const [vmArgs, setVmArgs] = useSetting<string>("languages.java.jdtlsVmArgs");
const [languageLevel, setLanguageLevel] = useSetting<string>("languages.java.languageLevel");
const id = useId();
@@ -417,6 +423,19 @@ export function JavaPage() {
</Row>
</Section>
<Section title="Language Server">
<Toggle
label="Share JDT LS across builds"
checked={shared}
onChange={setShared}
disabled={sharedDisabled}
hint={
sharedDisabled
? workspace
? "Shared JDT LS is available only in local ordinary project windows. Open a workspace member as a project to change this setting for it."
: "Shared JDT LS is available only in local ordinary project windows. Select Local machine for the Java language server to use it."
: "Uses one JDT LS process for linked builds in each local ordinary project window. Other project windows use separate processes."
}
/>
<SdkRow
k="languages.java.jdtlsJdk"
label="JDK"
+3
Переглянути файл
@@ -132,6 +132,9 @@ export const LANGUAGE_PAGES: PageSpec[] = [
"lombok",
"javaagent",
"eclipse jdt",
"shared jdtls",
"linked builds",
"server process",
],
component: JavaPage,
},
+2 -1
Переглянути файл
@@ -8,6 +8,7 @@ import { useEffect, useId, useState } from "react";
import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { WORKFLOW_LIMITS, type IssueLinkValid } from "@/platform/workflowSettings";
import { showInFileManagerLabel } from "@/platform/fileManager";
import { Button, Icon, Input, type SelectOption, T } from "@/ui";
import { Row, SettingSelect } from "../components/Form";
import { useSetting } from "../components/context";
@@ -222,7 +223,7 @@ function PushDialogRows() {
const PATCH_CREATED: SelectOption[] = [
{ value: "ask", label: "Ask" },
{ value: "no", label: "No" },
{ value: "reveal", label: "Show in Finder" },
{ value: "reveal", label: showInFileManagerLabel() },
];
const INCOMING: SelectOption[] = [
+62 -1
Переглянути файл
@@ -13,7 +13,7 @@ import {
} from "react";
import clsx from "clsx";
import { EditorView, keymap } from "@codemirror/view";
import { Prec, Text, type Extension } from "@codemirror/state";
import { Compartment, Prec, Text, type Extension } from "@codemirror/state";
import { history, historyKeymap } from "@codemirror/commands";
import {
MergeView,
@@ -27,12 +27,16 @@ import {
} from "@codemirror/merge";
import { attachDocument, embeddedEditorExtensions, type DocumentAttachment } from "@/editor/api";
import { setFindOpen } from "@/editor/core/cm/find";
import { softWrapActive } from "@/editor/core/cm/prefs";
import { FindPanel, searchAgain, seedFind, type FindTarget } from "@/editor/core/view/FindBar";
import { getContext, setContext } from "@/platform/context";
import { editorPrefs } from "@/platform/editorSettings";
import { call, commands } from "@/platform/ipc";
import { bindingsFor, normalizeBinding, shortcutLabel, strokeOf } from "@/platform/keymap";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { IconButton, Select, Spinner, T, showContextMenu } from "@/ui";
import { registerSoftWrapSurface } from "@/workbench/softWrap";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { changedLineGutters, diffOverview, diffWords, languageFor, viewerBase } from "./cm";
import { applyChunk, arrowControls, chunkAt, hoverRevert, revertUnifiedChunk } from "./diffControls";
@@ -365,6 +369,24 @@ export function DiffEditor({
const editableB = !binary && !!attached?.b && !attached.b.readOnly;
const ready = !!attached && !!statics && lang !== null && binary !== null;
// Soft wraps follow the editor's (Settings › Editor › General) unless toggled in the viewer settings.
const editorSoftWrap = useProject((s) => softWrapActive(s.settings?.editor?.softWrap, editorPrefs(s.settings), path));
const softWrap = opts.softWrap ?? editorSoftWrap;
const wrapSlot = useMemo(() => new Compartment(), []);
const softWrapRef = useRef(softWrap);
softWrapRef.current = softWrap;
const toggleSoftWrapRef = useRef(() => {});
toggleSoftWrapRef.current = () => setOpts({ softWrap: !softWrapRef.current });
useEffect(() => {
const host = hostRef.current;
if (!host || !ready || binary) return;
return registerSoftWrapSurface(host, {
enabled: () => softWrapRef.current,
toggle: () => toggleSoftWrapRef.current(),
});
}, [ready, binary]);
// Read when the views are built; toggling it later goes through `setSync`.
const syncScroll = useRef(opts.syncScroll);
syncScroll.current = opts.syncScroll;
@@ -419,6 +441,7 @@ export function DiffEditor({
const inclusion = includable ? inclusionGutter(path, textA) : [];
const side = (att: DocumentAttachment | null, editable: boolean, notes?: "left" | "right"): Extension[] => [
viewerBase({ readOnly: !editable, findBar: true }),
wrapSlot.of(softWrapRef.current ? EditorView.lineWrapping : []),
// Esc closes the find bar before it collapses the selection (a found match); open popups go first.
Prec.high(keymap.of([{ key: "Escape", run: () => findEscape.current() }])),
lang,
@@ -573,6 +596,7 @@ export function DiffEditor({
opts.collapse,
opts.ignore,
opts.highlight,
wrapSlot,
editableA,
editableB,
updateChunkInfo,
@@ -581,6 +605,37 @@ export function DiffEditor({
path,
]);
useEffect(() => {
const views = viewsRef.current;
if (!views) return;
// Aligned panes scroll in MergeView's outer element, which scrollSnapshot does not cover.
const outer = views.merge && !views.panes ? views.merge.dom : null;
const top = outer?.getBoundingClientRect().top;
const block = top == null ? null : views.b.lineBlockAtHeight(Math.max(0, top - views.b.documentTop));
const anchor =
block && top != null
? EditorView.scrollIntoView(block.from, { y: "start", yMargin: block.top + views.b.documentTop - top })
: null;
for (const view of [views.a, views.b]) {
if (view)
view.dispatch({
effects: [
wrapSlot.reconfigure(softWrap ? EditorView.lineWrapping : []),
...(outer ? (view === views.b && anchor ? [anchor] : []) : [view.scrollSnapshot()]),
],
});
}
// MergeView inserts alignment spacers on its next measure, after the panes have reflowed.
if (anchor) {
let frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => {
if (viewsRef.current === views) views.b.dispatch({ effects: anchor });
});
});
return () => cancelAnimationFrame(frame);
}
}, [softWrap, wrapSlot]);
useEffect(() => viewsRef.current?.panes?.setSync(opts.syncScroll), [opts.syncScroll]);
useEffect(
@@ -927,6 +982,12 @@ export function DiffEditor({
checked: opts.collapse,
run: () => setOpts({ collapse: !opts.collapse }),
},
{
id: "softWrap",
label: "Use Soft Wraps",
checked: softWrap,
run: () => setOpts({ softWrap: !softWrap }),
},
{
id: "sync",
label: "Synchronize Scrolling",
+12 -1
Переглянути файл
@@ -32,6 +32,7 @@ describe("diff options", () => {
collapse: false,
syncScroll: false,
alignChanges: false,
softWrap: true,
}),
).toEqual({
mode: "split",
@@ -40,8 +41,18 @@ describe("diff options", () => {
collapse: false,
syncScroll: false,
alignChanges: false,
softWrap: true,
});
expect(parseDiffOptions({ ignore: "bogus", highlight: 3, collapse: "x" })).toEqual(DEFAULT_DIFF_OPTIONS);
expect(parseDiffOptions({ ignore: "bogus", highlight: 3, collapse: "x", softWrap: "yes" })).toEqual(
DEFAULT_DIFF_OPTIONS,
);
// Options saved before soft wraps existed follow the editor's setting.
expect(parseDiffOptions({ mode: "unified" }).softWrap).toBeNull();
});
it.each([true, false, null])("round-trips the soft-wrap override %s", (softWrap) => {
const options = { ...DEFAULT_DIFF_OPTIONS, softWrap };
expect(parseDiffOptions(JSON.parse(JSON.stringify(options)))).toEqual(options);
});
it("ignore whitespace policies", () => {
+100
Переглянути файл
@@ -49,6 +49,7 @@ import { DiffEditor, mapLine } from "../DiffEditor";
import { DiffEditorTab } from "../diff-editor-tab";
import { diffInput, withChain, type DiffData } from "../diffInput";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import { useProject } from "@/platform/project";
/** Git Log opens a commit's file: both sides are revisions. */
const input = {
@@ -202,6 +203,105 @@ describe("Diff toolbar", () => {
localStorage.clear();
});
describe("soft wraps", () => {
const wrapped = () =>
[...document.querySelectorAll(".cm-editor .cm-content")].map((c) => c.classList.contains("cm-lineWrapping"));
const editorSettings = (softWrap: boolean, softWrapFiles?: string) =>
useProject.setState({
settings: { editor: { softWrap, ...(softWrapFiles ? { general: { softWrapFiles } } : {}) } } as never,
});
beforeEach(() => {
localStorage.clear();
texts.HEAD = "a\nb\n";
texts.abc123 = "a\nnew\nb\n";
});
it.each([
{ name: "the file matches Soft-wrap files", softWrap: true, files: "*.ts", mode: "split", expected: true },
{ name: "the file matches, unified viewer", softWrap: true, files: "*.ts", mode: "unified", expected: true },
{ name: "the file is not in Soft-wrap files", softWrap: true, files: undefined, mode: "split", expected: false },
{ name: "soft wraps are off in the editor", softWrap: false, files: "*.ts", mode: "split", expected: false },
] as const)("follow the editor's setting when $name", async ({ softWrap, files, mode, expected }) => {
editorSettings(softWrap, files);
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode }));
render(<DiffEditor input={input} />);
const panes = mode === "split" ? 2 : 1;
await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(panes));
expect(wrapped()).toEqual(Array(panes).fill(expected));
useProject.setState({ settings: null as never });
});
it.each([
{ mode: "split", alignChanges: false },
{ mode: "split", alignChanges: true },
{ mode: "unified", alignChanges: false },
])("reconfigures $mode (aligned: $alignChanges) without losing selection", async ({ mode, alignChanges }) => {
editorSettings(true, "*.ts");
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode, alignChanges }));
const mounted = render(
<>
<DiffEditor input={input} />
<ContextMenuHost />
</>,
);
const count = mode === "split" ? 2 : 1;
await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(count));
const views = [...document.querySelectorAll<HTMLElement>(".cm-editor")].map((dom) =>
EditorView.findFromDOM(dom)!,
);
for (const view of views) view.dispatch({ selection: { anchor: 1 } });
expect(wrapped()).toEqual(Array(count).fill(true));
// Settings changes still apply until an explicit viewer override is made.
editorSettings(false);
await waitFor(() => expect(wrapped()).toEqual(Array(count).fill(false)));
editorSettings(true, "*.ts");
await waitFor(() => expect(wrapped()).toEqual(Array(count).fill(true)));
fireEvent.click(screen.getByRole("button", { name: "Settings" }));
fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: "Use Soft Wraps" }));
await waitFor(() => expect(wrapped()).toEqual(Array(count).fill(false)));
expect(JSON.parse(localStorage.getItem("openidea.vcs.diffOptions")!).softWrap).toBe(false);
editorSettings(true, "*");
await waitFor(() => expect(wrapped()).toEqual(Array(count).fill(false)));
for (const view of views) {
expect(view.dom.isConnected).toBe(true);
expect(EditorView.findFromDOM(view.dom)).toBe(view);
expect(view.state.selection.main.head).toBe(1);
}
mounted.unmount();
render(<DiffEditor input={input} />);
await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(count));
expect(wrapped()).toEqual(Array(count).fill(false));
useProject.setState({ settings: null as never });
localStorage.clear();
});
it("turn on from the settings menu and stay on", async () => {
editorSettings(true);
const mounted = render(
<>
<DiffEditor input={input} />
<ContextMenuHost />
</>,
);
await waitFor(() => expect(document.querySelectorAll(".cm-mergeViewEditor .cm-editor")).toHaveLength(2));
expect(wrapped()).toEqual([false, false]);
(await screen.findByRole("button", { name: "Settings" })).click();
const item = await screen.findByRole("menuitemcheckbox", { name: "Use Soft Wraps" });
expect(item.getAttribute("aria-checked")).toBe("false");
item.click();
await waitFor(() => expect(wrapped()).toEqual([true, true]));
expect(JSON.parse(localStorage.getItem("openidea.vcs.diffOptions")!).softWrap).toBe(true);
// The next diff opens wrapped although the editor would not wrap this file.
mounted.unmount();
render(<DiffEditor input={input} />);
await waitFor(() => expect(document.querySelectorAll(".cm-mergeViewEditor .cm-editor")).toHaveLength(2));
expect(wrapped()).toEqual([true, true]);
useProject.setState({ settings: null as never });
localStorage.clear();
});
});
it("has no Jump to Source when the file is gone from the working tree", async () => {
probe.mockRejectedValue(new Error("no such file"));
render(<DiffEditor input={input} />);
+22
Переглянути файл
@@ -0,0 +1,22 @@
import { afterEach, expect, it } from "vitest";
import { _resetI18nForTests, setLocale, tx } from "@/platform/i18n";
import { usePlatform } from "@/platform/platformInfo";
import { patchSavedBody } from "../patches";
afterEach(() => _resetI18nForTests());
it.each([
["macos", "Patch file created successfully. Show it in Finder?", "补丁文件已创建。是否在访达中显示?"],
["windows", "Patch file created successfully. Show it in Explorer?", "补丁文件已创建。是否在资源管理器中显示?"],
["linux", "Patch file created successfully. Show it in Files?", "补丁文件已创建。是否在文件管理器中显示?"],
])("asks to show the saved patch in the %s file manager", async (os, english, chinese) => {
const previous = usePlatform.getState().os;
try {
usePlatform.setState({ os });
expect(patchSavedBody()).toBe(english);
await setLocale("zh");
expect(tx(patchSavedBody())).toBe(chinese);
} finally {
usePlatform.setState({ os: previous });
}
});
+4
Переглянути файл
@@ -26,6 +26,8 @@ export interface DiffViewOptions {
* keeps its own height and a curved divider joins the changes (IDEA's default).
*/
alignChanges: boolean;
/** Long lines wrap; null follows Settings › Editor › General › Soft-wrap files for the file. */
softWrap: boolean | null;
}
export const IGNORE_OPTIONS: ReadonlyArray<{ value: IgnorePolicy; label: string }> = [
@@ -48,6 +50,7 @@ export const DEFAULT_DIFF_OPTIONS: DiffViewOptions = {
collapse: true,
syncScroll: true,
alignChanges: false,
softWrap: null,
};
const KEY = "openidea.vcs.diffOptions";
@@ -66,6 +69,7 @@ export function parseDiffOptions(raw: unknown): DiffViewOptions {
collapse: typeof o.collapse === "boolean" ? o.collapse : d.collapse,
syncScroll: typeof o.syncScroll === "boolean" ? o.syncScroll : d.syncScroll,
alignChanges: typeof o.alignChanges === "boolean" ? o.alignChanges : d.alignChanges,
softWrap: typeof o.softWrap === "boolean" ? o.softWrap : d.softWrap,
};
}
+13 -3
Переглянути файл
@@ -2,7 +2,7 @@ import { commitRepo } from "./multiRoot";
/** Create Patch… (from local changes or commits) and Apply Patch… (file or clipboard, with a preview). */
import { useEffect, useState } from "react";
import type { Commit, FileStatus, PatchFile, PatchSource, ShelvedChangeList } from "@/bindings";
import { revealInFileManager } from "@/platform/fileManager";
import { fileManagerName, revealInFileManager } from "@/platform/fileManager";
import { call, commands } from "@/platform/ipc";
import { Button, Checkbox, Dialog, Icon, Input, List, Spinner, fileIconName, T } from "@/ui";
import { workflowSettings } from "@/platform/workflowSettings";
@@ -82,14 +82,24 @@ async function browseSave(current: string): Promise<string | null> {
}
}
/** Settings › Version Control › Confirmation › When patch is created: ask / no / show in Finder. */
/** Whole sentences let each locale translate the patch question. */
export function patchSavedBody(): string {
const name = fileManagerName();
return name === "Finder"
? "Patch file created successfully. Show it in Finder?"
: name === "Explorer"
? "Patch file created successfully. Show it in Explorer?"
: "Patch file created successfully. Show it in Files?";
}
/** Settings › Version Control › Confirmation › When patch is created: ask / no / show in the file manager. */
async function afterPatchSaved(path: string) {
const mode = workflowSettings().vcs.confirmation.onPatchCreated;
if (mode === "no") return;
if (mode === "ask") {
const r = await ask({
title: "Create Patch",
body: tx("Patch file created successfully. Show it in Finder?"),
body: tx(patchSavedBody()),
checkbox: "Don't ask again",
buttons: [{ id: "show", label: "Show", primary: true }],
});
+2 -2
Переглянути файл
@@ -1,7 +1,7 @@
import { useMemo, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
import clsx from "clsx";
import { call, commands, type RecentProject, type RecentProjectGroup } from "@/platform/ipc";
import { revealInFileManager } from "@/platform/fileManager";
import { revealInFileManager, showInFileManagerLabel } from "@/platform/fileManager";
import { parseRemoteLocation } from "@/platform/remote";
import {
HighlightedText,
@@ -137,7 +137,7 @@ export function recentMenu(project: RecentProject, onOpened?: () => void, onRemo
: { kind: "action", action: "file.openInNewWindow", arg: project.path, label: "Open in New Window" },
{
id: "reveal",
label: "Show in Finder",
label: showInFileManagerLabel(),
icon: "external-link",
run: () => void revealInFileManager(project.path).catch(() => undefined),
},
+22 -1
Переглянути файл
@@ -31,6 +31,7 @@ vi.mock("@tauri-apps/api/webview", () => ({
}));
import { registerActions } from "@/platform/actions";
import { usePlatform } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { ContextMenuHost } from "@/ui";
import { registerSettingsPage } from "@/workbench/contributions";
@@ -38,6 +39,7 @@ import { MessagesHost } from "@/workbench/messages";
import { projectInitials } from "@/workbench/projectColor";
import { handleListKey } from "./ProjectsPage";
import { customizeView } from "./CustomizePage";
import { recentMenu } from "./RecentList";
import { filterRecent, useRecent } from "./recent";
import { WelcomeView } from "./WelcomeView";
@@ -126,11 +128,30 @@ describe("Welcome › Projects", () => {
fireEvent.click(within(screen.getAllByRole("option")[0]!).getByRole("button", { name: "Project actions" }));
const menu = await screen.findByRole("menu");
expect(within(menu).getByText("Open in New Window")).toBeTruthy();
expect(within(menu).getByText("Show in Finder")).toBeTruthy();
expect(within(menu).getByText("Remove from Recent Projects…")).toBeTruthy();
dispose();
});
// Regression: the welcome menus are shared by the projects page and the two
// recent-project popups, and used to hardcode "Show in Finder" on every OS.
it("names the platform's file manager for the reveal action", () => {
const previous = usePlatform.getState().os;
const revealLabel = () => {
const items = recentMenu(p("acme-api", "/Users/me/repo/acme-api"));
return (items.find((i) => "id" in i && i.id === "reveal") as { label?: string } | undefined)?.label;
};
try {
usePlatform.setState({ os: "windows" });
expect(revealLabel()).toBe("Show in Explorer");
usePlatform.setState({ os: "linux" });
expect(revealLabel()).toBe("Show in Files");
usePlatform.setState({ os: "macos" });
expect(revealLabel()).toBe("Show in Finder");
} finally {
usePlatform.setState({ os: previous });
}
});
it("shows the landing page without recent projects", async () => {
recent = [];
await renderWelcome();
+18
Переглянути файл
@@ -0,0 +1,18 @@
import { expect, it } from "vitest";
import { isGradleBuildInput } from "./buildFiles";
it("recognizes applied scripts and Gradle properties for build and library refresh", () => {
for (const path of [
"/p/gradle/dependencies.gradle",
"/p/gradle/dependencies.gradle.kts",
"C:\\p\\gradle\\dependencies.gradle",
"/p/gradle.properties",
"/p/gradle/wrapper/gradle-wrapper.properties",
"/p/gradle/libs.versions.toml",
]) {
expect(isGradleBuildInput(path), path).toBe(true);
}
for (const path of ["/p/dependencies.gradle.bak", "/p/src/main.kt", "/p/README.md"]) {
expect(isGradleBuildInput(path), path).toBe(false);
}
});
+6
Переглянути файл
@@ -0,0 +1,6 @@
/** Gradle scripts and static inputs whose edits can change the build model or libraries. */
export function isGradleBuildInput(path: string): boolean {
return /(?:^|[\\/])(?:[^\\/]+\.gradle(?:\.kts)?|gradle\.properties|gradle-wrapper\.properties|[^\\/]+\.versions\.toml)$/.test(
path,
);
}
+91
Переглянути файл
@@ -0,0 +1,91 @@
import { describe, expect, it } from "vitest";
import { solutionPaths, jsonOutput, dotnetTestArgs, globalRunner, type DotnetProject } from "./dotnet";
import { dotnetTestType } from "@/features/run/dotnetTypes";
import { DotnetReports } from "@/features/run/testing/dotnet";
const project: DotnetProject = {
path: "C:/My Repo/Tests.csproj",
name: "Tests",
frameworks: ["net9.0"],
configurations: ["Debug", "Release"],
references: [],
packages: [],
test: true,
runner: "vstest",
adapter: "mstest",
trx: true,
};
describe(".NET workspace formats and runners", () => {
it("reads global.json comments and trailing commas without changing string values", () => {
expect(
globalRunner(
'{ // comment\n "test": { "runner": "Microsoft.Testing.Platform", }, "unused": "https://example.com/,}", }',
),
).toBe("mtp");
});
it("keeps SDK options before the legacy MTP argument boundary", () => {
const line = dotnetTestType.commandLine({
project: project.path,
runner: "mtp-legacy",
programArgs: "--no-build --filter Name=One",
testMethods: '["A.Tests.Two"]',
})!;
expect(line.args.indexOf("--no-build")).toBeLessThan(line.args.indexOf("--"));
expect(line.args.slice(line.args.indexOf("--") + 1)).toEqual(["--filter", "FullyQualifiedName=A.Tests.Two"]);
});
it("resolves solution projects, XML entities and external references", () => {
expect(
solutionPaths(
'Project("id") = "Tests", "..\\outside\\Tests.csproj", "id"\nProject("id") = "Folder", "Folder", "id"',
false,
"C:/repo",
),
).toEqual(["C:/outside/Tests.csproj"]);
expect(
solutionPaths(
'<Solution><Folder Name="src"><Project Path="A&amp;B/App.csproj" /></Folder></Solution>',
true,
"/repo",
),
).toEqual(["/repo/A&B/App.csproj"]);
});
it("reads JSON despite SDK banners", () =>
expect(jsonOutput('Welcome\n{"Properties":{"TargetFramework":"net9.0"}}\n')).toEqual({
Properties: { TargetFramework: "net9.0" },
}));
it.each(["vstest", "mtp", "mtp-legacy"] as const)(
"keeps %s discovery arguments in the correct command layer",
(runner) => {
const args = dotnetTestArgs({ ...project, runner }, "net9.0", ["--list-tests"], "Release");
expect(args.includes("--project")).toBe(runner === "mtp");
expect(args.includes("--")).toBe(runner === "mtp-legacy");
expect(args.at(-1)).toBe("--list-tests");
},
);
it.each(["mtp", "mtp-legacy"])("launches %s with TRX and adapter-native selectors", (runner) => {
const p = {
project: project.path,
framework: "net9.0",
runner,
adapter: "xunit",
testMethods: JSON.stringify(["A.Tests.One", "A.Tests.Two"]),
};
const line = dotnetTestType.commandLine(p)!;
expect(line.args).toContain("--filter-method");
expect(line.args).not.toContain("--filter");
const reporting = new DotnetReports().launch({
id: "test",
name: "test",
kind: "dotnet-test",
...line,
params: p,
cwd: null,
env: {},
isTest: true,
detected: true,
debugAdapter: null,
});
expect(reporting.args).toContain("--report-trx");
expect(reporting.args).not.toContain("--logger");
});
});
+285
Переглянути файл
@@ -0,0 +1,285 @@
import { Channel } from "@tauri-apps/api/core";
import { call, commands, ideEventsReady, onIdeEvent, type OutputChunk, type RunConfig, type RunId } from "./ipc";
import { dirname, useProject } from "./project";
import { tx } from "./i18n";
export type DotnetRunner = "vstest" | "mtp" | "mtp-legacy";
export interface DotnetProject {
path: string;
name: string;
frameworks: string[];
configurations: string[];
references: string[];
packages: Array<{ id: string; version: string }>;
test: boolean;
runner: DotnetRunner;
adapter: string;
trx: boolean;
platformVersion?: string;
}
export interface DotnetSolution {
path: string;
projects: string[];
}
export interface DotnetWorkspace {
projects: DotnetProject[];
solutions: DotnetSolution[];
errors?: string[];
}
export function dotnetConfig(args: string[], cwd: string): RunConfig {
return {
id: `dotnet-task:${crypto.randomUUID()}`,
name: `dotnet ${args[0]}`,
kind: "shell",
command: "dotnet",
args,
cwd,
env: { DOTNET_CLI_UI_LANGUAGE: "en" },
detected: true,
isTest: false,
debugAdapter: null,
emulateTerminal: false,
};
}
/** Uses the same trusted, remote-aware process host and cancellation as the Run window. */
export async function dotnet(args: string[], cwd: string, signal?: AbortSignal): Promise<string> {
signal?.throwIfAborted();
await ideEventsReady();
let id: RunId | undefined;
let output = "";
let overflow = false;
const exits = new Map<RunId, number | null>();
let finish!: (code: number | null) => void;
const exited = new Promise<number | null>((resolve) => {
finish = resolve;
});
const off = onIdeEvent("runExited", (event) => {
if (id === undefined) exits.set(event.run, event.code);
else if (event.run === id) finish(event.code);
});
const stop = () => {
if (id !== undefined) void call(commands.runStop(id)).catch(() => {});
};
const channel = new Channel<OutputChunk>();
channel.onmessage = (chunk) => {
if (output.length + chunk.text.length > 8_000_000) {
overflow = true;
stop();
} else output += chunk.text;
};
signal?.addEventListener("abort", stop);
try {
const info = await call(commands.runStart(dotnetConfig(args, cwd), channel));
id = info.id;
if (signal?.aborted || overflow) stop();
if (exits.has(id)) finish(exits.get(id)!);
const code = await exited;
signal?.throwIfAborted();
if (overflow) throw new Error(tx(".NET output exceeded the size limit"));
if (code !== 0) throw new Error(output.trim() || tx`dotnet exited with code ${code}`);
return output;
} finally {
off();
signal?.removeEventListener("abort", stop);
}
}
export function jsonOutput<T = Record<string, unknown>>(text: string): T {
const start = text.indexOf("{");
const end = text.lastIndexOf("}");
return JSON.parse(text.slice(start, end + 1));
}
function absolute(base: string, relative: string): string {
const path = relative.replace(/\\/g, "/");
if (/^(?:[A-Za-z]:\/|\/)/.test(path)) return path;
const parts = base.replace(/\\/g, "/").split("/");
for (const part of path.split("/")) {
if (part === "..") parts.pop();
else if (part && part !== ".") parts.push(part);
}
return parts.join("/");
}
export function solutionPaths(text: string, xml: boolean, dir: string): string[] {
const names = xml
? Array.from(new DOMParser().parseFromString(text, "application/xml").getElementsByTagName("Project")).map(
(p) => p.getAttribute("Path") || "",
)
: Array.from(text.matchAll(/^Project\([^\r\n]+?=\s*"[^"]*",\s*"([^"]+)"/gm), (m) => m[1]!);
return [...new Set(names.filter((p) => /\.(?:cs|fs|vb)proj$/i.test(p)).map((p) => absolute(dir, p)))];
}
export function globalRunner(text: string): DotnetRunner {
const json = JSON.parse(
text.replace(/"(?:\\.|[^"\\])*"|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*|,\s*(?=[}\]])/g, (token) =>
token.startsWith('"') ? token : "",
),
);
return json.test?.runner === "Microsoft.Testing.Platform" ? "mtp" : "vstest";
}
export async function runnerMode(dir: string): Promise<DotnetRunner> {
for (let current = dir; current;) {
try {
return globalRunner(await call(commands.fsReadText(`${current}/global.json`)));
} catch {
/* No global.json at this level. */
}
const parent = dirname(current);
if (parent === current) break;
current = parent;
}
return "vstest";
}
export async function evaluateProject(
path: string,
configuration = "Debug",
framework = "",
signal?: AbortSignal,
): Promise<DotnetProject> {
const data = jsonOutput<{ Properties: Record<string, string>; Items: Record<string, Array<Record<string, string>>> }>(
await dotnet(
[
"msbuild",
path,
"-nologo",
`-p:Configuration=${configuration}`,
...(framework ? [`-p:TargetFramework=${framework}`] : []),
"-getProperty:MSBuildProjectName,TargetFramework,TargetFrameworks,Configurations,IsTestProject,IsTestingPlatformApplication,TestingPlatformDotnetTestSupport,EnableMSTestRunner,ProjectAssetsFile",
"-getItem:ProjectReference,PackageReference",
],
dirname(path),
signal,
),
);
const p = data.Properties ?? {};
if (!framework && p.TargetFrameworks)
return evaluateProject(path, configuration, p.TargetFrameworks.split(";")[0], signal);
const packages = (data.Items?.PackageReference ?? []).map((x) => ({
id: String(x.Identity),
version: String(x.Version ?? ""),
}));
const mode = await runnerMode(dirname(path));
const mtp =
[p.IsTestingPlatformApplication, p.TestingPlatformDotnetTestSupport, p.EnableMSTestRunner].includes("true") ||
packages.some((x) => /xunit\.v3\.mtp/i.test(x.id));
let trx = packages.some((x) => /^Microsoft.Testing.Extensions.TrxReport$/i.test(x.id));
let platformVersion: string | undefined;
if (p.ProjectAssetsFile) {
try {
const assets = JSON.parse(await call(commands.fsReadText(p.ProjectAssetsFile)));
const libraries = Object.keys(assets.libraries ?? {});
trx ||= libraries.some((key) => /^Microsoft.Testing.Extensions.TrxReport\//i.test(key));
platformVersion = libraries.find((key) => /^Microsoft.Testing.Platform\//i.test(key))?.split("/")[1];
} catch {
/* Not restored yet. */
}
}
return {
path,
name: p.MSBuildProjectName || path.split("/").at(-1) || path,
frameworks: (p.TargetFrameworks || p.TargetFramework || "").split(";").filter(Boolean),
configurations: (p.Configurations || "Debug;Release").split(";"),
references: (data.Items?.ProjectReference ?? []).map((x) => absolute(dirname(path), x.Identity!)),
packages,
test:
p.IsTestProject === "true" ||
mtp ||
(p.IsTestProject !== "false" &&
packages.some((x) => /^(?:Microsoft.NET.Test.Sdk|MSTest|NUnit|xunit(?:\.v3(?:\.mtp-v[12])?)?)$/i.test(x.id))),
runner: mode === "mtp" ? mode : mtp ? "mtp-legacy" : "vstest",
adapter: packages.some((x) => /^xunit/i.test(x.id))
? "xunit"
: packages.some((x) => /^nunit/i.test(x.id))
? "nunit"
: "mstest",
trx,
platformVersion,
};
}
export async function dotnetWorkspace(root: string, signal?: AbortSignal): Promise<DotnetWorkspace> {
const paths = new Set<string>();
const solutions: DotnetSolution[] = [];
const queue = [root];
while (queue.length) {
signal?.throwIfAborted();
const dir = queue.shift()!;
for (const entry of await call(commands.fsReadDir(dir))) {
if (
entry.kind === "dir" &&
!entry.excluded &&
!/^(?:\.|bin$|obj$|node_modules$|target$|packages$)/.test(entry.name)
)
queue.push(entry.path);
else if (/\.(?:cs|fs|vb)proj$/i.test(entry.name)) paths.add(entry.path);
else if (/\.slnx?$/i.test(entry.name)) {
const projects = solutionPaths(
await call(commands.fsReadText(entry.path)),
entry.name.endsWith(".slnx"),
dirname(entry.path),
);
solutions.push({ path: entry.path, projects });
projects.forEach((p) => paths.add(p));
}
}
}
const projects: DotnetProject[] = [];
const errors: string[] = [];
for (const path of paths) {
try {
const project = await evaluateProject(path, "Debug", "", signal);
projects.push(project);
project.references.forEach((reference) => paths.add(reference));
} catch (e) {
signal?.throwIfAborted();
errors.push(`${path}: ${String(e)}`);
}
}
return { projects, solutions, errors };
}
export function dotnetTestArgs(
project: DotnetProject,
framework: string,
extra: string[] = [],
configuration = "Debug",
): string[] {
return [
"test",
...(project.runner === "mtp" ? ["--project", project.path] : [project.path]),
"--configuration",
configuration,
...(framework ? ["--framework", framework] : []),
...(project.runner === "mtp-legacy"
? [
"-p:TestingPlatformCaptureOutput=false",
"-p:TestingPlatformDotnetTestSupport=true",
...(extra.length ? ["--"] : []),
]
: []),
...extra,
];
}
export async function prepareDotnetTest(config: RunConfig): Promise<RunConfig> {
const root = useProject.getState().project?.root;
if (!root || !config.params?.project) return config;
let project = await evaluateProject(
absolute(root, config.params.project),
config.params.configuration,
config.params.framework,
);
if (project.runner !== "vstest" && !project.platformVersion) {
await dotnet(["restore", project.path], dirname(project.path));
project = await evaluateProject(project.path, config.params.configuration, config.params.framework);
}
return {
...config,
params: { ...config.params, runner: project.runner, adapter: project.adapter, trx: String(project.trx) },
};
}
+63
Переглянути файл
@@ -0,0 +1,63 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const host = vi.hoisted(() => ({
start: vi.fn(),
stop: vi.fn(),
listeners: new Set<(e: { run: number; code: number | null }) => void>(),
}));
vi.mock("@tauri-apps/api/core", () => ({
Channel: class {
onmessage = (_chunk: unknown) => {};
},
}));
vi.mock("./ipc", () => ({
commands: { runStart: host.start, runStop: host.stop },
call: <T>(promise: Promise<T>) => promise,
ideEventsReady: () => Promise.resolve(),
onIdeEvent: (_kind: string, fn: (e: { run: number; code: number | null }) => void) => {
host.listeners.add(fn);
return () => host.listeners.delete(fn);
},
}));
vi.mock("./project", () => ({
dirname: (p: string) => p.slice(0, p.lastIndexOf("/")),
useProject: { getState: () => ({ project: null }) },
}));
import { dotnet } from "./dotnet";
const exit = (run: number, code: number | null) => host.listeners.forEach((fn) => fn({ run, code }));
afterEach(() => {
host.start.mockReset();
host.stop.mockReset();
expect(host.listeners.size).toBe(0);
});
describe(".NET query lifecycle", () => {
it("captures a fast exit before runStart resolves, ignoring another run", async () => {
host.start.mockImplementation(async (_config, channel) => {
channel.onmessage({ text: '{"ok":true}' });
exit(99, 1);
exit(7, 0);
return { id: 7 };
});
expect(await dotnet(["msbuild"], "/repo")).toBe('{"ok":true}');
});
it("reports process failures and releases its event subscription", async () => {
host.start.mockImplementation(async () => {
exit(7, 1);
return { id: 7 };
});
await expect(dotnet(["msbuild"], "/repo")).rejects.toThrow("dotnet exited with code 1");
});
it("stops a process cancelled while runStart is pending", async () => {
const abort = new AbortController();
host.start.mockImplementation(async () => {
abort.abort();
return { id: 7 };
});
host.stop.mockImplementation(async (id) => exit(id, null));
await expect(dotnet(["msbuild"], "/repo", abort.signal)).rejects.toThrow();
expect(host.stop).toHaveBeenCalledWith(7);
});
it("releases its subscription if starting the process fails", async () => {
host.start.mockRejectedValue(new Error("SDK missing"));
await expect(dotnet(["msbuild"], "/repo")).rejects.toThrow("SDK missing");
});
});
+40 -2
Переглянути файл
@@ -1,8 +1,46 @@
import { describe, expect, it } from "vitest";
import { fileManagerPath } from "./fileManager";
import { afterEach, describe, expect, it } from "vitest";
import { fileManagerName, fileManagerPath, revealInFileManagerLabel, showInFileManagerLabel } from "./fileManager";
import { _resetI18nForTests, setLocale, tx } from "./i18n";
const raw = String.raw;
afterEach(() => _resetI18nForTests());
describe("file manager labels", () => {
it.each([
["macos", "Finder", "Reveal in Finder"],
["windows", "Explorer", "Show in Explorer"],
["linux", "Files", "Show in Files"],
["web", "Files", "Show in Files"],
])("names the %s file manager in submenus and project actions", (os, name, label) => {
expect(fileManagerName(os)).toBe(name);
expect(revealInFileManagerLabel(os)).toBe(label);
});
it("translates the project action on every desktop platform", async () => {
await setLocale("zh");
expect(tx(revealInFileManagerLabel("macos"))).toBe("在访达中显示");
expect(tx(revealInFileManagerLabel("windows"))).toBe("在资源管理器中显示");
expect(tx(revealInFileManagerLabel("linux"))).toBe("在文件管理器中显示");
});
});
describe("showInFileManagerLabel", () => {
it("names the file manager of the platform instead of always Finder", () => {
expect(showInFileManagerLabel("macos")).toBe("Show in Finder");
expect(showInFileManagerLabel("windows")).toBe("Show in Explorer");
expect(showInFileManagerLabel("linux")).toBe("Show in Files");
expect(showInFileManagerLabel("web")).toBe("Show in Files");
});
it("is translated into the platform's file manager, not Finder", async () => {
await setLocale("zh");
expect(tx(showInFileManagerLabel("macos"))).toBe("在访达中显示");
expect(tx(showInFileManagerLabel("windows"))).toBe("在资源管理器中显示");
expect(tx(showInFileManagerLabel("linux"))).toBe("在文件管理器中显示");
});
});
describe("fileManagerPath", () => {
it("converts verbatim UNC paths to the form Windows Shell accepts", () => {
expect(
+14
Переглянути файл
@@ -29,6 +29,20 @@ export function fileManagerPath(
return path;
}
/** English source text; callers and the action registry translate it. */
export function fileManagerName(os = usePlatform.getState().os): string {
return os === "macos" ? "Finder" : os === "windows" ? "Explorer" : "Files";
}
export function showInFileManagerLabel(os = usePlatform.getState().os): string {
return os === "macos" ? "Show in Finder" : os === "windows" ? "Show in Explorer" : "Show in Files";
}
/** The project action has historically used "Reveal" on macOS. */
export function revealInFileManagerLabel(os = usePlatform.getState().os): string {
return os === "macos" ? "Reveal in Finder" : showInFileManagerLabel(os);
}
/** Reveals files in Explorer, Finder or the Linux desktop's file manager. */
export async function revealInFileManager(paths: string | readonly string[]): Promise<void> {
if (!isTauri()) return;
+3
Переглянути файл
@@ -164,6 +164,7 @@ export interface LanguagesValid {
languageLevel: (typeof JAVA_LANGUAGE_LEVELS)[number];
jdtlsJdk: string;
jdtlsVmArgs: string;
jdtlsShared: boolean;
gradle: {
linkedProjects: string[] | null;
jvm: string;
@@ -243,6 +244,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
languageLevel: "",
jdtlsJdk: "",
jdtlsVmArgs: "",
jdtlsShared: false,
gradle: { linkedProjects: null, jvm: "", distribution: "wrapper", home: "", userHome: "", runUsing: "gradle" },
maven: {
runnerJre: "",
@@ -401,6 +403,7 @@ export function validateLanguages(raw: unknown): LanguagesValid {
languageLevel: oneOf(java.languageLevel, JAVA_LANGUAGE_LEVELS, d.java.languageLevel),
jdtlsJdk: text(java.jdtlsJdk, d.java.jdtlsJdk),
jdtlsVmArgs: text(java.jdtlsVmArgs, d.java.jdtlsVmArgs),
jdtlsShared: bool(java.jdtlsShared, d.java.jdtlsShared),
gradle: {
linkedProjects: Array.isArray(gradle.linkedProjects)
? gradle.linkedProjects.filter((p): p is string => typeof p === "string")
+2
Переглянути файл
@@ -97,6 +97,8 @@
"common.close": "Close",
"common.copied": "Copied",
"common.copy": "Copy",
"menu.activeEditor": "Active Editor",
"menu.editor.toggleSoftWrap": "Soft-Wrap",
"menu.app": "OpenIDEA",
"menu.app.about": "About OpenIDEA",
"menu.app.checkForUpdates": "Check for Updates…",
+55 -1
Переглянути файл
@@ -1,4 +1,26 @@
{
"Separate Procedures and Functions": "Separate Procedures and Functions",
"Shared JDT LS is available only in local ordinary project windows. Select Local machine for the Java language server to use it.": "Shared JDT LS is available only in local ordinary project windows. Select Local machine for the Java language server to use it.",
"Share JDT LS across builds": "Share JDT LS across builds",
"Shared JDT LS is available only in local ordinary project windows. Open a workspace member as a project to change this setting for it.": "Shared JDT LS is available only in local ordinary project windows. Open a workspace member as a project to change this setting for it.",
"Uses one JDT LS process for linked builds in each local ordinary project window. Other project windows use separate processes.": "Uses one JDT LS process for linked builds in each local ordinary project window. Other project windows use separate processes.",
"Finder": "Finder",
"Explorer": "Explorer",
"Files": "Files",
"Show in Finder": "Show in Finder",
"Show in Explorer": "Show in Explorer",
"Show in Files": "Show in Files",
"Reveal in Finder": "Reveal in Finder",
"Patch file created successfully. Show it in Finder?": "Patch file created successfully. Show it in Finder?",
"Patch file created successfully. Show it in Explorer?": "Patch file created successfully. Show it in Explorer?",
"Patch file created successfully. Show it in Files?": "Patch file created successfully. Show it in Files?",
"Cannot reveal in {fileManager}": "Cannot reveal in {fileManager}",
"Classes reloaded": "Classes reloaded",
"Active frames keep running the old code until they return. New calls use the reloaded code.": "Active frames keep running the old code until they return. New calls use the reloaded code.",
"The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.": "The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.",
"Reset Frame ({0})": "Reset Frame ({0})",
"Active Editor": "Active Editor",
"Soft-Wrap": "Soft-Wrap",
"The language server Java executable ({path}) cannot run on this machine. Choose a working JDK in {setting}, or set it to Auto.": "The language server Java executable ({path}) cannot run on this machine. Choose a working JDK in {setting}, or set it to Auto.",
"Input queue is full (4 MiB or 1024 writes); input was not sent.": "Input queue is full (4 MiB or 1024 writes); input was not sent.",
"Cannot write to terminal": "Cannot write to terminal",
@@ -602,6 +624,7 @@
"Database connection failed": "Database connection failed",
"Database service unavailable": "Database service unavailable",
"Trust this project to connect plugin data sources": "Trust this project to connect plugin data sources",
"Use Soft Wraps": "Use Soft Wraps",
"Language server runs on": "Language server runs on",
"Requires a container root for path mapping": "Requires a container root for path mapping",
"Target unavailable; language server runs on the host": "Target unavailable; language server runs on the host",
@@ -678,5 +701,36 @@
"Untagged Images": "Untagged Images",
"Show Processes": "Show Processes",
"Open Log in Editor": "Open Log in Editor",
"Open Container Log in Editor": "Open Container Log in Editor"
"Open Container Log in Editor": "Open Container Log in Editor",
"Could not read .NET test results: {error}\n": "Could not read .NET test results: {error}\n",
"Invalid TRX report": "Invalid TRX report",
".NET Workspace": ".NET Workspace",
"Reload .NET Workspace": "Reload .NET Workspace",
"Cancel .NET Operation": "Cancel .NET Operation",
"Select .NET Project": "Select .NET Project",
"Build .NET Project": "Build .NET Project",
"Restore .NET Project": "Restore .NET Project",
"Clean .NET Project": "Clean .NET Project",
"Refresh NuGet Packages": "Refresh NuGet Packages",
"Search NuGet Packages": "Search NuGet Packages",
"Change NuGet Package": "Change NuGet Package",
"Discover .NET Tests": "Discover .NET Tests",
"Run .NET Tests": "Run .NET Tests",
"Install TRX reporting": "Install TRX reporting",
"Project references": "Project references",
"NuGet packages": "NuGet packages",
"Refresh packages": "Refresh packages",
"Search NuGet packages": "Search NuGet packages",
"Install / Update": "Install / Update",
"Versions": "Versions",
"Transitive": "Transitive",
"Run all tests": "Run all tests",
"Install the TRX reporting extension to show MTP results in the test panel.": "Install the TRX reporting extension to show MTP results in the test panel.",
".NET output exceeded the size limit": ".NET output exceeded the size limit",
"Clean": "Clean",
"Run test": "Run test",
"Select a .NET project": "Select a .NET project",
"Project evaluation failed": "Project evaluation failed",
"dotnet exited with code {0}": "dotnet exited with code {0}",
"Microsoft.Testing.Platform was not found in the restored project.": "Microsoft.Testing.Platform was not found in the restored project."
}
+4 -1
Переглянути файл
@@ -2072,6 +2072,8 @@
"Show file extension": "Mostrar extensión de archivo",
"Show gutter icons": "Mostrar iconos del margen",
"Show hard wrap and visual guides (configured in Code Style options)": "Mostrar ajuste de línea fijo y guías visuales (configurado en las opciones de Estilo de código)",
"Show in Explorer": "Mostrar en el Explorador",
"Show in Files": "Mostrar en Archivos",
"Show in Finder": "Mostrar en Finder",
"Show in tool window": "Mostrar en ventana de herramientas",
"Show inlay Run to Cursor popup": "Mostrar ventana emergente integrada Ejecutar hasta el cursor",
@@ -4069,7 +4071,6 @@
"Include {path}": "Incluir {path}",
"Project View: {option}": "Vista del proyecto: {option}",
"Project View: Show {view}": "Vista del proyecto: Mostrar {view}",
"Reveal in {fileManager}": "Mostrar en {fileManager}",
"Unmark as {role}": "Desmarcar como {role}",
"Updated references in {count} file": "Referencias actualizadas en {count} archivo",
"Updated references in {count} files": "Referencias actualizadas en {count} archivos",
@@ -4779,6 +4780,8 @@
"Show Push dialog for Commit and Push": "Mostrar diálogo de Push al Confirmar y hacer Push",
"Show Push dialog only when committing to protected branches": "Mostrar diálogo de Push solo al confirmar en ramas protegidas",
"Combine stashes and shelves in one tab": "Combinar stashes y estantes en una sola pestaña",
"Patch file created successfully. Show it in Explorer?": "Archivo de parche creado correctamente. ¿Mostrarlo en el Explorador?",
"Patch file created successfully. Show it in Files?": "Archivo de parche creado correctamente. ¿Mostrarlo en Archivos?",
"Patch file created successfully. Show it in Finder?": "Archivo de parche creado correctamente. ¿Mostrarlo en Finder?",
"File names": "Nombres de archivo",
"Large files": "Archivos grandes",
+4 -1
Переглянути файл
@@ -1971,6 +1971,8 @@
"Show file extension": "Afficher l'extension du fichier",
"Show gutter icons": "Afficher les icônes de la gouttière",
"Show hard wrap and visual guides (configured in Code Style options)": "Afficher le retour à la ligne forcé et les repères visuels (configurés dans les options de style de code)",
"Show in Explorer": "Afficher dans l'Explorateur",
"Show in Files": "Afficher dans Fichiers",
"Show in Finder": "Afficher dans le Finder",
"Show in tool window": "Afficher dans la fenêtre d'outil",
"Show inlay Run to Cursor popup": "Afficher la fenêtre intégrée Exécuter jusqu'au curseur",
@@ -3926,7 +3928,6 @@
"Include {path}": "Inclure {path}",
"Project View: {option}": "Vue Projet : {option}",
"Project View: Show {view}": "Vue Projet : afficher {view}",
"Reveal in {fileManager}": "Afficher dans {fileManager}",
"Unmark as {role}": "Retirer le marquage {role}",
"Updated references in {count} file": "Références mises à jour dans {count} fichier",
"Updated references in {count} files": "Références mises à jour dans {count} fichiers",
@@ -4627,6 +4628,8 @@
"Show Push dialog for Commit and Push": "Afficher la boîte de dialogue Push pour Commit et push",
"Show Push dialog only when committing to protected branches": "Afficher la boîte de dialogue Push uniquement pour les commits sur des branches protégées",
"Combine stashes and shelves in one tab": "Regrouper les remises et les modifications mises de côté dans un seul onglet",
"Patch file created successfully. Show it in Explorer?": "Fichier de patch créé. L'afficher dans l'Explorateur ?",
"Patch file created successfully. Show it in Files?": "Fichier de patch créé. L'afficher dans Fichiers ?",
"Patch file created successfully. Show it in Finder?": "Fichier de patch créé. L'afficher dans le Finder ?",
"File names": "Noms de fichiers",
"Large files": "Fichiers volumineux",
+4 -1
Переглянути файл
@@ -2128,6 +2128,8 @@
"Show file extension": "파일 확장자 표시",
"Show gutter icons": "여백 아이콘 표시",
"Show hard wrap and visual guides (configured in Code Style options)": "하드 랩 및 시각적 가이드 표시(코드 스타일 옵션에서 구성)",
"Show in Explorer": "탐색기에서 표시",
"Show in Files": "파일에서 표시",
"Show in Finder": "Finder에서 표시",
"Show in tool window": "도구 창에 표시",
"Show inlay Run to Cursor popup": "인레이 “커서 위치까지 실행” 팝업 표시",
@@ -4135,7 +4137,6 @@
"Include {path}": "{path} 포함",
"Project View: {option}": "프로젝트 뷰: {option}",
"Project View: Show {view}": "프로젝트 뷰: {view} 표시",
"Reveal in {fileManager}": "{fileManager}에서 표시",
"Unmark as {role}": "{role} 표시 해제",
"Updated references in {count} file": "파일 {count}개의 참조를 업데이트했습니다",
"Updated references in {count} files": "파일 {count}개의 참조를 업데이트했습니다",
@@ -4852,6 +4853,8 @@
"Show Push dialog for Commit and Push": "커밋 및 푸시에 대한 푸시 대화 상자 표시",
"Show Push dialog only when committing to protected branches": "보호된 브랜치에 커밋할 때만 푸시 대화 상자 표시",
"Combine stashes and shelves in one tab": "스태시와 보류 항목을 하나의 탭에 결합",
"Patch file created successfully. Show it in Explorer?": "패치 파일이 생성되었습니다. 탐색기에서 표시하시겠습니까?",
"Patch file created successfully. Show it in Files?": "패치 파일이 생성되었습니다. 파일에서 표시하시겠습니까?",
"Patch file created successfully. Show it in Finder?": "패치 파일이 생성되었습니다. Finder에서 표시하시겠습니까?",
"File names": "파일 이름",
"Large files": "대용량 파일",
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more