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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 1df5bbdf32 perf(editor): keep recently used editor views across tab switches
Switching between file tabs destroyed the hidden tab's CodeMirror view and
built a new one on return: every switch re-ran the view's plugins, re-measured
the height map (the scrollbar jumped) and re-requested inlay hints, usages and
diagnostics, which popped in and shifted the text up to a second later.

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

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

The tabs perf scenario counts views rebuilt when switching back (budget 0).
2026-11-09 14:15:59 +08:00
166 змінених файлів з 572 додано та 11613 видалено

No files matched your search

+9 -641
Переглянути файл
@@ -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 rest = s;
while let Some(start) = rest.find(['"', '\'']) {
let Some((value, used)) = literal(&rest[start..]) else { break };
out.push(value);
rest = &rest[start + used..];
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());
}
}
out
}
@@ -565,12 +565,11 @@ 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 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)> {
/// Versions with interpolations, ranges and catalog aliases (`libs.x`) are skipped.
pub fn script_dependencies(text: &str) -> Vec<(String, String, String)> {
let text = strip_comments(text);
let mut out = Vec::new();
for line in text.lines().flat_map(statements) {
for line in text.lines().flat_map(|l| l.split(['{', ';'])) {
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) {
@@ -592,7 +591,6 @@ pub fn script_dependencies(text: &str, properties: &BTreeMap<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, '.' | '-' | '_' | '+'))
};
@@ -604,354 +602,11 @@ pub fn script_dependencies(text: &str, properties: &BTreeMap<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);
@@ -969,8 +624,6 @@ pub fn build_files(root: &Path, model: &GradleModel) -> Vec<PathBuf> {
catalogs.sort();
out.extend(catalogs);
}
out.sort();
out.dedup();
out
}
@@ -1155,7 +808,7 @@ dependencies {
classpath 'not:a:library'
}
"#;
let deps = script_dependencies(script, &BTreeMap::new());
let deps = script_dependencies(script);
let names: Vec<String> = deps.iter().map(|(g, a, v)| format!("{g}:{a}:{v}")).collect();
assert_eq!(
names,
@@ -1169,291 +822,6 @@ 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]
+6 -57
Переглянути файл
@@ -147,8 +147,7 @@ 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,
/// including the scripts they pull in with `apply from`.
/// `pom` imports and `system` scope; dependencies declared in the Gradle build scripts.
pub fn dependency_coordinates(root: &Path, model: &BuildModel) -> Vec<DependencyCoordinate> {
let mut out = Vec::new();
if let Some(m) = &model.maven {
@@ -178,26 +177,11 @@ pub fn dependency_coordinates(root: &Path, model: &BuildModel) -> Vec<Dependency
}
}
for g in &model.gradle {
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,
},
));
}
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 }
}));
}
}
out.sort();
@@ -328,39 +312,4 @@ 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,40 +818,6 @@ 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);
+3 -45
Переглянути файл
@@ -104,9 +104,6 @@ fn signal_group(child: &Child, signal: libc::c_int) {
#[cfg(windows)]
const TREE_EXIT_WAIT: Duration = Duration::from_secs(5);
#[cfg(windows)]
pub use windows_tree::ProcessTree;
/// `taskkill /T /F` from `pid`, then waits (up to [`TREE_EXIT_WAIT`]) until what the child
/// started is gone: termination is asynchronous, and until a process is gone the files it
/// holds open can't be opened or deleted. The child itself is left to its owner to reap.
@@ -139,48 +136,13 @@ mod windows_tree {
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS,
};
use windows_sys::Win32::System::Threading::{
GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
TerminateProcess, WaitForSingleObject,
GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, WaitForSingleObject,
};
/// Owned handles to a program and its current descendants, retained even if its launcher exits.
pub struct ProcessTree {
processes: Vec<OwnedHandle>,
}
impl ProcessTree {
pub fn capture(pid: u32) -> Self {
let Some(root) = open_with(pid, PROCESS_TERMINATE) else { return Self { processes: Vec::new() } };
let children = descendants_with(pid, PROCESS_TERMINATE);
Self { processes: std::iter::once(root).chain(children).collect() }
}
pub fn is_running(&self) -> bool {
self.processes.iter().any(|process| {
// SAFETY: an owned process handle opened with SYNCHRONIZE access.
unsafe {
WaitForSingleObject(process.as_raw_handle(), 0) == windows_sys::Win32::Foundation::WAIT_TIMEOUT
}
})
}
/// Requests termination children first; poll `is_running` until termination completes.
pub fn terminate(&self) {
for process in self.processes.iter().rev() {
// SAFETY: an owned process handle opened with TERMINATE access, never a reused pid.
unsafe { TerminateProcess(process.as_raw_handle(), 1) };
}
}
}
/// Every process `root` started, directly or not, opened so it can be waited for. A
/// parent's id is reused once it is gone, so a process counts only if it started after
/// its parent.
pub(super) fn descendants(root: u32) -> Vec<OwnedHandle> {
descendants_with(root, 0)
}
fn descendants_with(root: u32, access: u32) -> Vec<OwnedHandle> {
let Some(root_started) = open(root).as_ref().and_then(started) else { return Vec::new() };
let processes = processes();
let mut seen = HashSet::from([root]);
@@ -191,7 +153,7 @@ mod windows_tree {
if ppid != parent || !seen.insert(pid) {
continue;
}
let Some(handle) = open_with(pid, access) else { continue };
let Some(handle) = open(pid) else { continue };
if let Some(at) = started(&handle).filter(|&at| at >= parent_started) {
parents.push((pid, at));
found.push(handle);
@@ -231,12 +193,8 @@ mod windows_tree {
}
fn open(pid: u32) -> Option<OwnedHandle> {
open_with(pid, 0)
}
fn open_with(pid: u32, access: u32) -> Option<OwnedHandle> {
// SAFETY: plain call; a non-null result is a process handle owned by the caller.
let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION | access, 0, pid) };
let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
// SAFETY: as above.
(!handle.is_null()).then(|| unsafe { OwnedHandle::from_raw_handle(handle) })
}
-3
Переглянути файл
@@ -1130,9 +1130,6 @@ impl DebugManager {
/// Ends a session: `terminate` (when asked and supported) → `disconnect` → kill.
pub(crate) async fn shutdown(&self, s: &Arc<Session>, terminate: bool) {
if terminate {
crate::session::remember_debuggee(s).await;
}
// java-debug runs the program itself and pipes its stdout over DAP. A `disconnect`
// ends that DAP session, so every line the program writes while shutting down is lost.
// Ask the program to exit ourselves and keep the adapter attached until it has drained
+6 -34
Переглянути файл
@@ -59,8 +59,6 @@ pub(crate) struct Session {
/// adapter may report the launcher shell, whose child is the program).
#[cfg_attr(not(unix), allow(dead_code))]
pub stop_pids: parking_lot::Mutex<Vec<i32>>,
#[cfg(windows)]
pub stop_tree: Mutex<Option<ide_core::process::ProcessTree>>,
/// Breakpoints replaced for run to cursor / force stepping, restored on the next stop.
pub pending_restore: Mutex<PendingRestore>,
/// Adapter breakpoint id → (file, index in the stored list).
@@ -113,8 +111,6 @@ impl Session {
stop_force: AtomicBool::new(false),
debuggee_pid: AtomicI64::new(0),
stop_pids: parking_lot::Mutex::new(Vec::new()),
#[cfg(windows)]
stop_tree: Mutex::new(None),
pending_restore: Mutex::default(),
breakpoint_ids: Mutex::new(HashMap::new()),
resolved_paths: Mutex::new(HashMap::new()),
@@ -302,21 +298,6 @@ impl Session {
/// How long Stop waits for a launched program to exit before reporting the session ended.
pub(crate) const DEBUGGEE_EXIT_WAIT: Duration = Duration::from_secs(10);
pub(crate) async fn remember_debuggee(s: &Arc<Session>) {
#[cfg(windows)]
{
let Ok(pid) = u32::try_from(s.debuggee_pid.load(Ordering::Acquire)) else { return };
if s.request != "launch" || pid == 0 || s.stop_tree.lock().is_some() {
return;
}
if let Ok(tree) = tokio::task::spawn_blocking(move || ide_core::process::ProcessTree::capture(pid)).await {
s.stop_tree.lock().get_or_insert(tree);
}
}
#[cfg(not(windows))]
let _ = s;
}
/// The program and everything it started: an adapter may report the launcher shell, whose
/// child is the debugged program, so stopping only the reported pid leaves the program alive.
#[cfg(unix)]
@@ -368,10 +349,12 @@ pub(crate) fn signal_debuggee(s: &Arc<Session>, force: bool) {
}
#[cfg(windows)]
{
// Console programs have no external graceful signal; the adapter gets its chance first.
if force && let Some(tree) = s.stop_tree.lock().as_ref() {
tree.terminate();
let mut cmd = std::process::Command::new("taskkill");
cmd.args(["/PID", &pid.to_string(), "/T"]);
if force {
cmd.arg("/F");
}
let _ = cmd.status();
}
#[cfg(not(any(unix, windows)))]
let _ = (pid, force);
@@ -408,18 +391,7 @@ pub(crate) async fn wait_for_debuggee(s: &Arc<Session>, terminate: bool) {
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
#[cfg(windows)]
{
remember_debuggee(s).await;
let deadline = std::time::Instant::now() + DEBUGGEE_EXIT_WAIT;
while s.stop_tree.lock().as_ref().is_some_and(|tree| tree.is_running()) {
if s.stop_force.swap(false, Ordering::AcqRel) || std::time::Instant::now() >= deadline {
signal_debuggee(s, true);
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
#[cfg(not(any(unix, windows)))]
#[cfg(not(unix))]
{
let _ = pid;
}
-87
Переглянути файл
@@ -14,93 +14,6 @@ use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
type Log = Arc<Mutex<Vec<Value>>>;
#[cfg(windows)]
#[test]
#[ignore = "child process for Windows stop tests"]
fn windows_debuggee_process() {
if std::env::var_os("OPENIDEA_TEST_DEBUGGEE").is_none() {
return;
}
if std::env::var("OPENIDEA_TEST_DEBUGGEE").unwrap() == "wrapper" {
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
let mut child = ide_core::process::prepare(&mut command)
.args(["--exact", "tests::windows_debuggee_process", "--ignored", "--nocapture"])
.env("OPENIDEA_TEST_DEBUGGEE", "leaf")
.spawn()
.unwrap();
let _ = child.wait();
return;
}
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
println!("LISTENING {}", listener.local_addr().unwrap().port());
std::thread::sleep(Duration::from_secs(60));
}
#[cfg(windows)]
#[tokio::test]
async fn windows_stop_releases_the_debuggees_port_before_returning() {
use std::io::BufRead;
use std::sync::atomic::Ordering;
struct Child(std::process::Child, Option<ide_core::process::ProcessTree>);
impl Drop for Child {
fn drop(&mut self) {
if let Some(tree) = &self.1 {
tree.terminate();
}
let _ = self.0.kill();
let _ = self.0.wait();
}
}
for (second_stop, wrapper, supports_terminate) in
[(false, false, false), (true, false, false), (true, true, false), (true, true, true)]
{
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
ide_core::process::prepare(&mut command)
.args(["--exact", "tests::windows_debuggee_process", "--ignored", "--nocapture"])
.env("OPENIDEA_TEST_DEBUGGEE", if wrapper { "wrapper" } else { "leaf" })
.stdout(std::process::Stdio::piped());
let mut child = Child(command.spawn().unwrap(), None);
let port: u16 = std::io::BufReader::new(child.0.stdout.take().unwrap())
.lines()
.map(Result::unwrap)
.find_map(|line| line.split("LISTENING ").nth(1).and_then(|p| p.parse().ok()))
.unwrap();
let pid = child.0.id();
child.1 = Some(ide_core::process::ProcessTree::capture(pid));
let h = harness(Script { debuggee_pid: Some(pid), supports_terminate, ..Default::default() });
let id = h.start(config()).await.unwrap();
let session = h.manager.session(id).unwrap();
while session.debuggee_pid.load(Ordering::Acquire) != i64::from(pid) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
let stop = tokio::spawn({
let manager = h.manager.clone();
async move { manager.stop(id).await }
});
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while session.stop_tree.lock().is_none() && !stop.is_finished() {
assert!(std::time::Instant::now() < deadline, "Stop did not capture the program tree");
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(!stop.is_finished(), "Stop must wait for the live program");
if wrapper {
assert!(session.stop_tree.lock().is_some());
child.0.kill().unwrap();
child.0.wait().unwrap();
assert!(std::net::TcpListener::bind(("127.0.0.1", port)).is_err(), "the child still owns its port");
}
if second_stop {
h.manager.stop(id).await.unwrap();
}
let limit = if second_stop { 10 } else { 25 };
tokio::time::timeout(Duration::from_secs(limit), stop).await.unwrap().unwrap().unwrap();
assert!(child.0.try_wait().unwrap().is_some(), "Stop returned with the program alive");
let _listener = std::net::TcpListener::bind(("127.0.0.1", port)).expect("Stop returned with its port occupied");
}
}
#[derive(Clone)]
struct Script {
/// Send a `runInTerminal` reverse request when `launch` arrives.
-26
Переглянути файл
@@ -253,32 +253,6 @@ pub fn inspect(ep: &DockerEndpoint, object: DockerObject, id: &str) -> IdeResult
}
}
fn check_id(id: &str) -> IdeResult<&str> {
let id = id.trim();
if id.is_empty() || id.starts_with('-') { Err(IdeError::invalid("invalid Docker identifier")) } else { Ok(id) }
}
/// `docker image history --no-trunc --format '{{json .}}'` of one image.
pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImageLayer>> {
let id = check_id(id)?;
let out = run(ep, &["image", "history", "--no-trunc", "--format", "{{json .}}", id], QUICK)?;
Ok(parse_image_history(&out))
}
/// `docker top <id>` of a running container.
pub fn container_top(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerProcessList> {
let id = check_id(id)?;
let out = run(ep, &["top", id], QUICK)?;
Ok(parse_container_top(&out))
}
/// `docker stats --no-stream --no-trunc --format '{{json .}}' <id>` of a running container.
pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContainerStats> {
let id = check_id(id)?;
let out = run(ep, &["stats", "--no-stream", "--no-trunc", "--format", "{{json .}}", id], QUICK)?;
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
}
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
/// until it ends or `cancel` fires.
pub fn logs(
+19 -181
Переглянути файл
@@ -41,15 +41,6 @@ pub struct DockerContainer {
pub compose_working_dir: Option<String>,
/// `com.docker.compose.project.config_files` label (comma-separated in docker).
pub compose_files: Vec<String>,
/// Mounted volume names or host paths reported by `docker ps` (`Mounts`).
#[serde(default)]
pub mounts: Vec<String>,
/// Connected network names reported by `docker ps` (`Networks`).
#[serde(default)]
pub networks: Vec<String>,
/// User and tool labels assigned to the container.
#[serde(default)]
pub labels: BTreeMap<String, String>,
}
impl DockerContainer {
@@ -89,10 +80,6 @@ pub struct DockerVolume {
pub driver: String,
pub mountpoint: String,
pub compose_project: Option<String>,
#[serde(default)]
pub scope: String,
#[serde(default)]
pub labels: BTreeMap<String, String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -103,46 +90,6 @@ pub struct DockerNetwork {
pub driver: String,
pub scope: String,
pub compose_project: Option<String>,
#[serde(default)]
pub created_at: String,
#[serde(default)]
pub ipv6: bool,
#[serde(default)]
pub internal: bool,
#[serde(default)]
pub labels: BTreeMap<String, String>,
}
/// One layer in `docker image history --no-trunc --format '{{json .}}'`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerImageLayer {
pub id: String,
pub created_by: String,
pub size: String,
pub created_since: String,
pub created_at: String,
pub comment: String,
}
/// Process table returned by `docker top <container>`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerProcessList {
pub titles: Vec<String>,
pub processes: Vec<Vec<String>>,
}
/// Live resource metrics returned by `docker stats --no-stream --no-trunc --format '{{json .}}'`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerContainerStats {
pub cpu_perc: String,
pub mem_usage: String,
pub mem_perc: String,
pub net_io: String,
pub block_io: String,
pub pids: String,
}
/// Everything the Services tree shows, fetched in one go.
@@ -239,20 +186,17 @@ struct RawContainer {
ports: String,
created_at: String,
labels: String,
mounts: String,
networks: String,
}
fn split_csv(raw: &str) -> Vec<String> {
raw.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
}
/// `docker ps -a --no-trunc --format '{{json .}}'`.
pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
let mut out: Vec<DockerContainer> = lines::<RawContainer>(text)
.map(|r| {
let all_labels = parse_labels(&r.labels);
let files = all_labels.get(COMPOSE_FILES).map(|f| split_csv(f)).unwrap_or_default();
let mut labels = parse_labels(&r.labels);
let files = labels
.remove(COMPOSE_FILES)
.map(|f| f.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect())
.unwrap_or_default();
// Older docker versions derive `State` from nothing: fall back on the status text.
let state = if r.state.is_empty() {
if r.status.starts_with("Up") { "running".into() } else { "exited".into() }
@@ -268,13 +212,10 @@ pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
status: r.status,
ports: r.ports,
created_at: r.created_at,
compose_project: all_labels.get(COMPOSE_PROJECT).filter(|s| !s.is_empty()).cloned(),
compose_service: all_labels.get(COMPOSE_SERVICE).filter(|s| !s.is_empty()).cloned(),
compose_working_dir: all_labels.get(COMPOSE_DIR).filter(|s| !s.is_empty()).cloned(),
compose_project: labels.remove(COMPOSE_PROJECT).filter(|s| !s.is_empty()),
compose_service: labels.remove(COMPOSE_SERVICE).filter(|s| !s.is_empty()),
compose_working_dir: labels.remove(COMPOSE_DIR).filter(|s| !s.is_empty()),
compose_files: files,
mounts: split_csv(&r.mounts),
networks: split_csv(&r.networks),
labels: all_labels,
}
})
.collect();
@@ -317,23 +258,17 @@ struct RawVolume {
name: String,
driver: String,
mountpoint: String,
scope: String,
labels: String,
}
/// `docker volume ls --format '{{json .}}'`.
pub fn parse_volumes(text: &str) -> Vec<DockerVolume> {
let mut out: Vec<DockerVolume> = lines::<RawVolume>(text)
.map(|r| {
let labels = parse_labels(&r.labels);
DockerVolume {
compose_project: labels.get(COMPOSE_PROJECT).filter(|s| !s.is_empty()).cloned(),
name: r.name,
driver: r.driver,
mountpoint: r.mountpoint,
scope: r.scope,
labels,
}
.map(|r| DockerVolume {
compose_project: parse_labels(&r.labels).remove(COMPOSE_PROJECT).filter(|s| !s.is_empty()),
name: r.name,
driver: r.driver,
mountpoint: r.mountpoint,
})
.collect();
out.sort_by(|a, b| a.name.cmp(&b.name));
@@ -348,121 +283,24 @@ struct RawNetwork {
name: String,
driver: String,
scope: String,
created_at: String,
#[serde(rename = "IPv6")]
ipv6: String,
internal: String,
labels: String,
}
/// `docker network ls --no-trunc --format '{{json .}}'`.
pub fn parse_networks(text: &str) -> Vec<DockerNetwork> {
let mut out: Vec<DockerNetwork> = lines::<RawNetwork>(text)
.map(|r| {
let labels = parse_labels(&r.labels);
DockerNetwork {
compose_project: labels.get(COMPOSE_PROJECT).filter(|s| !s.is_empty()).cloned(),
id: r.id,
name: r.name,
driver: r.driver,
scope: r.scope,
created_at: r.created_at,
ipv6: r.ipv6.eq_ignore_ascii_case("true"),
internal: r.internal.eq_ignore_ascii_case("true"),
labels,
}
.map(|r| DockerNetwork {
compose_project: parse_labels(&r.labels).remove(COMPOSE_PROJECT).filter(|s| !s.is_empty()),
id: r.id,
name: r.name,
driver: r.driver,
scope: r.scope,
})
.collect();
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawImageLayer {
#[serde(rename = "ID")]
id: String,
created_by: String,
size: String,
created_since: String,
created_at: String,
comment: String,
}
/// `docker image history --no-trunc --format '{{json .}}'`.
pub fn parse_image_history(text: &str) -> Vec<DockerImageLayer> {
lines::<RawImageLayer>(text)
.map(|r| DockerImageLayer {
id: r.id,
created_by: r.created_by,
size: r.size,
created_since: r.created_since,
created_at: r.created_at,
comment: r.comment,
})
.collect()
}
/// `docker top <container>` tabular output.
pub fn parse_container_top(text: &str) -> DockerProcessList {
let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
let Some(header) = lines.next() else {
return DockerProcessList::default();
};
let titles: Vec<String> = header.split_whitespace().map(str::to_owned).collect();
if titles.is_empty() {
return DockerProcessList::default();
}
let cols = titles.len();
let processes = lines
.map(|line| {
let mut row = Vec::with_capacity(cols);
let mut rest = line.trim_start();
for _ in 0..cols.saturating_sub(1) {
match rest.split_once(char::is_whitespace) {
Some((field, tail)) => {
row.push(field.to_owned());
rest = tail.trim_start();
}
None => break,
}
}
if !rest.is_empty() || row.len() < cols {
row.push(rest.to_owned());
}
row
})
.collect();
DockerProcessList { titles, processes }
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawStats {
#[serde(rename = "CPUPerc")]
cpu_perc: String,
mem_usage: String,
mem_perc: String,
#[serde(rename = "NetIO")]
net_io: String,
#[serde(rename = "BlockIO")]
block_io: String,
#[serde(rename = "PIDs")]
pids: String,
}
/// `docker stats --no-stream --no-trunc --format '{{json .}}'`.
pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
lines::<RawStats>(text).next().map(|r| DockerContainerStats {
cpu_perc: r.cpu_perc,
mem_usage: r.mem_usage,
mem_perc: r.mem_perc,
net_io: r.net_io,
block_io: r.block_io,
pids: r.pids,
})
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct RawVersion {
+1 -44
Переглянути файл
@@ -1,9 +1,6 @@
//! Parsing of recorded `docker … --format '{{json .}}'` output.
use ide_docker::{
parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images, parse_networks,
parse_volumes,
};
use ide_docker::{parse_containers, parse_images, parse_networks, parse_volumes};
const PS: &str = include_str!("fixtures/ps.jsonl");
const IMAGES: &str = include_str!("fixtures/images.jsonl");
@@ -25,16 +22,11 @@ fn containers_with_compose_labels() {
assert_eq!(db.compose_working_dir.as_deref(), Some("/work/shop"));
assert_eq!(db.compose_files, ["/work/shop/compose.yaml", "/work/shop/compose.override.yaml"]);
assert_eq!(db.ports, "0.0.0.0:5432->5432/tcp");
assert_eq!(db.mounts, ["shop_pgdata"]);
assert_eq!(db.networks, ["shop_default"]);
assert_eq!(db.labels.get("com.docker.compose.project").map(String::as_str), Some("shop"));
let web = &c[1];
assert_eq!(web.name, "web", "leading slash of legacy names is dropped");
assert!(!web.running());
assert_eq!(web.compose_project, None);
assert!(web.mounts.is_empty());
assert_eq!(web.networks, ["bridge"]);
}
#[test]
@@ -52,44 +44,9 @@ fn volumes_and_networks() {
assert_eq!(v.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["0a1b", "shop_pgdata"]);
assert_eq!(v[1].compose_project.as_deref(), Some("shop"));
assert_eq!(v[1].mountpoint, "/var/lib/docker/volumes/shop_pgdata/_data");
assert_eq!(v[1].scope, "local");
assert_eq!(v[1].labels.get("com.docker.compose.volume").map(String::as_str), Some("pgdata"));
let n = parse_networks(NETWORKS);
assert_eq!(n.iter().map(|n| n.name.as_str()).collect::<Vec<_>>(), ["bridge", "host", "shop_default"]);
assert_eq!(n[2].compose_project.as_deref(), Some("shop"));
assert_eq!(n[1].driver, "host");
assert!(!n[2].ipv6);
assert!(!n[2].internal);
assert_eq!(n[2].labels.get("com.docker.compose.network").map(String::as_str), Some("default"));
}
#[test]
fn image_history_top_and_stats() {
let history = [
r#"{"Comment":"buildkit.dockerfile.v0","CreatedAt":"2026-10-01 09:00:00 +0000 UTC","CreatedBy":"CMD [\"postgres\"]","CreatedSince":"5 weeks ago","ID":"sha256:1234567890ab","Size":"0B"}"#,
r#"{"Comment":"","CreatedAt":"2026-10-01 08:59:00 +0000 UTC","CreatedBy":"/bin/sh -c #(nop) COPY file:abc in /usr/local/bin/ ","CreatedSince":"5 weeks ago","ID":"<missing>","Size":"42.5MB"}"#,
]
.join("\n");
let layers = parse_image_history(&history);
assert_eq!(layers.len(), 2);
assert_eq!(layers[0].created_by, "CMD [\"postgres\"]");
assert_eq!(layers[1].size, "42.5MB");
let top = "UID PID PPID C STIME TTY TIME CMD\nroot 1234 1200 0 09:12 ? 00:00:01 postgres -c config_file=/etc/postgresql.conf\n";
let parsed_top = parse_container_top(top);
assert_eq!(parsed_top.titles, ["UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"]);
assert_eq!(parsed_top.processes.len(), 1);
assert_eq!(parsed_top.processes[0][0], "root");
assert_eq!(parsed_top.processes[0][1], "1234");
assert_eq!(parsed_top.processes[0][7], "postgres -c config_file=/etc/postgresql.conf");
let stats_line = r#"{"BlockIO":"1.2MB / 0B","CPUPerc":"1.25%","Container":"shop-db-1","ID":"4f2b8c1d9e0a","MemPerc":"2.50%","MemUsage":"50MiB / 2GiB","Name":"shop-db-1","NetIO":"12kB / 8kB","PIDs":"14"}"#;
let stats = parse_container_stats(stats_line).expect("stats parsed");
assert_eq!(stats.cpu_perc, "1.25%");
assert_eq!(stats.mem_usage, "50MiB / 2GiB");
assert_eq!(stats.mem_perc, "2.50%");
assert_eq!(stats.net_io, "12kB / 8kB");
assert_eq!(stats.block_io, "1.2MB / 0B");
assert_eq!(stats.pids, "14");
}
+2 -2
Переглянути файл
@@ -592,8 +592,8 @@ pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::
/// References of the symbol at `pos`. `project_wide` also searches project files
/// outside the language server's analysis scope; bulk scans over many symbols
/// leave it off. Java: without `libraries`, the dependencies and the JDK are not
/// searched; with it and `project_wide`, those found in the sources arrive on `on_partial` before
/// leave it off. Java, `project_wide`: without `libraries`, the dependencies and the JDK
/// are not searched; with it, those found in the sources arrive on `on_partial` before
/// the slower search for the rest, and the result has them all. Cancel with
/// `cancel_request(request)`.
#[allow(clippy::too_many_arguments)]
+6 -7
Переглянути файл
@@ -218,13 +218,12 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
.filter(|s| !s.is_empty())
.or_else(|| artifacts.first().map(|a| &a.id))
.ok_or_else(|| IdeError::invalid("Choose a WAR artifact"))?;
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
// "Build before launch" is skipped when the built WAR is already newer than the
// module's sources, so a repeated run does not rebuild (IDEA's up-to-date check).
if ide_run::tomcat::artifact_is_current(&project.root, &base, &config) {
return Ok(None);
}
let mut plan = ide_build::web::build(&project.root, &model, id, &base)?;
let mut plan = ide_build::web::build(
&project.root,
&model,
id,
&ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?,
)?;
plan.env.extend(config.env.clone());
let mut build = RunConfig {
id: format!("tomcat-build:{}", config.id),
+6 -7
Переглянути файл
@@ -1069,13 +1069,12 @@ impl Project {
let Some(root) = root else {
return ide_lsp::CandidateFiles::default();
};
let mut exclude = self.search_excludes();
// Directories the server analyses fully: their files are never read.
exclude.extend(q.skip.iter().filter_map(|dir| {
let rel = dir.strip_prefix(&root).ok()?.to_str()?.replace('\\', "/");
(!rel.is_empty() && !rel.contains(['*', '?', '[', ']', '{', '}', '!', ','])).then(|| format!("{rel}/**"))
}));
let query = ide_search::WordQuery { word: q.word.clone(), dir: q.root.clone(), exclude, limit: q.limit };
let query = ide_search::WordQuery {
word: q.word.clone(),
dir: q.root.clone(),
exclude: self.search_excludes(),
limit: q.limit,
};
let filter = |rel: &str| q.languages.contains(&self.languages.detect(&root.join(rel), None));
match ide_search::files_with_word(&root, &query, Some(&filter), &|p| self.documents.search_text_of(p), cancel) {
Ok(found) => ide_lsp::CandidateFiles { files: found.files, limit_hit: found.limit_hit },
-26
Переглянути файл
@@ -468,25 +468,6 @@ impl ServerCaps {
self.restriction = restriction;
return;
}
// JDT LS registers the commands of bundles that were not loaded when it initialized.
if method == "workspace/executeCommand"
&& let Some(added) = options.and_then(|o| o.get("commands")).and_then(Value::as_array)
{
if !self.raw.get("executeCommandProvider").is_some_and(Value::is_object) {
self.raw["executeCommandProvider"] = json!({ "commands": [] });
}
let provider = &mut self.raw["executeCommandProvider"];
if !provider.get("commands").is_some_and(Value::is_array) {
provider["commands"] = json!([]);
}
let commands = provider["commands"].as_array_mut().expect("commands");
for command in added {
if !commands.contains(command) {
commands.push(command.clone());
}
}
return;
}
if method == "textDocument/didSave" {
let include = options.and_then(|o| o.get("includeText")).and_then(Value::as_bool).unwrap_or(false);
self.save = Some(include);
@@ -585,13 +566,6 @@ mod tests {
assert!(c.file_operation("willRename").is_some());
c.unregister("workspace/willRenameFiles");
assert!(c.file_operation("willRename").is_none());
// Commands registered later join those announced at initialization.
let mut c = ServerCaps::parse(json!({ "executeCommandProvider": { "commands": ["a"] } }));
c.register("workspace/executeCommand", Some(&json!({ "commands": ["b", "a"] })));
assert_eq!(c.commands(), vec!["a", "b"]);
let mut c = ServerCaps::parse(json!({}));
c.register("workspace/executeCommand", Some(&json!({ "commands": ["b"] })));
assert_eq!(c.commands(), vec!["b"]);
}
fn restriction(features: &[&str], kinds: &[&str]) -> Restriction {
+3 -6
Переглянути файл
@@ -1462,8 +1462,8 @@ impl LspManager {
self.references_streaming(doc, pos, include_declaration, project_wide, true, cancel, None).await
}
/// [`Self::references`]. Java: without `libraries`, only the workspace's sources
/// are searched (`libraries_skipped`); with it and `project_wide`, those found
/// [`Self::references`]. Java, `project_wide`: without `libraries`, only the
/// workspace's sources are searched (`libraries_skipped`); with it, those found
/// there arrive on `partial` before the dependencies and the JDK are searched.
#[allow(clippy::too_many_arguments)]
pub async fn references_streaming(
@@ -1630,10 +1630,7 @@ impl LspManager {
};
scope::Widened { first: all, second: Some(found), incomplete: sources.incomplete }
} else {
// Scoped probes (usage counts, bulk scans) run for many symbols at once:
// without `libraries`, the dependencies and the JDK are not searched.
libraries_skipped = !libraries;
let first = query(!libraries).await?;
let first = query(false).await?;
let empty = first.is_empty();
scope::Widened::only(first, empty, &t.server)
};
+14 -51
Переглянути файл
@@ -25,17 +25,12 @@ use std::time::Duration;
/// Files opened for one search at most.
pub const MAX_CANDIDATES: usize = 300;
/// Candidates checked against a server's analysis scope ([`COVERED_FILES`]) at most: most
/// are usually covered, so a common name only exceeds [`MAX_CANDIDATES`] after that check.
const MAX_SCOPE_CANDIDATES: usize = 5000;
/// Larger files (generated code, bundles) are not opened.
const MAX_CANDIDATE_BYTES: u64 = 1 << 20;
/// How long a search that found nothing waits for a server to finish indexing.
const INDEX_WAIT: Duration = Duration::from_secs(10);
/// Optional server command: candidate URIs in, already analysed candidate URIs out.
const COVERED_FILES: &str = "openidea.workspace.coveredFiles";
/// Optional server command: directories whose files of its languages it all analyses.
const COVERED_ROOTS: &str = "openidea.workspace.coveredRoots";
/// Project files that may mention a symbol.
#[derive(Clone, Debug)]
@@ -47,8 +42,6 @@ pub struct CandidateQuery {
/// Only files of these languages.
pub languages: Vec<LanguageId>,
pub limit: usize,
/// Directories not to look in: the server already analyses every file there.
pub skip: Vec<PathBuf>,
}
#[derive(Clone, Debug, Default)]
@@ -99,16 +92,14 @@ impl LspManager {
*self.candidates_hook.write() = Some(Arc::from(hook));
}
async fn candidates(
&self,
t: &Target,
word: String,
limit: usize,
skip: Vec<PathBuf>,
cancel: &CancellationToken,
) -> Option<CandidateFiles> {
async fn candidates(&self, t: &Target, word: String, cancel: &CancellationToken) -> Option<CandidateFiles> {
let hook = self.candidates_hook.read().clone()?;
let query = CandidateQuery { word, root: t.server.root.clone(), languages: t.server.languages(), limit, skip };
let query = CandidateQuery {
word,
root: t.server.root.clone(),
languages: t.server.languages(),
limit: MAX_CANDIDATES,
};
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || hook(&query, &cancel)).await.ok()
}
@@ -134,12 +125,11 @@ impl LspManager {
// gopls searches the view of the file asked about; files opened for it only get views of
// their own (see `go_scope`).
let word = search_word(snap, pos).filter(|_| t.caps().open_close && snap.language.as_str() != "go");
let reports_scope = has_command(t, COVERED_FILES);
let limit = if reports_scope { MAX_SCOPE_CANDIDATES } else { MAX_CANDIDATES };
let candidates = async {
let w = word?;
let skip = if reports_scope { self.covered_roots(t, cancel).await } else { Vec::new() };
self.candidates(t, w, limit, skip, cancel).await
match word {
Some(w) => self.candidates(t, w, cancel).await,
None => None,
}
};
let (first, candidates) = futures::join!(query(), candidates);
let mut first = first?;
@@ -158,14 +148,10 @@ impl LspManager {
}
let known: HashSet<PathBuf> = covered(&first).into_iter().chain([snap.path.clone()]).collect();
let files: Vec<PathBuf> = candidates.files.into_iter().filter(|f| !known.contains(f)).collect();
let mut files = self.files_beyond_scope(t, files, cancel).await;
let files = self.files_beyond_scope(t, files, cancel).await;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if files.len() > MAX_CANDIDATES {
files.truncate(MAX_CANDIDATES);
incomplete = incomplete.or(Some(ReferencesIncomplete::TooManyFiles));
}
if files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
@@ -194,25 +180,8 @@ impl LspManager {
}
}
/// Directories whose files `t` analyses all ([`COVERED_ROOTS`]); none when it can't say.
async fn covered_roots(&self, t: &Target, cancel: &CancellationToken) -> Vec<PathBuf> {
if !has_command(t, COVERED_ROOTS) {
return Vec::new();
}
let params = json!({ "command": COVERED_ROOTS, "arguments": [] });
let roots: IdeResult<Vec<String>> =
self.call(t, "workspace/executeCommand", params, Some(cancel), crate::DEFAULT_TIMEOUT).await;
match roots {
Ok(roots) => roots.iter().filter_map(|uri| crate::uri::uri_to_path(uri)).collect(),
Err(e) => {
tracing::debug!("{}: covered roots unavailable: {}", t.server.name, e.message);
Vec::new()
}
}
}
async fn files_beyond_scope(&self, t: &Target, files: Vec<PathBuf>, cancel: &CancellationToken) -> Vec<PathBuf> {
if files.is_empty() || !has_command(t, COVERED_FILES) {
if files.is_empty() || !t.caps().commands().iter().any(|c| c == COVERED_FILES) {
return files;
}
let uris: Vec<String> = files.iter().map(|p| crate::uri::path_to_uri_string(p)).collect();
@@ -255,9 +224,7 @@ impl LspManager {
.filter(|l| l.uri.is_none())
.collect();
let Some(declaration) = declarations.first() else { return GoMentions::default() };
let Some(candidates) = self.candidates(t, word.clone(), MAX_CANDIDATES, Vec::new(), cancel).await else {
return GoMentions::default();
};
let Some(candidates) = self.candidates(t, word.clone(), cancel).await else { return GoMentions::default() };
let (origin, declared) = (snap.path.clone(), declaration.path.to_path_buf());
let files = tokio::task::spawn_blocking(move || {
crate::go_scope::files_beyond_search(&origin, &declared, candidates.files)
@@ -511,7 +478,3 @@ impl Drop for TransientFiles<'_> {
}
}
}
fn has_command(t: &Target, command: &str) -> bool {
t.caps().commands().iter().any(|c| c == command)
}
-101
Переглянути файл
@@ -3454,81 +3454,6 @@ async fn unavailable_scope_capability_keeps_widening_and_incomplete_signals() {
}
}
/// A common name is mentioned by more files than a search opens, but a server that reports its
/// analysis scope already covers most of them: only those beyond it count toward the limit.
#[tokio::test(flavor = "multi_thread")]
async fn covered_candidates_do_not_count_toward_the_open_limit() {
for covers_all in [true, false] {
let mut caps = incremental_caps();
caps["executeCommandProvider"]["commands"] = json!(["openidea.workspace.coveredFiles"]);
let h = harness(&[("mock", caps)]);
let s = h.launcher.state("mock");
let files: Vec<PathBuf> = (0..ide_lsp::MAX_CANDIDATES + 100)
.map(|i| {
let path = h.root.join(format!("f{i:03}.mk"));
std::fs::write(&path, "target\n").unwrap();
path
})
.collect();
let covered: Vec<String> = if covers_all { files.iter().map(|f| uri_of(f)).collect() } else { vec![] };
let responder = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if method == "workspace/executeCommand" {
return Some(json!(covered));
}
responder(s, method, params)
}));
let seen = grep_candidates(&h);
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert!(seen.lock().iter().all(|q| q.limit > ide_lsp::MAX_CANDIDATES));
let opened = s.notified("textDocument/didOpen").len() - 1;
if covers_all {
assert_eq!(refs.incomplete, None);
assert_eq!(opened, 0);
assert_eq!(s.requested("textDocument/references").len(), 1);
} else {
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::TooManyFiles));
assert_eq!(opened, ide_lsp::MAX_CANDIDATES);
}
}
}
/// Files under the directories a server analyses fully are not read to find candidates.
#[tokio::test(flavor = "multi_thread")]
async fn candidates_skip_the_directories_the_server_covers() {
for (commands, reported) in [
(json!(["openidea.workspace.coveredFiles", "openidea.workspace.coveredRoots"]), json!(["src"])),
(json!(["openidea.workspace.coveredFiles", "openidea.workspace.coveredRoots"]), json!(null)),
(json!(["openidea.workspace.coveredFiles"]), json!(["src"])),
] {
let mut caps = incremental_caps();
caps["executeCommandProvider"]["commands"] = commands.clone();
let h = harness(&[("mock", caps)]);
let s = h.launcher.state("mock");
let src = h.root.join("src");
let roots = reported.as_array().map(|r| r.iter().map(|_| json!(uri_of(&src))).collect::<Vec<_>>());
let responder = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if method == "workspace/executeCommand" {
return Some(match params["command"].as_str() {
Some("openidea.workspace.coveredRoots") => roots.clone().map_or(json!(null), Value::Array),
_ => json!([]),
});
}
responder(s, method, params)
}));
let seen = grep_candidates(&h);
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
let skipped: Vec<Vec<PathBuf>> = seen.lock().iter().map(|q| q.skip.clone()).collect();
let expected = if commands.as_array().unwrap().len() == 2 && reported.is_array() { vec![src] } else { vec![] };
assert_eq!(skipped, vec![expected], "{commands} {reported}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn references_open_unopened_files_that_mention_the_name() {
let (h, s) = scope_harness();
@@ -3827,32 +3752,6 @@ async fn classified_java_references_widen_without_losing_metadata() {
}
}
/// Usage counts probe many symbols at once: without `libraries` they search the sources alone.
#[tokio::test(flavor = "multi_thread")]
async fn scoped_java_usages_search_the_sources_unless_libraries_are_asked_for() {
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
let s = h.launcher.state("jdtls");
s.respond("workspace/executeCommand", json!([]));
let (doc, _) = h.open("a.java", "int target;");
h.wait_status("jdtls", ServerStatus::Ready).await;
let seen = grep_candidates(&h);
for libraries in [false, true] {
let refs = h
.mgr
.references_streaming(doc, Pos::new(0, 5), false, false, libraries, Default::default(), None)
.await
.unwrap();
assert_eq!(refs.libraries_skipped, !libraries);
let requested = s.requested("workspace/executeCommand");
let arguments = requested.last().unwrap()["arguments"].as_array().unwrap().clone();
assert_eq!(arguments.get(4) == Some(&json!("sources")), !libraries);
assert_eq!(arguments.len(), if libraries { 4 } else { 5 });
}
assert!(seen.lock().is_empty());
}
/// A library method's usages in the sources are shown before the dependencies and the JDK
/// are searched, which takes seconds; scope widening searches the sources alone again.
#[tokio::test(flavor = "multi_thread")]
+18 -151
Переглянути файл
@@ -271,11 +271,6 @@ impl Cx<'_> {
}
}
/// A filesystem path: expand IDEA's macros before converting a file URL.
fn path(&self, value: Option<&str>) -> Res<Option<String>> {
Ok(self.text(value)?.map(|v| file_url_path(&v)))
}
/// Words of a parameters field, split like IDEA's `ParametersListUtil.parse`.
fn words(&self, value: Option<&str>) -> Res<Vec<String>> {
self.words_quoted(value, Quotes::Double)
@@ -291,16 +286,12 @@ impl Cx<'_> {
}
fn args_quoted(&self, value: Option<&str>, quotes: Quotes, dir: &Path) -> Res<Vec<String>> {
Ok(self
.words_quoted(value, quotes)?
.into_iter()
.map(|a| path_from(self.root, file_url_path(&a), dir))
.collect())
Ok(self.words_quoted(value, quotes)?.into_iter().map(|a| path_from(self.root, a, dir)).collect())
}
/// The working directory (absolute) and the configuration's `cwd`.
fn cwd(&self, value: Option<&str>) -> Res<(PathBuf, Option<PathBuf>)> {
Ok(match self.path(value)? {
Ok(match self.text(value)? {
Some(dir) => working_dir(self.root, &dir),
None => (self.root.to_path_buf(), None),
})
@@ -359,7 +350,7 @@ impl Cx<'_> {
/// options, and the working directory.
fn interpreter(&self, c: &El, ignored: &mut Vec<String>) -> Res<(String, Vec<String>, PathBuf, Option<PathBuf>)> {
let (dir, cwd) = self.cwd(c.option("WORKING_DIRECTORY"))?;
let sdk = if c.flag("IS_MODULE_SDK") { None } else { self.path(c.option("SDK_HOME"))? };
let sdk = if c.flag("IS_MODULE_SDK") { None } else { self.text(c.option("SDK_HOME"))? };
let (exe, mut args) = match sdk {
Some(sdk) => (path_from(self.root, sdk, &dir), Vec::new()),
None => project_python(self.root, &dir),
@@ -378,7 +369,7 @@ impl Cx<'_> {
rc.extras.include_system_env = c.option("PARENT_ENVS") != Some("false");
// PyCharm 2024+: "Paths to .env files", joined with `File.pathSeparator`.
for file in split_env_files(c.option("ENV_FILES").unwrap_or_default(), PATH_SEPARATOR) {
if let Some(file) = self.path(Some(file))? {
if let Some(file) = self.text(Some(file))? {
rc.extras.env_files.push(path_from(self.root, file, self.root));
}
}
@@ -412,7 +403,7 @@ impl Cx<'_> {
ignored.push(format!("EnvFile {path}"));
continue;
}
if let Some(file) = self.path(Some(path))? {
if let Some(file) = self.text(Some(path))? {
rc.extras.env_files.push(path_from(self.root, file, self.root));
}
}
@@ -427,7 +418,7 @@ impl Cx<'_> {
if c.flag("MODULE_MODE") {
args.extend(["-m".to_owned(), script]);
} else {
args.push(path_from(self.root, file_url_path(&script), &dir));
args.push(path_from(self.root, script, &dir));
}
args.extend(self.args(c.option("PARAMETERS"), &dir)?);
let mut rc = config(name, "python", exe, args, Some("debugpy"));
@@ -489,7 +480,7 @@ impl Cx<'_> {
args.extend([manage, "test".to_owned()]);
args.extend(self.words(c.option("TARGET"))?);
if c.flag("CUSTOM_SETTINGS")
&& let Some(settings) = self.path(c.option("SETTINGS_FILE"))?
&& let Some(settings) = self.text(c.option("SETTINGS_FILE"))?
{
args.extend(["--settings".to_owned(), settings_module(&settings, self.root, &dir)]);
}
@@ -528,7 +519,7 @@ impl Cx<'_> {
}
}
Some("CUSTOM") => {}
_ => args.push(path_from(self.root, file_url_path(&target), &dir)),
_ => args.push(path_from(self.root, target, &dir)),
}
}
if target_type.as_deref() != Some("CUSTOM")
@@ -583,7 +574,7 @@ impl Cx<'_> {
fn node_interpreter(&self, c: &El) -> Res<Option<String>> {
match c.value("node-interpreter").or_else(|| c.attr("node-interpreter")).map(str::trim) {
None | Some("" | "project") => Ok(None),
interpreter => self.path(interpreter),
interpreter => self.text(interpreter),
}
}
@@ -596,12 +587,12 @@ impl Cx<'_> {
}
fn npm(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
let package_json = self.path(c.value("package-json"))?;
let package_json = self.text(c.value("package-json"))?;
let dir = match &package_json {
Some(p) => normalize(&self.root.join(p)).parent().map(Path::to_path_buf).unwrap_or(self.root.to_path_buf()),
None => self.root.to_path_buf(),
};
let manager = match self.path(c.value("package-manager"))? {
let manager = match self.text(c.value("package-manager"))? {
Some(pm) if ["npm", "pnpm", "yarn", "bun"].contains(&command_name(&pm)) => command_name(&pm).to_owned(),
_ => {
let pkg = std::fs::read_to_string(dir.join("package.json"))
@@ -659,14 +650,14 @@ impl Cx<'_> {
fn js_tests(&self, name: &str, c: &El, vitest: bool, ignored: &mut Vec<String>) -> Res<RunConfig> {
let (dir, cwd) = self.cwd(c.value("working-dir"))?;
let mut args: Vec<String> = if vitest { vec!["vitest".into(), "run".into()] } else { vec!["jest".into()] };
if !vitest && let Some(config_file) = self.path(c.value("config-file"))? {
if !vitest && let Some(config_file) = self.text(c.value("config-file"))? {
args.extend(["--config".to_owned(), path_from(self.root, config_file, &dir)]);
}
args.extend(self.args(c.value(if vitest { "vitest-options" } else { "jest-options" }), &dir)?);
match c.value("scope-kind").unwrap_or("ALL") {
"DIRECTORY" => args.extend(self.path(c.value("test-directory"))?.map(|d| path_from(self.root, d, &dir))),
"DIRECTORY" => args.extend(self.text(c.value("test-directory"))?.map(|d| path_from(self.root, d, &dir))),
"TEST_FILE" | "SUITE" | "TEST" => {
args.extend(self.path(c.value("test-file"))?.map(|f| path_from(self.root, f, &dir)));
args.extend(self.text(c.value("test-file"))?.map(|f| path_from(self.root, f, &dir)));
let names: Vec<&str> = c
.child("test-names")
.into_iter()
@@ -695,7 +686,7 @@ impl Cx<'_> {
fn node(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
let (dir, cwd) = self.cwd(c.attr("working-dir"))?;
let Some(file) = self.path(c.attr("path-to-js-file"))? else {
let Some(file) = self.text(c.attr("path-to-js-file"))? else {
return Err(SkipReason::NothingToRun);
};
let mut args = self.words(c.attr("node-parameters"))?;
@@ -765,11 +756,11 @@ impl Cx<'_> {
let mut params = BTreeMap::new();
// Both default to true when missing (`ShRunConfiguration.java:148-149`).
let rc = if c.option("EXECUTE_SCRIPT_FILE") != Some("false") {
let Some(path) = self.path(c.option("SCRIPT_PATH"))? else { return Err(SkipReason::NothingToRun) };
let Some(path) = self.text(c.option("SCRIPT_PATH"))? else { return Err(SkipReason::NothingToRun) };
let path = path_from(self.root, path, &dir);
let options = self.text(c.option("SCRIPT_OPTIONS"))?.unwrap_or_default();
let interpreter =
self.path(c.option("INTERPRETER_PATH"))?.map(|i| path_from(self.root, i, &dir)).unwrap_or_default();
self.text(c.option("INTERPRETER_PATH"))?.map(|i| path_from(self.root, i, &dir)).unwrap_or_default();
let interpreter_options = self.text(c.option("INTERPRETER_OPTIONS"))?.unwrap_or_default();
// Run directly, the script is the program: `./run.sh`, so it isn't looked up on the PATH.
let path = if interpreter.is_empty() { dot_slash(path) } else { path };
@@ -870,67 +861,7 @@ const PATH_SEPARATOR: char = if cfg!(windows) { ';' } else { ':' };
/// The `ENV_FILES` paths, joined with `separator` (intellij-community
/// `AbstractPythonRunConfiguration.java:303-304`, `:337`).
fn split_env_files(value: &str, separator: char) -> impl Iterator<Item = &str> {
let mut rest = value;
std::iter::from_fn(move || {
if rest.is_empty() {
return None;
}
let end = rest.match_indices(separator).find_map(|(end, _)| {
let field = rest[..end].trim_start();
if separator == ':' {
// A URL's scheme and optional drive letter aren't list separators.
let scheme = field.eq_ignore_ascii_case("file");
let drive = field.strip_prefix("file:").is_some_and(|body| {
let body = body.trim_start_matches('/');
let body = body
.split_once('/')
.filter(|(host, _)| host.eq_ignore_ascii_case("localhost"))
.map_or(body, |(_, path)| path);
body.len() == 1 && body.as_bytes()[0].is_ascii_alphabetic()
});
if scheme || drive {
return None;
}
}
Some(end)
});
let field = match end {
Some(end) => {
let field = &rest[..end];
rest = &rest[end + separator.len_utf8()..];
field
}
None => std::mem::take(&mut rest),
};
Some(field)
})
.filter(|f| !f.trim().is_empty())
}
/// The path a `file:` URL names, and `value` unchanged when it is not one.
///
/// IDEA writes path options as URLs (`file://$PROJECT_DIR$`), which expand to
/// `file://C:/project` on Windows: the drive letter lands where a URL's authority
/// belongs. Parsing that as a path yields `C:project`, a drive-relative path that
/// then resolves against the project directory instead of replacing it.
fn file_url_path(value: &str) -> String {
let Some(rest) = value.strip_prefix("file:") else {
return value.to_owned();
};
let rest = match rest.strip_prefix("//").and_then(|r| r.split_once('/')) {
Some((host, path)) if host.eq_ignore_ascii_case("localhost") => path,
_ => rest,
};
let body = rest.trim_start_matches('/');
let drive = matches!(body.as_bytes(), [d, b':', ..] if d.is_ascii_alphabetic());
if drive {
body.to_owned()
} else if rest.starts_with("//") && !rest.starts_with("///") {
// A real authority (`file://server/share`): a UNC path.
format!("//{body}")
} else {
format!("/{body}")
}
value.split(separator).filter(|f| !f.trim().is_empty())
}
/// Keywords without the quotes around them (`"not slow"` → `not slow`).
@@ -1034,57 +965,6 @@ mod tests {
assert!(parse("<a><b></a>").is_err());
}
#[test]
fn file_urls_become_paths_whatever_the_drive_letter_looks_like() {
// IDEA on Windows: the drive letter sits where the authority belongs.
assert_eq!(file_url_path("file://C:/p"), "C:/p");
assert_eq!(file_url_path(r"file://C:\p"), r"C:\p");
assert_eq!(file_url_path("file:///C:/p"), "C:/p");
assert_eq!(file_url_path("file:///p/a"), "/p/a");
assert_eq!(file_url_path("file://server/share"), "//server/share");
// Not a URL: left alone, including a bare Windows path.
assert_eq!(file_url_path(r"C:\p"), r"C:\p");
assert_eq!(file_url_path("/p/a"), "/p/a");
assert_eq!(file_url_path(""), "");
}
#[test]
fn file_urls_preserve_paths_and_treat_localhost_as_local() {
for (url, expected) in [
("file:///p/100%20", "/p/100%20"),
("file:///p/a%E4", "/p/a%E4"),
("file:///p/a b/中.py", "/p/a b/中.py"),
("file://C:/a b/é", "C:/a b/é"),
("file:///C:/a%20b", "C:/a%20b"),
("file://localhost/p/a%20b", "/p/a%20b"),
("file://localhost/C:/a%20b", "C:/a%20b"),
("file://LOCALHOST/p", "/p"),
("file://server/share/a%20b", "//server/share/a%20b"),
("file:///p/%2520", "/p/%2520"),
("/p/a%20b", "/p/a%20b"),
("relative%20path", "relative%20path"),
("https://localhost/a%20b", "https://localhost/a%20b"),
] {
assert_eq!(file_url_path(url), expected, "{url}");
}
}
/// The property the bug broke: `working_dir` joins its `cwd` onto the project
/// directory, so a URL that reads as a relative path resolves inside it instead
/// of replacing it.
#[test]
fn file_urls_name_absolute_paths() {
let absolute = if cfg!(windows) {
vec!["file://C:/p", "file:///C:/p", r"file://C:\p", "file://server/share"]
} else {
vec!["file:///p/a", "file://server/share"]
};
for url in absolute {
let path = file_url_path(url);
assert!(Path::new(&path).is_absolute(), "{url} became {path:?}, which is not absolute");
}
}
#[test]
fn env_files_split_on_the_path_separator() {
assert_eq!(
@@ -1095,19 +975,6 @@ mod tests {
split_env_files(r"C:\p\.env;C:\p\.env.local", ';').collect::<Vec<_>>(),
[r"C:\p\.env", r"C:\p\.env.local"]
);
assert_eq!(
split_env_files("file://$PROJECT_DIR$/.env:file://localhost/p/a%20b:.env.local", ':').collect::<Vec<_>>(),
["file://$PROJECT_DIR$/.env", "file://localhost/p/a%20b", ".env.local"]
);
assert_eq!(
split_env_files("file://C:/p/.env:file:///D:/p/.env:file://localhost/E:/p/.env%3Adev", ':')
.collect::<Vec<_>>(),
["file://C:/p/.env", "file:///D:/p/.env", "file://localhost/E:/p/.env%3Adev"]
);
assert_eq!(
split_env_files("file://C:/p/.env;file://localhost/C:/p/.env.local", ';').collect::<Vec<_>>(),
["file://C:/p/.env", "file://localhost/C:/p/.env.local"]
);
assert_eq!(split_env_files("", ':').count(), 0);
assert_eq!(PATH_SEPARATOR, if cfg!(windows) { ';' } else { ':' });
}
+11 -156
Переглянути файл
@@ -849,115 +849,21 @@ fn sync_tree(
Ok(())
}
/// A built `*.war` under a module's usual output directory (`target/`, `build/libs/`).
fn is_war(path: &Path) -> bool {
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("war"))
}
/// The module directory a config's `cwd` names (absolute, or relative to the project root).
fn module_dir(root: &Path, module: Option<&Path>) -> PathBuf {
match module {
Some(m) if m.is_absolute() => m.to_path_buf(),
Some(m) => root.join(m),
None => root.to_path_buf(),
}
}
/// The newest modification time of `path` or, for a directory, anything below it.
fn newest_mtime_under(path: &Path) -> Option<std::time::SystemTime> {
let meta = fs::metadata(path).ok()?;
let mut newest = meta.modified().ok();
if meta.is_dir() {
for entry in fs::read_dir(path).ok()?.flatten() {
if let Some(time) = newest_mtime_under(&entry.path())
&& newest.is_none_or(|cur| time > cur)
{
newest = Some(time);
}
}
}
newest
}
/// The newest `*.war` a build tool left in the module's output directories. Used when no
/// build ran this launch and nothing was recorded, so a project that was already built can
/// start directly (IDEA deploys the existing artifact instead of rebuilding it).
fn find_built_war(root: &Path, module: Option<&Path>) -> Option<PathBuf> {
let module = module_dir(root, module);
let mut newest: Option<(std::time::SystemTime, PathBuf)> = None;
for dir in [module.join("target"), module.join("build/libs")] {
let Ok(entries) = fs::read_dir(dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && is_war(&path) {
let modified = entry.metadata().and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH);
if newest.as_ref().is_none_or(|(at, _)| modified > *at) {
newest = Some((modified, path));
}
}
}
}
newest.map(|(_, path)| path)
}
/// Whether the WAR a Tomcat config deploys is newer than the module's sources, so its
/// "Before launch › Build" task can be skipped (IDEA's up-to-date check). Conservative:
/// a missing WAR or a newer source/build file means it is not current. Only the module's
/// own sources and build files are inspected, not dependency modules.
pub fn artifact_is_current(root: &Path, base: &Path, config: &RunConfig) -> bool {
let p = &config.extras.params;
if p.get("deployment").map(String::as_str).unwrap_or("artifact") != "artifact" {
return true;
}
let module = module_dir(root, config.cwd.as_ref().map(|c| c.0.as_path()));
let selected = p.get("artifact").filter(|s| !s.is_empty());
let recorded_id = fs::read_to_string(base.join("artifact-id.txt")).ok();
let id_matches = selected.is_none_or(|id| recorded_id.as_deref().map(str::trim) == Some(id.as_str()));
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
let war = match recorded.filter(|_| id_matches) {
Some(war) if war.is_file() && is_war(&war) => war,
_ => match find_built_war(root, Some(&module)) {
Some(war) => war,
None => return false,
},
};
let Ok(war_time) = fs::metadata(&war).and_then(|m| m.modified()) else { return false };
let mut newest = newest_mtime_under(&module.join("src"));
for dir in [module.as_path(), root] {
for name in ["pom.xml", "build.gradle", "build.gradle.kts"] {
if let Ok(time) = fs::metadata(dir.join(name)).and_then(|m| m.modified())
&& newest.is_none_or(|cur| time > cur)
{
newest = Some(time);
}
}
}
newest.is_none_or(|time| time <= war_time)
}
pub fn deployment(root: &Path, base: &Path, config: &RunConfig, resources_only: bool) -> IdeResult<PathBuf> {
let p = &config.extras.params;
match p.get("deployment").map(String::as_str).unwrap_or("artifact") {
"artifact" => {
// A build run this launch records its archive here. Without one (Before launch ›
// Build removed, as IDEA allows), reuse the last build's archive, or an archive a
// build tool already left in the module output, instead of rebuilding.
let selected = p.get("artifact").filter(|s| !s.is_empty());
let recorded_id = fs::read_to_string(base.join("artifact-id.txt")).ok();
let id_matches = selected.is_none_or(|id| recorded_id.as_deref().map(str::trim) == Some(id.as_str()));
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
let war = match recorded.filter(|_| id_matches) {
Some(war) => {
if war.is_file() && is_war(&war) {
war
} else {
return Err(invalid(format!("The built WAR artifact does not exist: {}", war.display())));
}
}
None => find_built_war(root, config.cwd.as_ref().map(|c| c.0.as_path())).ok_or_else(|| {
invalid("No built WAR artifact found - build the project first, or add 'Build' to Before launch")
})?,
};
if let Some(id) = p.get("artifact").filter(|s| !s.is_empty())
&& fs::read_to_string(base.join("artifact-id.txt")).ok().as_ref() != Some(id)
{
return Err(invalid("Build the selected WAR artifact before launching Tomcat"));
}
let war = fs::read_to_string(base.join("artifact-path.txt"))
.map_err(|_| invalid("Build the WAR artifact before launching Tomcat"))?;
let war = PathBuf::from(war.trim());
if !war.is_file() || !war.extension().is_some_and(|e| e.eq_ignore_ascii_case("war")) {
return Err(invalid(format!("The built WAR artifact does not exist: {}", war.display())));
}
let dest = base.join("deployment");
explode(&war, &dest, resources_only)?;
Ok(dest)
@@ -1496,57 +1402,6 @@ mod tests {
}
}
}
#[test]
fn reuses_a_built_war_when_no_build_ran() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let module = root.join("web");
fs::create_dir_all(module.join("target")).unwrap();
let war = module.join("target/app.war");
archive(&war, &[("index.html", "built")]);
let base = root.join("cache");
fs::create_dir_all(&base).unwrap();
let mut c = config();
c.cwd = Some(ide_core::IpcPath(PathBuf::from("web")));
c.extras.params.insert("artifact".into(), "maven:web/pom.xml".into());
// No artifact-path.txt / artifact-id.txt: it was never built through Tomcat.
let dest = deployment(root, &base, &c, false).unwrap();
assert_eq!(fs::read_to_string(dest.join("index.html")).unwrap(), "built");
}
#[test]
fn reports_a_missing_artifact_when_nothing_was_built() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path().join("cache");
fs::create_dir_all(&base).unwrap();
let error = deployment(tmp.path(), &base, &config(), false).unwrap_err().to_string();
assert!(error.contains("No built WAR artifact found"), "{error}");
}
#[test]
fn skips_the_build_when_the_built_war_is_current() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let module = root.join("web");
fs::create_dir_all(module.join("src/main/java")).unwrap();
fs::create_dir_all(module.join("target")).unwrap();
fs::write(module.join("pom.xml"), "<project/>").unwrap();
let source = module.join("src/main/java/App.java");
fs::write(&source, "class App {}").unwrap();
let war = module.join("target/app.war");
archive(&war, &[("index.html", "built")]);
let base = root.join("cache");
fs::create_dir_all(&base).unwrap();
let mut c = config();
c.cwd = Some(ide_core::IpcPath(PathBuf::from("web")));
c.extras.params.insert("artifact".into(), "maven:web/pom.xml".into());
// The WAR was packed after the source was written.
assert!(artifact_is_current(root, &base, &c));
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(&source, "class App { int changed; }").unwrap();
assert!(!artifact_is_current(root, &base, &c));
}
#[test]
fn prepares_isolated_base_and_jdwp_only_for_run() {
let tmp = tempfile::tempdir().unwrap();
-220
Переглянути файл
@@ -787,223 +787,3 @@ fn java_applications_and_spring_boot_keep_their_module() {
assert_eq!(reason(&r, "NoMain"), &SkipReason::NothingToRun);
}
/// IDEA writes the working directory as a URL. On Windows `file://$PROJECT_DIR$`
/// expands to `file://C:/project`, where the drive letter sits where the authority
/// belongs; read as a path that is `C:project`, which resolves against the project
/// directory instead of replacing it and the launch fails on the doubled path.
#[test]
fn file_url_working_directories_stay_inside_the_project() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(&root, "pom.xml", "<project><artifactId>shop</artifactId><packaging>pom</packaging></project>");
write(
&root,
"gateway/pom.xml",
"<project><parent><artifactId>shop</artifactId></parent><artifactId>gateway</artifactId></project>",
);
write(
&root,
".run/Gateway.run.xml",
&run_file(
"Gateway",
r#"<configuration name="NAME" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="gateway" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.example.GatewayApplication" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ACTIVE_PROFILES" value="dev,local" />
<option name="VM_PARAMETERS" value="-Xmx512m" />
<option name="PROGRAM_PARAMETERS" value="--server.port=8081" />
<envs><env name="TZ" value="UTC" /></envs>
<method v="2"><option name="Make" enabled="true" /></method>
</configuration>"#,
),
);
write(
&root,
".run/Sub.run.xml",
&run_file(
"Sub",
r#"<configuration name="NAME" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="gateway" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.example.SubApplication" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$/gateway" />
<method v="2" />
</configuration>"#,
),
);
let local_root = root.to_string_lossy().replace('\\', "/");
for (name, working_directory) in [
("Literal", "file://$PROJECT_DIR$/gateway é".to_owned()),
("Localhost", format!("file://localhost/{}", local_root.trim_start_matches('/'))),
] {
write(
&root,
&format!(".run/{name}.run.xml"),
&run_file(
name,
&format!(
r#"
<configuration name="NAME" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="gateway" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.example.GatewayApplication" />
<option name="WORKING_DIRECTORY" value="{working_directory}" />
</configuration>"#
),
),
);
}
let r = import_from(&root, &[]);
let boot = get(&r, "Gateway");
assert_eq!(boot.kind, "spring-boot");
assert_eq!(boot.extras.module.as_deref(), Some("gateway"));
assert_eq!(
boot.args,
s(&[
"-Xmx512m",
"-cp",
"${classpath}",
"com.example.GatewayApplication",
"--spring.profiles.active=dev,local",
"--server.port=8081"
])
);
assert_eq!(boot.env["TZ"], "UTC");
assert_eq!(cwd(get(&r, "Literal")), Some(PathBuf::from("gateway é")));
assert_eq!(cwd(get(&r, "Localhost")), None);
// The project directory itself: no `cwd` to store.
assert_eq!(cwd(get(&r, "Gateway")), None);
assert_eq!(cwd(get(&r, "Sub")), Some(PathBuf::from("gateway")));
}
#[test]
fn file_urls_work_in_all_imported_path_fields() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
let cases = [
(
"Python",
r#"<configuration name="NAME" type="PythonConfigurationType">
<option name="WORKING_DIRECTORY" value="{base}/jobs 中" />
<option name="SDK_HOME" value="{base}/bin/python" />
<option name="SCRIPT_NAME" value="{base}/jobs 中/run me.py" />
<option name="PARAMETERS" value="&quot;{base}/data file&quot; unchanged%20arg" />
<option name="ENV_FILES" value="{base}/.env dev{sep}{base}/.env local" />
<extension name="net.ashald.envfile">
<option name="IS_ENABLED" value="true" />
<ENTRIES><ENTRY PATH="{base}/.env plugin" PARSER="env" /></ENTRIES>
</extension>
</configuration>"#,
),
(
"Django",
r#"<configuration name="NAME" type="DjangoTestsConfigurationType">
<option name="CUSTOM_SETTINGS" value="true" />
<option name="SETTINGS_FILE" value="{base}/settings/dev.py" />
</configuration>"#,
),
(
"Pytest",
r#"<configuration name="NAME" type="tests" factoryName="pytest">
<option name="_new_targetType" value="&quot;PATH&quot;" />
<option name="_new_target" value="&quot;{base}/test file.py&quot;" />
<option name="_new_additionalArguments" value="&quot;'{base}/data file'&quot;" />
</configuration>"#,
),
(
"Npm",
r#"<configuration name="NAME" type="js.build_tools.npm">
<package-json value="{base}/web app/package.json" />
<package-manager value="{base}/bin/pnpm" />
<node-interpreter value="{base}/bin/node" />
<command value="run" /><scripts><script value="start" /></scripts>
</configuration>"#,
),
(
"Jest",
r#"<configuration name="NAME" type="JavaScriptTestRunnerJest">
<working-dir value="{base}/web app" />
<config-file value="{base}/web app/jest config.js" />
<scope-kind value="TEST_FILE" /><test-file value="{base}/web app/test file.js" />
</configuration>"#,
),
(
"Vitest",
r#"<configuration name="NAME" type="JavaScriptTestRunnerVitest">
<scope-kind value="DIRECTORY" /><test-directory value="{base}/test dir" />
</configuration>"#,
),
(
"Node",
r#"<configuration name="NAME" type="NodeJSConfigurationType"
working-dir="{base}/web app" path-to-js-file="{base}/web app/main file.js"
application-parameters="&quot;{base}/data file&quot;" />"#,
),
(
"Shell",
r#"<configuration name="NAME" type="ShConfigurationType">
<option name="SCRIPT_WORKING_DIRECTORY" value="{base}/jobs 中" />
<option name="SCRIPT_PATH" value="{base}/jobs 中/run me.sh" />
<option name="INTERPRETER_PATH" value="{base}/bin/sh" />
</configuration>"#,
),
];
write(&root, "manage.py", "");
for (name, body) in cases {
write(
&root,
&format!(".run/{name}.run.xml"),
&run_file(name, &body.replace("{base}", "file://$PROJECT_DIR$").replace("{sep}", &SEP.to_string())),
);
}
let r = import_from(&root, &[]);
assert!(r.skipped.is_empty(), "{r:#?}");
let python = get(&r, "Python");
assert_eq!(cwd(python), Some(PathBuf::from("jobs 中")));
assert_eq!(python.command, "../bin/python");
assert_eq!(python.args, s(&["run me.py", "../data file", "unchanged%20arg"]));
assert_eq!(python.extras.env_files, s(&[".env dev", ".env local", ".env plugin"]));
assert_eq!(get(&r, "Django").args, s(&["manage.py", "test", "--settings", "settings.dev"]));
assert_eq!(get(&r, "Pytest").args, s(&["-m", "pytest", "test file.py", "data file"]));
let npm = get(&r, "Npm");
assert_eq!(cwd(npm), Some(PathBuf::from("web app")));
assert_eq!(npm.command, "pnpm");
assert_eq!(Path::new(&npm.extras.params["nodeInterpreter"]), root.join("bin/node"));
assert_eq!(get(&r, "Jest").args, s(&["jest", "--config", "jest config.js", "test file.js"]));
assert_eq!(get(&r, "Vitest").args, s(&["vitest", "run", "test dir"]));
assert_eq!(get(&r, "Node").args, s(&["main file.js", "../data file"]));
let shell = get(&r, "Shell");
assert_eq!(shell.command, "../bin/sh");
assert_eq!(shell.args, s(&["run me.sh"]));
assert_eq!(shell.extras.params["path"], "run me.sh");
}
#[test]
fn file_urls_expand_module_and_home_macros() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(
&root,
".run/Home.run.xml",
&run_file(
"Home",
r#"<configuration name="NAME" type="PythonConfigurationType">
<option name="WORKING_DIRECTORY" value="file://$MODULE_DIR$/jobs dir" />
<option name="SCRIPT_NAME" value="file://$MODULE_WORKING_DIR$/jobs dir/main.py" />
<option name="SDK_HOME" value="file://$USER_HOME$/bin/python" />
</configuration>"#,
),
);
let mut environment = env();
let home = root.join("home").to_string_lossy().into_owned();
environment.insert("HOME".into(), home.clone());
environment.insert("USERPROFILE".into(), home);
let r = import(&root, RunImportSource::Jetbrains, &[], &environment).unwrap();
let home = get(&r, "Home");
assert_eq!(home.command, "../home/bin/python");
assert_eq!(home.args, s(&["main.py"]));
assert_eq!(cwd(home), Some(PathBuf::from("jobs dir")));
assert!(home.extras.local);
}
+6 -67
Переглянути файл
@@ -523,63 +523,6 @@ pub fn maven_local_repository(root: &Path, s: &Settings) -> Option<PathBuf> {
})
}
fn xml_escape(text: &str) -> String {
text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}
/// Inserts `<localRepository>` right after the `<settings>` open tag.
fn inject_local_repository(settings_xml: &str, repo: &str) -> Option<String> {
let start = settings_xml.find("<settings")?;
let end = settings_xml[start..].find('>')? + start;
let mut out = String::with_capacity(settings_xml.len() + repo.len() + 40);
out.push_str(&settings_xml[..=end]);
out.push_str("<localRepository>");
out.push_str(&xml_escape(repo));
out.push_str("</localRepository>");
out.push_str(&settings_xml[end + 1..]);
Some(out)
}
fn write_m2e_settings(root: &Path, text: &str) -> Option<PathBuf> {
let file = ide_core::project_dir::path(root, "maven-settings.xml");
if let Some(parent) = file.parent() {
std::fs::create_dir_all(parent).ok()?;
}
match std::fs::read_to_string(&file) {
Ok(existing) if existing == text => {}
_ => std::fs::write(&file, text).ok()?,
}
Some(file)
}
/// The user settings file m2e (the JDTLS Maven import) should read: the
/// configured `settings.xml` when it already declares `<localRepository>`,
/// else a derived copy under `<root>/.openidea/` with the configured local
/// repository injected. m2e resolves the local repository from the settings
/// XML, not from `-Dmaven.repo.local`, so without this the import downloads
/// into `~/.m2/repository` even when the IDE's own `mvn` runs honor the
/// configured path (#1739). `None` = m2e's default applies.
pub fn maven_user_settings_for_m2e(root: &Path, s: &Settings) -> Option<PathBuf> {
let m = &s.languages.java.maven;
if let Some(file) = setting_path(root, &m.user_settings) {
let text = std::fs::read_to_string(&file).ok()?;
if crate::java::xml_value(&crate::lombok::strip_xml_comments(&text), "localRepository").is_some() {
return Some(file);
}
if let Some(repo) = setting_path(root, &m.local_repository) {
let merged = inject_local_repository(&text, &repo.to_string_lossy())?;
if let Some(derived) = write_m2e_settings(root, &merged) {
return Some(derived);
}
}
return Some(file);
}
let repo = setting_path(root, &m.local_repository)?;
let minimal =
format!("<settings><localRepository>{}</localRepository></settings>", xml_escape(&repo.to_string_lossy()));
write_m2e_settings(root, &minimal)
}
/// TypeScript `lib` directory for the selected version; `None` = the server's bundled one.
pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
match s.languages.typescript.version.trim() {
@@ -918,22 +861,18 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
// The jdtls launcher forwards `--jvm-arg=` values to the JVM it starts.
let args = s.languages.java.jdtls_vm_args.split_whitespace().map(|a| format!("--jvm-arg={a}"));
cfg.args.extend(args);
// m2e (the Maven import) reads mirrors, servers and `<localRepository>`
// from the settings file — never from `-Dmaven.repo.local`. The
// derived file carries the configured local repository so the import
// downloads where the IDE's own `mvn` runs do (#1739).
if let Some(file) =
maven_user_settings_for_m2e(root, s).or_else(|| setting_path(root, &s.languages.java.maven.user_settings))
{
// m2e (the Maven import) reads mirrors, servers and `<localRepository>` from it.
if let Some(file) = setting_path(root, &s.languages.java.maven.user_settings) {
let file = file.to_string_lossy();
merge_init_options(
cfg,
json!({ "settings": { "java": { "configuration": { "maven": { "userSettings": file } } } } }),
);
}
// The JVM system property is still forwarded for JVM-level consumers,
// but it is the settings file above that m2e honors. A
// `-Dmaven.repo.local` the user put in their own jdtls VM options wins.
// m2e resolves and downloads into `maven.repo.local`; without it the
// embedded Maven falls back to ~/.m2 even when the IDE's own `mvn`
// runs honor the configured local repository. A `-Dmaven.repo.local`
// the user put in their own jdtls VM options wins.
if let Some(repo) = maven_local_repository(root, s) {
let arg = format!("-Dmaven.repo.local={}", repo.to_string_lossy());
let taken = cfg.args.iter().enumerate().any(|(i, a)| {
+1 -1
Переглянути файл
@@ -1508,7 +1508,7 @@ mod kotlin_bridge_bundle_tests {
/// Installs the app-owned JDT LS command bundle, falling back to ordinary LSP on IO failure.
pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
let extension = data_dir.join("java-usages-1.12.0.jar");
let extension = data_dir.join("java-usages-1.9.0.jar");
let bytes = include_bytes!("../../../java/java-usages/openidea-java-usages.jar");
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
clean_usages_bundles(data_dir, &extension);
-47
Переглянути файл
@@ -208,53 +208,6 @@ fn jdtls_honors_the_configured_maven_local_repository() {
assert!(cfg.args.iter().all(|a| !a.contains("maven.repo.local")));
}
#[test]
fn jdtls_m2e_gets_effective_settings_with_local_repository() {
fn user_settings(cfg: &LanguageServerConfig) -> Option<std::path::PathBuf> {
let opts = serde_json::to_value(cfg.initialization_options.clone()?).ok()?;
opts.pointer("/settings/java/configuration/maven/userSettings")?.as_str().map(std::path::PathBuf::from)
}
// Configured repository, no user settings: a derived file is passed (#1739).
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("m2-repo");
let mut s = Settings::default();
s.languages.java.maven.local_repository = repo.to_string_lossy().into_owned();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
let derived = tmp.path().join(".openidea").join("maven-settings.xml");
assert_eq!(user_settings(&cfg), Some(derived.clone()));
let text = std::fs::read_to_string(&derived).unwrap();
assert!(text.contains(&format!("<localRepository>{}</localRepository>", repo.to_string_lossy())));
// Stable across runs (no rewrite churn).
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(user_settings(&cfg), Some(derived.clone()));
// User settings without `<localRepository>`: the derived copy keeps the
// user's mirrors and gains the configured repository.
let settings = tmp.path().join("mine.xml");
std::fs::write(&settings, "<settings><mirrors><mirror><id>m</id></mirror></mirrors></settings>").unwrap();
s.languages.java.maven.user_settings = settings.to_string_lossy().into_owned();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(user_settings(&cfg), Some(derived.clone()));
let text = std::fs::read_to_string(&derived).unwrap();
assert!(text.contains("<mirror><id>m</id></mirror>"));
assert!(text.contains(&format!("<localRepository>{}</localRepository>", repo.to_string_lossy())));
// User settings already declaring `<localRepository>`: passed through untouched.
std::fs::write(&settings, "<settings><localRepository>/user/repo</localRepository></settings>").unwrap();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(user_settings(&cfg), Some(settings.clone()));
// Neither configured: no userSettings at all.
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &Settings::default());
assert_eq!(user_settings(&cfg), None);
}
#[test]
fn rust_analyzer_check_command_and_toolchain() {
if cfg!(windows) {
-42
Переглянути файл
@@ -1,42 +0,0 @@
# Open scripts from Unity
OpenIDEA can open scripts and Console source locations without a Unity plugin.
1. In Unity, open **Edit > Preferences > External Tools** (on macOS,
**Unity > Settings/Preferences > External Tools**).
2. Under **External Script Editor**, choose **Browse** and select OpenIDEA's
executable (or its `.app` on macOS).
3. Set **External Script Editor Args** to:
```text
$(ProjectPath) --file $(File) --line $(Line) --column $(Column)
```
Unity 2022.3 quotes the expanded project and file paths itself, including paths
with spaces. Do not add another pair of quotes around these placeholders.
Double-click a script in the Project window or a source location in the Console.
OpenIDEA opens the project and file, or focuses its existing project window, then
places the caret at the supplied location. Other open tabs stay in place.
The project argument makes cold launches open the Unity project rather than a
standalone file. Without it, `--file` opens in an existing matching project window
or in LightEdit. Relative file paths resolve against the supplied project folder,
or against the launch working directory when no project is supplied.
For a direct invocation of the application executable, quote paths as required
by your shell. The separately installed `openidea` command has its own syntax:
```text
/path/to/openidea "/path/to/My Game" --file "/path/to/My Game/Assets/Player.cs" --line 12 --column 5
```
`--file=...`, `--line=...` and `--column=...` also work. Lines and columns are
1-based; Unity's `0` and `-1` mean an unknown position. An omitted or unknown
column uses the start of the line. Without a known line, the file opens without
an explicit caret position. Invalid arguments and missing files report an error.
On Windows, use the same permissions for Unity and OpenIDEA when possible.
If a running instance does not receive a request, restart both applications with
matching permissions and retry. This integration opens local projects; it does
not generate C# project files or attach a debugger.
-20
Переглянути файл
@@ -340,23 +340,3 @@ test("selects through code blocks and tables while keeping copy controls outside
await copies.last().click();
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(flow);
});
test("keeps mermaid `<style>` rules scoped to the rendered svg after id rewriting", async ({ page }) => {
const diagram = [
"```mermaid",
"%%{init: {'theme': 'base', 'flowchart': {'htmlLabels': false, 'curve': 'basis'}}}%%",
"flowchart TB",
' subgraph T1["Tier 1"]',
" A[(Local)] <--> B[(Peer)]",
" end",
' subgraph T2["Tier 2"]',
" C[(Host RAM)]",
" end",
' C -->|"PCIe"| A',
"```",
].join("\n");
const reply = await openReply(page, `Diagram:\n\n${diagram}`);
await expect(reply.locator("[data-mermaid-state='ok'] .mermaid-output svg")).toBeVisible();
expect(await css(reply, ".cluster rect", "fill")).not.toBe("rgb(0, 0, 0)");
expect(await css(reply, ".flowchart-link", "fill")).toBe("none");
});
-32
Переглянути файл
@@ -1,32 +0,0 @@
import { expect, openFromTree, test } from "./fixtures";
/** The end of a long line must stay visible: the floating corner widgets leave it room. */
test("the inspection widget does not cover the end of a long line", async ({ workbench: page }) => {
const editor = await openFromTree(page, "build.gradle.kts");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("x".repeat(600));
await expect(editor.locator(".cm-line")).toHaveCount(1);
await expect(editor.locator(".cm-openidea-corner")).toBeAttached();
const scroller = editor.locator(".cm-scroller");
await expect.poll(() => scroller.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeGreaterThan(0);
await scroller.evaluate((el) => {
el.scrollLeft = el.scrollWidth;
});
const rects = await editor.evaluate((el) => {
const line = el.querySelector(".cm-line")!;
const range = document.createRange();
range.selectNodeContents(line);
return {
textRight: range.getBoundingClientRect().right,
cornerLeft: el.querySelector(".cm-openidea-corner")!.getBoundingClientRect().left,
scrollLeft: el.querySelector(".cm-scroller")!.scrollLeft,
};
});
// Scrolled as far right as it goes, and the last character sits left of the widget.
expect(rects.scrollLeft).toBeGreaterThan(0);
expect(rects.cornerLeft).toBeGreaterThan(rects.textRight);
});
-124
Переглянути файл
@@ -18,7 +18,6 @@ interface Opts {
alignChanges?: boolean;
syncScroll?: boolean;
collapse?: boolean;
softWrap?: boolean;
ignore?: "none" | "trim" | "whitespace" | "whitespaceAndLines";
}
@@ -351,126 +350,3 @@ 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,17 +61,6 @@ const FUNCS = ["parse", "format", "validate", "render", "save"].map(
const MINIFIED = Array.from({ length: 2_000 }, (_, i) => `var a${i}=f(${i},"k${i}");`).join("");
export const CASES: readonly DiffCase[] = [
{
path: "src/soft-wrap.ts",
before:
`// ${"long original text ".repeat(100)}\n` +
lines(150, (i) => `const value${i} = ${i};`) +
`// ${"old tail ".repeat(100)}\n`,
after:
`// ${"long changed text ".repeat(160)}\n` +
lines(150, (i) => `const value${i} = ${i};`) +
`// ${"new changed tail ".repeat(180)}\n`,
},
// A word edited and a comment added: one modified block (the reported case).
{ path: "src/options.ts", before: OPTIONS_BEFORE, after: OPTIONS_AFTER },
{
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.12.0
Bundle-Version: 1.9.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+2 -17
Переглянути файл
@@ -27,11 +27,6 @@ from directory names. References, rename and incoming calls leave those files cl
and only widen with the remaining candidates. A missing or failing command retains
widening. The result is query-local, so imports and classpath changes need no cache invalidation.
`openidea.workspace.coveredRoots()` returns the URIs of source folders whose Java files the search
scope covers all: no exclusion patterns, no inclusion pattern other than Maven's `**/*.java`, and
enclosed by the test-source policy. The client does not read the files under them when it looks
for candidates, which on a large project took most of a cached search's time.
## Search plan and access semantics
For source fields on the verified JDT LS implementation, a single plan merges
@@ -63,14 +58,7 @@ traversals. It indexes only requested exact AST ranges and verified invocation
selector-to-call-end spans; duplicate, recovered, malformed or uncontained ranges
fall back to NodeFinder. Method references do not get invocation aliases. Source
snapshot checks remain per result, and the index is discarded after the query.
Answers are cached by their search targets (JDT handles, kinds, declarations), the scope and the
search settings, together with a digest of the editors' unsaved contents, until a Java element
delta reports a change to the sources, a compilation unit or a classpath (`UsageCache`). Opening
or closing an editor and decompiled library classes' private working copies do not invalidate
them. A usage count and the usages shown when it is clicked, or the same search run again, need
no second search, and concurrent requests for the same targets share one. There is no
binding-resolution shortcut.
There is no cross-request cache or binding-resolution shortcut.
Popup and Find share persisted read/write toolbar switches. Both initially show;
turning the last one off automatically enables the other. Unknown and readWrite
@@ -88,7 +76,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.12.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.9.0.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
@@ -130,9 +118,6 @@ longer resolves every Spring Boot property again; its reproducible SHA-256 is
Version 1.9.0 adds the analysis-scope command to avoid redundant semantic queries;
its reproducible SHA-256 is
`ae04182d6a86dfdd6f6befaaeb28907fd9e4c022ceedb445f0b32ea917dca379`.
Version 1.12.0 caches usages answers until the Java model or an unsaved edit changes and adds
`openidea.workspace.coveredRoots`; its reproducible SHA-256 is
`c1bd28d7b956cb64af3e936aac0553413a5dc5fd373a043ddba003009e0ea783`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
Бінарний файл не відображається.
-3
Переглянути файл
@@ -4,9 +4,6 @@
<delegateCommandHandler class="ai.openidea.usages.CoveredFilesCommand">
<command id="openidea.workspace.coveredFiles"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.usages.CoveredRootsCommand">
<command id="openidea.workspace.coveredRoots"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.usages.UsagesCommand">
<command id="openidea.java.usages"/>
</delegateCommandHandler>
-51
Переглянути файл
@@ -1,51 +0,0 @@
package ai.openidea.usages;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.managers.ProjectsManager;
import org.eclipse.jdt.ls.core.internal.preferences.Preferences.SearchScope;
/**
* Directories whose Java files are all in the workspace's semantic source searches: source
* folders without inclusion or exclusion patterns that the search scope encloses. A client
* looking for files beyond that scope need not read the files under them.
*/
public final class CoveredRootsCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
var setting = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().getSearchScope();
var scope = SearchEngine.createJavaSearchScope(setting == SearchScope.main, projects,
IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS);
List<String> covered = new ArrayList<>();
for (IJavaProject project : projects) {
// The default project holds standalone open files, not an indexed source tree.
if (ProjectsManager.getDefaultProject().equals(project.getProject())) continue;
for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
if (monitor.isCanceled()) throw new OperationCanceledException();
if (root.getKind() != IPackageFragmentRoot.K_SOURCE || root.getResource() == null) continue;
IClasspathEntry entry = root.getRawClasspathEntry();
if (entry == null || entry.getExclusionPatterns().length > 0) continue;
// Maven projects include `**/*.java`: every Java file, like no pattern at all.
boolean allJava = true;
for (var pattern : entry.getInclusionPatterns()) allJava &= pattern.toString().equals("**/*.java");
if (!allJava) continue;
if (!scope.encloses(root)) continue;
var location = root.getResource().getLocationURI();
if (location != null) covered.add(location.toString());
}
}
return covered;
}
}
-157
Переглянути файл
@@ -1,157 +0,0 @@
package ai.openidea.usages;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.managers.ProjectsManager;
/**
* Answers of `openidea.java.usages` by search targets, kept until a Java element changes: the
* sources or unsaved edits of a compilation unit, or a project's classpath. A usage count and
* the usages shown when it is clicked, or the same search run again, then need no new search.
* Concurrent requests for the same targets share one search.
*/
final class UsageCache {
private static final int MAX_ENTRIES = 32, MAX_ROWS = 200_000;
/** Opening or closing an editor's working copy and AST-only reconciles change no usage. */
private static final int IGNORED_FLAGS = IJavaElementDelta.F_CHILDREN | IJavaElementDelta.F_PRIMARY_WORKING_COPY
| IJavaElementDelta.F_AST_AFFECTED | IJavaElementDelta.F_FINE_GRAINED;
private static final AtomicLong REVISION = new AtomicLong();
private record Entry(long revision, List<Map<String, Object>> rows) {}
private static final Map<String, Entry> DONE = new LinkedHashMap<>(16, 0.75f, true);
private static final Map<String, CompletableFuture<List<Map<String, Object>>>> RUNNING = new HashMap<>();
static {
JavaCore.addElementChangedListener(event -> {
if (affects(event.getDelta())) REVISION.incrementAndGet();
}, ElementChangedEvent.POST_CHANGE | ElementChangedEvent.POST_RECONCILE);
}
private UsageCache() {}
interface Search {
List<Map<String, Object>> run() throws Exception;
}
static boolean affects(IJavaElementDelta delta) {
// Decompiled library classes open as private working copies; searches never see them.
if (delta.getElement() instanceof ICompilationUnit unit && unit.getOwner() != null) return false;
// Files outside the source folders (opened to widen a search) join the default project
// while open: they are part of the key instead (`openContents`).
IJavaProject project = delta.getElement().getJavaProject();
if (project != null && standalone(project)) return false;
int flags = delta.getFlags() & ~IGNORED_FLAGS;
if (delta.getElement().getElementType() < IJavaElement.COMPILATION_UNIT) flags &= ~IJavaElementDelta.F_CONTENT;
if (delta.getKind() != IJavaElementDelta.CHANGED || flags != 0) return true;
for (IJavaElementDelta child : delta.getAffectedChildren()) if (affects(child)) return true;
return false;
}
static List<Map<String, Object>> get(String targets, IProgressMonitor monitor, Search search) throws Exception {
// Searches read unsaved editor contents, which change before the reconcile that reports them.
String key = targets + '|' + openContents(monitor);
while (true) {
long revision = REVISION.get();
CompletableFuture<List<Map<String, Object>>> running;
boolean owner = false;
synchronized (UsageCache.class) {
Entry done = DONE.get(key);
if (done != null && done.revision == revision) return done.rows;
running = RUNNING.get(key);
if (running == null) {
running = new CompletableFuture<>();
RUNNING.put(key, running);
owner = true;
}
}
if (owner) return search(key, revision, running, search);
// The same targets are searched for another request: its answer, or a new search
// when that one was cancelled, failed or saw a change.
while (true) {
if (monitor.isCanceled()) throw new OperationCanceledException();
try {
List<Map<String, Object>> rows = running.get(50, TimeUnit.MILLISECONDS);
if (REVISION.get() == revision) return rows;
break;
} catch (TimeoutException e) {
continue;
} catch (ExecutionException e) {
break;
}
}
}
}
private static boolean standalone(IJavaProject project) {
return ProjectsManager.getDefaultProject().equals(project.getProject());
}
/** A digest of the editors' unsaved contents and of the open files outside the source
* folders: merely opening or closing a file of the sources keeps it. */
private static String openContents(IProgressMonitor monitor) throws Exception {
Map<String, ICompilationUnit> copies = new TreeMap<>();
for (ICompilationUnit copy : JavaCore.getWorkingCopies(null)) copies.put(copy.getPrimary().getHandleIdentifier(), copy);
for (ICompilationUnit copy : JavaCore.getWorkingCopies(JavaLanguageServerPlugin.getInstance().getWorkingCopyOwner()))
copies.put(copy.getPrimary().getHandleIdentifier(), copy);
var digest = MessageDigest.getInstance("SHA-256");
for (var entry : copies.entrySet()) {
if (monitor.isCanceled()) throw new OperationCanceledException();
ICompilationUnit copy = entry.getValue();
if (!copy.hasUnsavedChanges() && !standalone(copy.getJavaProject())) continue;
digest.update(entry.getKey().getBytes(StandardCharsets.UTF_8));
String source = entry.getValue().getSource();
if (source != null) digest.update(source.getBytes(StandardCharsets.UTF_8));
}
return HexFormat.of().formatHex(digest.digest());
}
private static List<Map<String, Object>> search(String key, long revision,
CompletableFuture<List<Map<String, Object>>> running, Search search) throws Exception {
List<Map<String, Object>> rows;
try {
rows = List.copyOf(search.run());
} catch (Throwable e) {
synchronized (UsageCache.class) { RUNNING.remove(key); }
running.completeExceptionally(e);
throw e;
}
synchronized (UsageCache.class) {
RUNNING.remove(key);
if (REVISION.get() == revision && rows.size() <= MAX_ROWS) remember(key, new Entry(revision, rows));
}
running.complete(rows);
return rows;
}
private static void remember(String key, Entry entry) {
DONE.put(key, entry);
int rows = DONE.values().stream().mapToInt(e -> e.rows.size()).sum();
// Least recently used first; `get` on this access-ordered map would reorder it.
var oldest = DONE.entrySet().iterator();
while ((DONE.size() > MAX_ENTRIES || rows > MAX_ROWS) && oldest.hasNext()) {
var evicted = oldest.next();
if (evicted.getKey().equals(key)) continue;
rows -= evicted.getValue().rows.size();
oldest.remove();
}
}
}
+4 -25
Переглянути файл
@@ -92,34 +92,13 @@ public final class UsagesCommand implements IDelegateCommandHandler {
}
}
}
UsageCache.Search run = () -> respond(search, plan, results, monitor);
// Unverified builds answer partly through the native handler, before the plan.
return replicated && !plan.targets.isEmpty()
? UsageCache.get(cacheKey(plan, sources, preferences), monitor, run) : run.run();
for (var target : plan.targets.values()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
add(search, target.element, target.kind(), target.declarations, results, monitor);
}
} finally {
if (targetRoot != null) JDTUtils.discardClassFileWorkingCopy(targetRoot);
}
}
/** What a search depends on besides the Java model: its targets, scope and search settings. */
private static String cacheKey(SearchPlan plan, boolean sources,
org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager preferences) {
var settings = preferences.getPreferences();
StringBuilder key = new StringBuilder().append(sources).append('|').append(settings.getSearchScope())
.append('|').append(preferences.isClientSupportsClassFileContent() && settings.isIncludeDecompiledSources());
for (var target : plan.targets.values()) {
key.append('|').append(target.element.getHandleIdentifier()).append('#').append(target.kind())
.append('#').append(target.declarations);
}
return key.toString();
}
private static List<Map<String, Object>> respond(Search search, SearchPlan plan, Map<Location, String> results,
IProgressMonitor monitor) throws Exception {
for (var target : plan.targets.values()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
add(search, target.element, target.kind(), target.declarations, results, monitor);
}
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
List<Map<String, Object>> response = new ArrayList<>();
UsageAccess access = new UsageAccess(monitor, results);
-25
Переглянути файл
@@ -136,31 +136,6 @@ try:
line, text = next((i, t) for i, t in enumerate(source.splitlines()) if 'println' in t)
evidence['jdkSources'] = assert_sources(line, text.index('println'))
assert evidence['jdkSources'], 'no JDK method usages in the sources'
# Answers are reused until the sources change: an unsaved edit is seen at once, before its reconcile.
line, text = next((i, t) for i, t in enumerate(source.splitlines()) if 'private String name;' in t)
usages = lambda: request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),line,text.index('name'),False]})
getters = lambda rows: [r['kind'] for r in rows].count('getter')
first = usages()
assert usages() == first
edited = source.replace(' void calls(Bean b)', ' void more(Bean b) { b.getName(); }\n void calls(Bean b)')
send({'jsonrpc':'2.0','method':'textDocument/didChange','params':{'textDocument':{'uri':file.as_uri(),'version':2},'contentChanges':[{'text':edited}]}})
changed = usages()
assert getters(changed) == getters(first) + 1, (first, changed)
send({'jsonrpc':'2.0','method':'textDocument/didChange','params':{'textDocument':{'uri':file.as_uri(),'version':3},'contentChanges':[{'text':source}]}})
assert usages() == first
# The source folder holds only covered files; the folder beside it does not.
roots = request('workspace/executeCommand', {'command':'openidea.workspace.coveredRoots','arguments':[]})
assert [pathlib.Path(r.replace('file:', '', 1)).resolve() for r in roots] == [(project / 'src').resolve()], roots
evidence['coveredRoots'] = roots
# A file outside the source folders, opened and closed to widen a search, leaves the answer as it was.
extra = project / 'other' / 'Extra.java'
extra.parent.mkdir()
extra.write_text('class Extra { void use(Bean b) { b.getName(); } }\n')
send({'jsonrpc':'2.0','method':'textDocument/didOpen','params':{'textDocument':{'uri':extra.as_uri(),'languageId':'java','version':1,'text':extra.read_text()}}})
widened = usages()
send({'jsonrpc':'2.0','method':'textDocument/didClose','params':{'textDocument':{'uri':extra.as_uri()}}})
assert usages() == first
evidence['cached'] = {'first':first, 'edited':changed, 'widened':widened}
# Respect the existing global preference: the command must not switch it on.
send({'jsonrpc':'2.0','method':'workspace/didChangeConfiguration','params':{'settings':{'java':{'references':{'includeAccessors':False}}}}})
disabled = request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),3,19,False]})
-3
Переглянути файл
@@ -43,9 +43,6 @@ contentProvider = { preferred = "fernflowerContentProvider" }
maven = { downloadSources = true, updateSnapshots = false }
eclipse = { downloadSources = true }
references = { includeDecompiledSources = true }
# The editor's usage lenses count usages; the server's own lenses would search every
# declaration of the file again, all at once (on by default in JDT LS).
referencesCodeLens = { enabled = false }
signatureHelp = { enabled = true }
symbols = { includeGeneratedCode = true }
configuration = { updateBuildConfiguration = "automatic" }
+2 -23
Переглянути файл
@@ -3,8 +3,8 @@
use crate::state::AppState;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_docker::{
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
ComposeOp, ContainerOp, DockerEndpoint, DockerEvent, DockerLogLine, DockerObject, DockerRegistry, DockerSettings,
DockerSnapshot, PruneTarget, RegistryAuth,
};
use tauri::State;
use tauri::ipc::Channel;
@@ -56,27 +56,6 @@ pub async fn docker_inspect(endpoint: DockerEndpoint, object: DockerObject, id:
blocking(move || ide_docker::inspect(&endpoint, object, &id)).await
}
/// Layers of an image (`docker image history`).
#[tauri::command]
#[specta::specta]
pub async fn docker_image_history(endpoint: DockerEndpoint, id: String) -> IdeResult<Vec<DockerImageLayer>> {
blocking(move || ide_docker::image_history(&endpoint, &id)).await
}
/// Processes running inside a container (`docker top`).
#[tauri::command]
#[specta::specta]
pub async fn docker_container_top(endpoint: DockerEndpoint, id: String) -> IdeResult<DockerProcessList> {
blocking(move || ide_docker::container_top(&endpoint, &id)).await
}
/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`).
#[tauri::command]
#[specta::specta]
pub async fn docker_container_stats(endpoint: DockerEndpoint, id: String) -> IdeResult<DockerContainerStats> {
blocking(move || ide_docker::container_stats(&endpoint, &id)).await
}
/// Streams a container's log lines until it stops or the request is cancelled.
#[tauri::command]
#[specta::specta]
-4
Переглянути файл
@@ -447,7 +447,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
window::window_is_fullscreen,
window_drag::window_start_drag,
window::window_take_launch,
window::window_complete_launch,
window::window_close_context,
window::window_open_projects,
window::app_quit,
@@ -564,9 +563,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
docker::docker_container_op,
docker::docker_remove,
docker::docker_inspect,
docker::docker_image_history,
docker::docker_container_top,
docker::docker_container_stats,
docker::docker_logs,
docker::docker_events,
docker::docker_pull,
-8
Переглянути файл
@@ -163,14 +163,6 @@ pub fn window_take_launch(window: WebviewWindow, windows: State<'_, WindowsState
windows.take_launch(window.label())
}
/// Release the opening window's reservation after navigation or cancellation.
#[tauri::command]
#[specta::specta]
pub fn window_complete_launch(window: WebviewWindow, windows: State<'_, WindowsState>) -> IdeResult<()> {
windows.complete_launch(window.label());
Ok(())
}
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct OpenProject {
+15 -12
Переглянути файл
@@ -102,7 +102,7 @@ pub fn run() {
#[cfg(debug_assertions)]
export_bindings(&builder);
let app = tauri::Builder::default().manage(WindowsState::default());
let app = tauri::Builder::default();
// Single instance first: a second launch focuses this one and opens its path argument.
// Debug builds have a separate identifier per worktree.
let app = app.plugin(tauri_plugin_single_instance::init(windows::on_second_instance));
@@ -176,22 +176,26 @@ pub fn run() {
.setup(move |app| {
builder.mount_events(app);
let state = AppState::new(app.handle().clone())?;
let windows = app.state::<WindowsState>();
let windows = WindowsState::default();
if let Ok(cwd) = std::env::current_dir() {
match windows::cli_launch(&std::env::args().collect::<Vec<_>>(), &cwd) {
Ok(Some(launch)) => windows.set_launch("main", launch),
Ok(None) => {}
Err(error) => windows::report_cli_error(app.handle(), error),
let args = std::env::args().collect::<Vec<_>>();
match windows::cli_launch(&args, &cwd) {
Some(windows::CliLaunch::Path(path)) => {
windows::remember_cli_position(&windows, &args, &path);
windows.set_launch("main", windows::path_launch(path));
}
// `openidea diff a.txt b.txt`: the main window opens the pair in the diff viewer.
Some(windows::CliLaunch::Diff(diff)) => {
windows.set_launch("main", windows::Launch { diff: Some(Box::new(diff)), ..Default::default() });
}
None => {}
}
}
let menu_state = menu::MenuState::default();
menu::install(app.handle(), &menu_state, &state.recent.list());
app.manage(state);
commands::mcp::apply(&app.state::<AppState>());
#[cfg(windows)]
if let Err(error) = windows::allow_external_launches(app.handle()) {
windows::report_cli_error(app.handle(), error);
}
app.manage(windows);
app.manage(application_focus::ApplicationFocus::default());
#[cfg(target_os = "macos")]
macos::intercept_system_quit(app.handle());
@@ -208,7 +212,6 @@ pub fn run() {
}
app.on_menu_event(on_menu_event);
windows::create_main_window(app.handle())?;
windows::ready_for_cli(app.handle());
jump_list::refresh(app.handle(), app.state::<AppState>().recent.list());
Ok(())
})
@@ -259,7 +262,7 @@ pub fn run() {
#[cfg(target_os = "macos")]
if let tauri::RunEvent::Opened { urls } = &event {
let paths = windows::opened_paths(urls);
if app.try_state::<AppState>().is_some() {
if app.try_state::<WindowsState>().is_some() {
windows::open_paths(app, paths);
} else {
early_opens.lock().get_or_insert_default().extend(paths);
-19
Переглянути файл
@@ -395,7 +395,6 @@ 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"),
@@ -1653,24 +1652,6 @@ mod tests {
}
}
#[test]
fn soft_wrap_is_available_under_view_active_editor_on_every_os() {
for os in ALL_OS {
let menus = spec(os);
let Entry::Submenu { children: view, .. } =
menus.iter().find(|e| matches!(e, Entry::Submenu { id: "view", .. })).unwrap()
else {
panic!("View menu missing")
};
let Entry::Submenu { children: active, .. } =
view.iter().find(|e| matches!(e, Entry::Submenu { id: "activeEditor", .. })).unwrap()
else {
panic!("Active Editor menu missing")
};
assert!(action_ids(active).contains(&"editor.toggleSoftWrap"), "{os:?}");
}
}
#[test]
fn unchanged_menu_config_is_not_rebuilt() {
let state = MenuState::default();
File diff suppressed because it is too large. Load diff
-227
Переглянути файл
@@ -1,227 +0,0 @@
//! External file-opening arguments, shared by cold and second-instance launches.
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
/// Guarded by WindowsState's mutex. One worker drains requests in arrival order.
#[derive(Default)]
pub struct Queue {
requests: VecDeque<(Vec<String>, String)>,
ready: bool,
running: bool,
}
impl Queue {
pub fn push(&mut self, args: Vec<String>, cwd: String) -> bool {
self.requests.push_back((args, cwd));
self.start()
}
pub fn ready(&mut self) -> bool {
self.ready = true;
self.start()
}
fn start(&mut self) -> bool {
if self.ready && !self.running && !self.requests.is_empty() {
self.running = true;
true
} else {
false
}
}
pub fn next(&mut self) -> Option<(Vec<String>, String)> {
let request = self.requests.pop_front();
if request.is_none() {
self.running = false;
}
request
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Request {
pub path: Option<PathBuf>,
pub file: Option<PathBuf>,
pub position: Option<(u32, u32)>,
}
/// Preserve the application's `diff` subcommand; a non-leading `diff` remains a path.
pub fn diff_paths(args: &[String], cwd: &Path) -> Option<Vec<PathBuf>> {
if args.get(1).map(String::as_str) != Some("diff") {
return None;
}
let mut paths = Vec::new();
let mut args = args.iter().skip(2);
let mut positional = false;
while let Some(arg) = args.next() {
if !positional && arg == "--" {
positional = true;
} else if !positional && matches!(arg.as_str(), "--line" | "--column") {
args.next();
} else if !arg.is_empty() && (positional || !arg.starts_with('-')) {
paths.push(absolute(cwd, Path::new(arg)));
}
}
Some(paths)
}
pub fn parse(args: &[String], cwd: &Path) -> Result<Request, String> {
let (mut path, mut file, mut line, mut column) = (None, None, None, None);
let mut positional = false;
let mut args = args.iter().skip(1);
while let Some(arg) = args.next() {
if !positional && arg == "--" {
positional = true;
continue;
}
let (flag, inline) = arg.split_once('=').map_or((arg.as_str(), None), |(k, v)| (k, Some(v)));
if !positional && matches!(flag, "--file" | "--line" | "--column") {
let value = inline
.or_else(|| args.next().map(String::as_str))
.filter(|s| !s.is_empty() && !s.starts_with("--"))
.ok_or_else(|| format!("{flag} requires a value"))?;
match flag {
"--file" => {
if file.replace(PathBuf::from(value)).is_some() {
return Err("--file may only be supplied once".into());
}
}
"--line" => line = coordinate(flag, value)?,
"--column" => column = coordinate(flag, value)?,
_ => unreachable!(),
}
} else if !arg.is_empty() && (positional || (!arg.starts_with('-') && !arg.starts_with("psn_"))) {
// Preserve ordinary CLI opening: the first positional path is the target.
if path.is_none() {
path = Some(absolute(cwd, Path::new(arg)));
}
}
}
let base = path.as_deref().filter(|p| p.is_dir()).unwrap_or(cwd);
let file = file.map(|p| absolute(base, &p));
Ok(Request { path, file, position: line.map(|l| (l - 1, column.unwrap_or(1) - 1)) })
}
fn absolute(base: &Path, path: &Path) -> PathBuf {
if path.is_absolute() { path.to_owned() } else { base.join(path) }
}
fn coordinate(flag: &str, value: &str) -> Result<Option<u32>, String> {
// Unity supplies 0/-1 when an asset has no source position.
match value.parse::<i64>() {
Ok(-1 | 0) => Ok(None),
Ok(n @ 1..=4294967295) => Ok(Some(n as u32)),
_ => Err(format!("{flag} expects a 1-based position (or 0/-1 for an unknown position)")),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn request(args: &[&str]) -> Result<Request, String> {
parse(
&std::iter::once("openidea").chain(args.iter().copied()).map(str::to_owned).collect::<Vec<_>>(),
Path::new("/work"),
)
}
#[test]
fn diff_paths_keep_flags_out_and_honor_end_of_options() {
let args = |tail: &[&str]| {
std::iter::once("openidea").chain(tail.iter().copied()).map(str::to_owned).collect::<Vec<_>>()
};
let cwd = Path::new("/work");
assert_eq!(
diff_paths(&args(&["diff", "--line", "12", "--column=3", "a.txt", "b.txt"]), cwd),
Some(vec![cwd.join("a.txt"), cwd.join("b.txt")])
);
assert_eq!(
diff_paths(&args(&["diff", "--", "-a.txt", "-b.txt"]), cwd),
Some(vec![cwd.join("-a.txt"), cwd.join("-b.txt")])
);
assert_eq!(diff_paths(&args(&["--", "diff"]), cwd), None);
assert_eq!(diff_paths(&args(&["project", "diff"]), cwd), None);
assert_eq!(diff_paths(&args(&["diff"]), cwd), Some(vec![]));
}
#[test]
fn queued_launches_stay_in_order_across_startup_and_later_arrivals() {
let mut queue = Queue::default();
assert!(!queue.push(vec!["first".into()], "cwd1".into()));
assert!(!queue.push(vec!["second".into()], "cwd2".into()));
assert!(queue.ready());
assert!(!queue.push(vec!["third".into()], "cwd3".into()));
assert_eq!(queue.next(), Some((vec!["first".into()], "cwd1".into())));
assert_eq!(queue.next(), Some((vec!["second".into()], "cwd2".into())));
assert_eq!(queue.next(), Some((vec!["third".into()], "cwd3".into())));
assert_eq!(queue.next(), None);
assert!(queue.push(vec!["later".into()], "cwd4".into()));
assert!(!queue.ready());
assert_eq!(queue.next(), Some((vec!["later".into()], "cwd4".into())));
}
#[test]
fn named_files_positions_and_unicode() {
for args in [
vec!["--file", "Game Scripts/角色.cs", "--line", "42", "--column", "7"],
vec!["--column=7", "--line=42", "--file=Game Scripts/角色.cs"],
] {
assert_eq!(
request(&args).unwrap(),
Request {
path: None,
file: Some(PathBuf::from("/work/Game Scripts/角色.cs")),
position: Some((41, 6)),
}
);
}
assert_eq!(request(&["--line=5", "file.cs"]).unwrap().position, Some((4, 0)));
}
#[test]
fn unknown_positions_and_malformed_flags() {
for value in ["0", "-1"] {
assert_eq!(request(&["--file", "a.cs", "--line", value, "--column", value]).unwrap().position, None);
assert_eq!(request(&["--file", "a.cs", "--line", "5", "--column", value]).unwrap().position, Some((4, 0)));
}
for args in [
vec!["--file"],
vec!["--file="],
vec!["--file", "--line", "2"],
vec!["--line", "bad", "a.cs"],
vec!["--line=4294967296", "a.cs"],
vec!["--column=-2", "a.cs"],
vec!["--file=a.cs", "--file=b.cs"],
] {
assert!(request(&args).is_err(), "{args:?}");
}
}
#[test]
fn positional_opening_and_end_of_options() {
assert_eq!(request(&["--verbose", "proj"]).unwrap().path, Some(PathBuf::from("/work/proj")));
assert_eq!(request(&["--", "-notes.txt"]).unwrap().path, Some(PathBuf::from("/work/-notes.txt")));
assert_eq!(request(&["-psn_0_123"]).unwrap(), Request::default());
assert_eq!(request(&["--column", "7", "a.cs"]).unwrap().position, None);
}
#[test]
fn project_relative_file_is_independent_of_invocation_directory() {
let project = std::env::temp_dir();
let args = vec!["openidea".into(), project.to_string_lossy().into_owned(), "--file=Assets/A.cs".into()];
let r = parse(&args, Path::new("/unrelated")).unwrap();
assert_eq!(r.path, Some(project.clone()));
assert_eq!(r.file, Some(project.join("Assets/A.cs")));
}
#[test]
#[cfg(windows)]
fn windows_absolute_paths_are_not_prefixed() {
for file in [r"D:\Game Scripts\角色.cs", r"\\server\share\Game\A.cs", "D:/Game Scripts/A.cs"] {
assert_eq!(request(&["--file", file]).unwrap().file, Some(PathBuf::from(file)));
}
}
}
-41
Переглянути файл
@@ -1,41 +0,0 @@
//! Receive external file-open requests when the editor has a higher integrity level.
use ide_core::{IdeError, IdeResult};
use tauri::AppHandle;
use windows_sys::Win32::UI::WindowsAndMessaging::{
ChangeWindowMessageFilterEx, FindWindowW, GetWindowThreadProcessId, MSGFLT_ALLOW, WM_COPYDATA,
};
/// Called after the single-instance plugin creates its receiver and app state is ready.
pub fn allow_external_launches(app: &AppHandle) -> IdeResult<()> {
// tauri-plugin-single-instance names its receiver using the configured identifier,
// including the worktree suffix in debug builds. Never change a webview's filter.
let identifier = &app.config().identifier;
let class: Vec<u16> = format!("{identifier}-sic").encode_utf16().chain(Some(0)).collect();
let title: Vec<u16> = format!("{identifier}-siw").encode_utf16().chain(Some(0)).collect();
// SAFETY: both strings are NUL-terminated. Check ownership before allowing the
// plugin's argument-transfer message on this one window.
unsafe {
let receiver = FindWindowW(class.as_ptr(), title.as_ptr());
if receiver.is_null() {
return Err(IdeError::unavailable("Cannot find the single-instance receiver for external editor requests"));
}
let mut owner = 0;
if GetWindowThreadProcessId(receiver, &mut owner) == 0 {
return Err(IdeError::unavailable(format!(
"Cannot identify the single-instance receiver: {}",
std::io::Error::last_os_error()
)));
}
if owner != std::process::id() {
return Err(IdeError::unavailable("The single-instance receiver belongs to another process"));
}
if ChangeWindowMessageFilterEx(receiver, WM_COPYDATA, MSGFLT_ALLOW, std::ptr::null_mut()) == 0 {
return Err(IdeError::unavailable(format!(
"Cannot enable external editor requests: {}. Run Unity and OpenIDEA with the same permissions.",
std::io::Error::last_os_error()
)));
}
}
Ok(())
}
-1
Переглянути файл
@@ -20,7 +20,6 @@
"windows": {
"nsis": {
"installMode": "both",
"template": "windows/installer.nsi",
"installerIcon": "icons/icon.ico",
"uninstallerIcon": "icons/icon.ico"
}
-997
Переглянути файл
@@ -1,997 +0,0 @@
; Based on tauri-bundler 2.10.3 (MIT OR Apache-2.0).
; https://github.com/tauri-apps/tauri/blob/tauri-bundler-v2.10.3/crates/tauri-bundler/src/bundle/windows/nsis/installer.nsi
; Preserve legacy install scope through UninstallString; keep the rest in sync with upstream.
Unicode true
ManifestDPIAware true
; Add in `dpiAwareness` `PerMonitorV2` to manifest for Windows 10 1607+ (note this should not affect lower versions since they should be able to ignore this and pick up `dpiAware` `true` set by `ManifestDPIAware true`)
; Currently undocumented on NSIS's website but is in the Docs folder of source tree, see
; https://github.com/kichik/nsis/blob/5fc0b87b819a9eec006df4967d08e522ddd651c9/Docs/src/attributes.but#L286-L300
; https://github.com/tauri-apps/tauri/pull/10106
ManifestDPIAwareness PerMonitorV2
!if "{{compression}}" == "none"
SetCompress off
!else
; Set the compression algorithm. We default to LZMA.
SetCompressor /SOLID "{{compression}}"
!endif
; Keep above !include to stay ahead of any plugin command
; see https://github.com/tauri-apps/tauri/pull/15422#discussion_r3289239624
{{#if signed_plugins_path}}
!addplugindir "{{signed_plugins_path}}"
{{/if}}
!include MUI2.nsh
!include FileFunc.nsh
!include x64.nsh
!include WordFunc.nsh
!include "utils.nsh"
!include "FileAssociation.nsh"
!include "Win\COM.nsh"
!include "Win\Propkey.nsh"
!include "Win\RestartManager.nsh"
!include "StrFunc.nsh"
${StrCase}
${StrLoc}
{{#if installer_hooks}}
!include "{{installer_hooks}}"
{{/if}}
!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
!define MANUFACTURER "{{manufacturer}}"
!define PRODUCTNAME "{{product_name}}"
!define VERSION "{{version}}"
!define VERSIONWITHBUILD "{{version_with_build}}"
!define HOMEPAGE "{{homepage}}"
!define INSTALLMODE "{{install_mode}}"
!define LICENSE "{{license}}"
!define INSTALLERICON "{{installer_icon}}"
!define SIDEBARIMAGE "{{sidebar_image}}"
!define HEADERIMAGE "{{header_image}}"
!define UNINSTALLERICON "{{uninstaller_icon}}"
!define UNINSTALLERHEADERIMAGE "{{uninstaller_header_image}}"
!define MAINBINARYNAME "{{main_binary_name}}"
!define MAINBINARYSRCPATH "{{main_binary_path}}"
!define BUNDLEID "{{bundle_id}}"
!define COPYRIGHT "{{copyright}}"
!define OUTFILE "{{out_file}}"
!define ARCH "{{arch}}"
!define ADDITIONALPLUGINSPATH "{{additional_plugins_path}}"
!define ALLOWDOWNGRADES "{{allow_downgrades}}"
!define DISPLAYLANGUAGESELECTOR "{{display_language_selector}}"
!define INSTALLWEBVIEW2MODE "{{install_webview2_mode}}"
!define WEBVIEW2INSTALLERARGS "{{webview2_installer_args}}"
!define WEBVIEW2BOOTSTRAPPERPATH "{{webview2_bootstrapper_path}}"
!define WEBVIEW2INSTALLERPATH "{{webview2_installer_path}}"
!define MINIMUMWEBVIEW2VERSION "{{minimum_webview2_version}}"
!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}"
!define MANUKEY "Software\${MANUFACTURER}"
!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}"
!define UNINSTALLERSIGNCOMMAND "{{uninstaller_sign_cmd}}"
!define ESTIMATEDSIZE "{{estimated_size}}"
!define STARTMENUFOLDER "{{start_menu_folder}}"
Var PassiveMode
Var UpdateMode
Var NoShortcutMode
Var WixMode
Var OldMainBinaryName
Name "${PRODUCTNAME}"
BrandingText "${COPYRIGHT}"
OutFile "${OUTFILE}"
; We don't actually use this value as default install path,
; it's just for nsis to append the product name folder in the directory selector
; https://nsis.sourceforge.io/Reference/InstallDir
!define PLACEHOLDER_INSTALL_DIR "placeholder\${PRODUCTNAME}"
InstallDir "${PLACEHOLDER_INSTALL_DIR}"
VIProductVersion "${VERSIONWITHBUILD}"
VIAddVersionKey "ProductName" "${PRODUCTNAME}"
VIAddVersionKey "FileDescription" "${PRODUCTNAME}"
VIAddVersionKey "LegalCopyright" "${COPYRIGHT}"
VIAddVersionKey "FileVersion" "${VERSION}"
VIAddVersionKey "ProductVersion" "${VERSION}"
# additional plugins
!addplugindir "${ADDITIONALPLUGINSPATH}"
; Uninstaller signing command
!if "${UNINSTALLERSIGNCOMMAND}" != ""
!uninstfinalize '${UNINSTALLERSIGNCOMMAND}'
!endif
; Handle install mode, `perUser`, `perMachine` or `both`
!if "${INSTALLMODE}" == "perMachine"
RequestExecutionLevel admin
!endif
!if "${INSTALLMODE}" == "currentUser"
RequestExecutionLevel user
!endif
!if "${INSTALLMODE}" == "both"
!define MULTIUSER_MUI
!define MULTIUSER_INSTALLMODE_INSTDIR "${PRODUCTNAME}"
!define MULTIUSER_INSTALLMODE_COMMANDLINE
!if "${ARCH}" == "x64"
!define MULTIUSER_USE_PROGRAMFILES64
!else if "${ARCH}" == "arm64"
!define MULTIUSER_USE_PROGRAMFILES64
!endif
!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}"
!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "UninstallString"
!define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME
!define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation
!define MULTIUSER_EXECUTIONLEVEL Highest
!include MultiUser.nsh
!endif
; Installer icon
!if "${INSTALLERICON}" != ""
!define MUI_ICON "${INSTALLERICON}"
!endif
; Installer sidebar image
!if "${SIDEBARIMAGE}" != ""
!define MUI_WELCOMEFINISHPAGE_BITMAP "${SIDEBARIMAGE}"
!endif
; Enable header images for installer and uninstaller pages when either image is configured.
!if "${HEADERIMAGE}" != ""
!define MUI_HEADERIMAGE
!else if "${UNINSTALLERHEADERIMAGE}" != ""
!define MUI_HEADERIMAGE
!endif
; Installer header image
!if "${HEADERIMAGE}" != ""
!define MUI_HEADERIMAGE_BITMAP "${HEADERIMAGE}"
!endif
; Uninstaller header image
!if "${UNINSTALLERHEADERIMAGE}" != ""
!define MUI_HEADERIMAGE_UNBITMAP "${UNINSTALLERHEADERIMAGE}"
!endif
; Uninstaller icon
!if "${UNINSTALLERICON}" != ""
!define MUI_UNICON "${UNINSTALLERICON}"
!endif
; Define registry key to store installer language
!define MUI_LANGDLL_REGISTRY_ROOT "HKCU"
!define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}"
!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language"
; Installer pages, must be ordered as they appear
; 1. Welcome Page
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MUI_PAGE_WELCOME
; 2. License Page (if defined)
!if "${LICENSE}" != ""
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MUI_PAGE_LICENSE "${LICENSE}"
!endif
; 3. Install mode (if it is set to `both`)
!if "${INSTALLMODE}" == "both"
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MULTIUSER_PAGE_INSTALLMODE
!endif
; 4. Custom page to ask user if he wants to reinstall/uninstall
; only if a previous installation was detected
Var ReinstallPageCheck
Page custom PageReinstall PageLeaveReinstall
Function PageReinstall
; Uninstall previous WiX installation if exists.
;
; A WiX installer stores the installation info in registry
; using a UUID and so we have to loop through all keys under
; `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`
; and check if `DisplayName` and `Publisher` keys match ${PRODUCTNAME} and ${MANUFACTURER}
;
; This has a potential issue that there maybe another installation that matches
; our ${PRODUCTNAME} and ${MANUFACTURER} but wasn't installed by our WiX installer,
; however, this should be fine since the user will have to confirm the uninstallation
; and they can chose to abort it if doesn't make sense.
StrCpy $0 0
wix_loop:
EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0
StrCmp $1 "" wix_loop_done ; Exit loop if there is no more keys to loop on
IntOp $0 $0 + 1
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName"
ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher"
StrCmp "$R0$R1" "${PRODUCTNAME}${MANUFACTURER}" 0 wix_loop
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "UninstallString"
${StrCase} $R1 $R0 "L"
${StrLoc} $R0 $R1 "msiexec" ">"
StrCmp $R0 0 0 wix_loop_done
StrCpy $WixMode 1
StrCpy $R6 "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1"
Goto compare_version
wix_loop_done:
; Check if there is an existing installation, if not, abort the reinstall page
ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
${IfThen} "$R0$R1" == "" ${|} Abort ${|}
; Compare this installar version with the existing installation
; and modify the messages presented to the user accordingly
compare_version:
StrCpy $R4 "$(older)"
${If} $WixMode = 1
ReadRegStr $R0 HKLM "$R6" "DisplayVersion"
${Else}
ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"
${EndIf}
${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|}
nsis_tauri_utils::SemverCompare "${VERSION}" $R0
Pop $R0
; Reinstalling the same version
${If} $R0 = 0
StrCpy $R1 "$(alreadyInstalledLong)"
StrCpy $R2 "$(addOrReinstall)"
StrCpy $R3 "$(uninstallApp)"
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(chooseMaintenanceOption)"
; Upgrading
${ElseIf} $R0 = 1
StrCpy $R1 "$(olderOrUnknownVersionInstalled)"
StrCpy $R2 "$(uninstallBeforeInstalling)"
StrCpy $R3 "$(dontUninstall)"
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
; Downgrading
${ElseIf} $R0 = -1
StrCpy $R1 "$(newerVersionInstalled)"
StrCpy $R2 "$(uninstallBeforeInstalling)"
!if "${ALLOWDOWNGRADES}" == "true"
StrCpy $R3 "$(dontUninstall)"
!else
StrCpy $R3 "$(dontUninstallDowngrade)"
!endif
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
${Else}
Abort
${EndIf}
; Skip showing the page if passive
;
; Note that we don't call this earlier at the beginning
; of this function because we need to populate some variables
; related to current installed version if detected and whether
; we are downgrading or not.
${If} $PassiveMode = 1
Call PageLeaveReinstall
${Else}
nsDialogs::Create 1018
Pop $R4
${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|}
${NSD_CreateLabel} 0 0 100% 24u $R1
Pop $R1
${NSD_CreateRadioButton} 30u 50u -30u 8u $R2
Pop $R2
${NSD_OnClick} $R2 PageReinstallUpdateSelection
${NSD_CreateRadioButton} 30u 70u -30u 8u $R3
Pop $R3
; Disable this radio button if downgrading and downgrades are disabled
!if "${ALLOWDOWNGRADES}" == "false"
${IfThen} $R0 = -1 ${|} EnableWindow $R3 0 ${|}
!endif
${NSD_OnClick} $R3 PageReinstallUpdateSelection
; Check the first radio button if this the first time
; we enter this page or if the second button wasn't
; selected the last time we were on this page
${If} $ReinstallPageCheck <> 2
SendMessage $R2 ${BM_SETCHECK} ${BST_CHECKED} 0
${Else}
SendMessage $R3 ${BM_SETCHECK} ${BST_CHECKED} 0
${EndIf}
${NSD_SetFocus} $R2
nsDialogs::Show
${EndIf}
FunctionEnd
Function PageReinstallUpdateSelection
${NSD_GetState} $R2 $R1
${If} $R1 == ${BST_CHECKED}
StrCpy $ReinstallPageCheck 1
${Else}
StrCpy $ReinstallPageCheck 2
${EndIf}
FunctionEnd
Function PageLeaveReinstall
${NSD_GetState} $R2 $R1
; If migrating from Wix, always uninstall
${If} $WixMode = 1
Goto reinst_uninstall
${EndIf}
; In update mode, always proceeds without uninstalling
${If} $UpdateMode = 1
Goto reinst_done
${EndIf}
; $R0 holds whether same(0)/upgrading(1)/downgrading(-1) version
; $R1 holds the radio buttons state:
; 1 => first choice was selected
; 0 => second choice was selected
${If} $R0 = 0 ; Same version, proceed
${If} $R1 = 1 ; User chose to add/reinstall
Goto reinst_done
${Else} ; User chose to uninstall
Goto reinst_uninstall
${EndIf}
${ElseIf} $R0 = 1 ; Upgrading
${If} $R1 = 1 ; User chose to uninstall
Goto reinst_uninstall
${Else}
Goto reinst_done ; User chose NOT to uninstall
${EndIf}
${ElseIf} $R0 = -1 ; Downgrading
${If} $R1 = 1 ; User chose to uninstall
Goto reinst_uninstall
${Else}
Goto reinst_done ; User chose NOT to uninstall
${EndIf}
${EndIf}
reinst_uninstall:
HideWindow
ClearErrors
${If} $WixMode = 1
ReadRegStr $R1 HKLM "$R6" "UninstallString"
ExecWait '$R1' $0
${Else}
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
ExecWait '$R1' $0
${EndIf}
BringToFront
${IfThen} ${Errors} ${|} StrCpy $0 2 ${|} ; ExecWait failed, set fake exit code
${If} $0 <> 0
${OrIf} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe"
; User cancelled wix uninstaller? return to select un/reinstall page
${If} $WixMode = 1
${AndIf} $0 = 1602
Abort
${EndIf}
; User cancelled NSIS uninstaller? return to select un/reinstall page
${If} $0 = 1
Abort
${EndIf}
; Other errors? show generic error message and return to select un/reinstall page
MessageBox MB_ICONEXCLAMATION "$(unableToUninstall)"
Abort
${EndIf}
; The NSIS uninstaller was run in place (`_?=`), so it cannot delete itself
; and the install directory, clean them up here once the uninstall succeeded
; https://nsis.sourceforge.io/Docs/Chapter3.html#:~:text=path%20contains%20spaces.-,3.2.3%20Examples,-installer.exe%20/NCRC
${If} $WixMode = 0
${AndIf} $4 != ""
Delete "$4\uninstall.exe"
RMDir "$4"
${EndIf}
reinst_done:
FunctionEnd
; 5. Choose install directory page
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MUI_PAGE_DIRECTORY
; 6. Start menu shortcut page
Var AppStartMenuFolder
!if "${STARTMENUFOLDER}" != ""
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!define MUI_STARTMENUPAGE_DEFAULTFOLDER "${STARTMENUFOLDER}"
!else
!define MUI_PAGE_CUSTOMFUNCTION_PRE Skip
!endif
!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder
; 7. Installation page
!insertmacro MUI_PAGE_INSTFILES
; 8. Finish page
;
; Don't auto jump to finish page after installation page,
; because the installation page has useful info that can be used debug any issues with the installer.
!define MUI_FINISHPAGE_NOAUTOCLOSE
; Use show readme button in the finish page as a button create a desktop shortcut
!define MUI_FINISHPAGE_SHOWREADME
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)"
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateOrUpdateDesktopShortcut
; Show run app after installation.
!define MUI_FINISHPAGE_RUN
!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MUI_PAGE_FINISH
Function RunMainBinary
nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" ""
FunctionEnd
; Uninstaller Pages
; 1. Confirm uninstall page
Var DeleteAppDataCheckbox
Var DeleteAppDataCheckboxState
!define /ifndef WS_EX_LAYOUTRTL 0x00400000
!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow
Function un.ConfirmShow ; Add add a `Delete app data` check box
; $1 inner dialog HWND
; $2 window DPI
; $3 style
; $4 x
; $5 y
; $6 width
; $7 height
FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog
System::Call "user32::GetDpiForWindow(p r1) i .r2"
${If} $(^RTL) = 1
StrCpy $3 "${__NSD_CheckBox_EXSTYLE} | ${WS_EX_LAYOUTRTL}"
IntOp $4 50 * $2
${Else}
StrCpy $3 "${__NSD_CheckBox_EXSTYLE}"
IntOp $4 0 * $2
${EndIf}
IntOp $5 100 * $2
IntOp $6 400 * $2
IntOp $7 25 * $2
IntOp $4 $4 / 96
IntOp $5 $5 / 96
IntOp $6 $6 / 96
IntOp $7 $7 / 96
System::Call 'user32::CreateWindowEx(i r3, w "${__NSD_CheckBox_CLASS}", w "$(deleteAppData)", i ${__NSD_CheckBox_STYLE}, i r4, i r5, i r6, i r7, p r1, i0, i0, i0) i .s'
Pop $DeleteAppDataCheckbox
SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1
SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1
FunctionEnd
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave
Function un.ConfirmLeave
SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState
FunctionEnd
!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive
!insertmacro MUI_UNPAGE_CONFIRM
; 2. Uninstalling Page
!insertmacro MUI_UNPAGE_INSTFILES
;Languages
{{#each languages}}
!insertmacro MUI_LANGUAGE "{{this}}"
{{/each}}
!insertmacro MUI_RESERVEFILE_LANGDLL
{{#each language_files}}
!include "{{this}}"
{{/each}}
Function .onInit
${GetOptions} $CMDLINE "/P" $PassiveMode
${IfNot} ${Errors}
StrCpy $PassiveMode 1
${EndIf}
${GetOptions} $CMDLINE "/NS" $NoShortcutMode
${IfNot} ${Errors}
StrCpy $NoShortcutMode 1
${EndIf}
${GetOptions} $CMDLINE "/UPDATE" $UpdateMode
${IfNot} ${Errors}
StrCpy $UpdateMode 1
${EndIf}
!if "${DISPLAYLANGUAGESELECTOR}" == "true"
!insertmacro MUI_LANGDLL_DISPLAY
!endif
!insertmacro SetContext
${If} $INSTDIR == "${PLACEHOLDER_INSTALL_DIR}"
; Set default install location
!if "${INSTALLMODE}" == "perMachine"
${If} ${RunningX64}
!if "${ARCH}" == "x64"
StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
!else if "${ARCH}" == "arm64"
StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
!else
StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
!endif
${Else}
StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
${EndIf}
!else if "${INSTALLMODE}" == "currentUser"
StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}"
!endif
Call RestorePreviousInstallLocation
${EndIf}
!if "${INSTALLMODE}" == "both"
!insertmacro MULTIUSER_INIT
!endif
; Abort downgrades if they are disabled, in the modes that skip the reinstall page choice:
; silent, passive and update
!if "${ALLOWDOWNGRADES}" == "false"
${If} ${Silent}
${OrIf} $PassiveMode = 1
${OrIf} $UpdateMode = 1
ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"
nsis_tauri_utils::SemverCompare "${VERSION}" $R0
Pop $R0
; If downgrading
${If} $R0 = -1
${If} ${Silent}
System::Call 'kernel32::AttachConsole(i -1)i.r0'
${If} $0 <> 0
System::Call 'kernel32::GetStdHandle(i -11)i.r0'
System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color
FileWrite $0 "$(silentDowngrades)"
${EndIf}
${Else}
MessageBox MB_ICONSTOP "$(silentDowngrades)"
${EndIf}
Abort
${EndIf}
${EndIf}
!endif
FunctionEnd
Section WebView2
; Check if Webview2 is already installed and skip this section
${If} ${RunningX64}
ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
${Else}
ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
${EndIf}
${If} $4 == ""
ReadRegStr $4 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
${EndIf}
${If} $4 == ""
; Webview2 installation
;
; Skip if updating
${If} $UpdateMode <> 1
!if "${INSTALLWEBVIEW2MODE}" == "downloadBootstrapper"
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
DetailPrint "$(webview2Downloading)"
NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe"
Pop $0
${If} $0 == "success"
DetailPrint "$(webview2DownloadSuccess)"
${Else}
DetailPrint "$(webview2DownloadError)"
Abort "$(webview2AbortError)"
${EndIf}
StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
Goto install_webview2
!endif
!if "${INSTALLWEBVIEW2MODE}" == "embedBootstrapper"
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
File "/oname=$TEMP\MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPERPATH}"
DetailPrint "$(installingWebview2)"
StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
Goto install_webview2
!endif
!if "${INSTALLWEBVIEW2MODE}" == "offlineInstaller"
Delete "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
File "/oname=$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" "${WEBVIEW2INSTALLERPATH}"
DetailPrint "$(installingWebview2)"
StrCpy $6 "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
Goto install_webview2
!endif
Goto webview2_done
install_webview2:
DetailPrint "$(installingWebview2)"
; $6 holds the path to the webview2 installer
ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1
${If} $1 = 0
DetailPrint "$(webview2InstallSuccess)"
${Else}
DetailPrint "$(webview2InstallError)"
Abort "$(webview2AbortError)"
${EndIf}
webview2_done:
${EndIf}
${Else}
!if "${MINIMUMWEBVIEW2VERSION}" != ""
${VersionCompare} "${MINIMUMWEBVIEW2VERSION}" "$4" $R0
${If} $R0 = 1
update_webview:
DetailPrint "$(installingWebview2)"
${If} ${RunningX64}
ReadRegStr $R1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate" "path"
${Else}
ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\EdgeUpdate" "path"
${EndIf}
${If} $R1 == ""
ReadRegStr $R1 HKCU "SOFTWARE\Microsoft\EdgeUpdate" "path"
${EndIf}
${If} $R1 != ""
; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md
; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath"
ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1
${If} $1 = 0
DetailPrint "$(webview2InstallSuccess)"
${Else}
MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview
Quit
ignore:
${EndIf}
${EndIf}
${EndIf}
!endif
${EndIf}
SectionEnd
Section Install
SetOutPath $INSTDIR
!ifmacrodef NSIS_HOOK_PREINSTALL
!insertmacro NSIS_HOOK_PREINSTALL
!endif
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
; Copy main executable
File "${MAINBINARYSRCPATH}"
; Copy resources
{{#each resources_dirs}}
CreateDirectory "$INSTDIR\\{{this}}"
{{/each}}
{{#each resources}}
File /a "/oname={{this.[1]}}" "{{no-escape @key}}"
{{/each}}
; Copy external binaries
{{#each binaries}}
File /a "/oname={{this}}" "{{no-escape @key}}"
{{/each}}
; Create file associations
{{#each file_associations as |association| ~}}
{{#each association.ext as |ext| ~}}
!insertmacro APP_ASSOCIATE "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\""
{{/each}}
{{/each}}
; Register deep links
{{#each deep_link_protocols as |protocol| ~}}
WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "URL Protocol" ""
WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "" "URL:${BUNDLEID} protocol"
WriteRegStr SHCTX "Software\Classes\\{{protocol}}\DefaultIcon" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\",0"
WriteRegStr SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""
{{/each}}
; Create uninstaller
WriteUninstaller "$INSTDIR\uninstall.exe"
; Save $INSTDIR in registry for future installations
WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR
!if "${INSTALLMODE}" == "both"
; Save install mode to be selected by default for the next installation such as updating
; or when uninstalling
WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1
!endif
; Remove old main binary if it doesn't match new main binary name
ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName"
${If} $OldMainBinaryName != ""
${AndIf} $OldMainBinaryName != "${MAINBINARYNAME}.exe"
Delete "$INSTDIR\$OldMainBinaryName"
${EndIf}
; Save current MAINBINARYNAME for future updates
WriteRegStr SHCTX "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe"
; Registry information for add/remove programs
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}"
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${VERSION}"
WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}"
WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\""
WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" "1"
WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" "1"
${GetSize} "$INSTDIR" "/M=uninstall.exe /S=0K /G=0" $0 $1 $2
IntOp $0 $0 + ${ESTIMATEDSIZE}
IntFmt $0 "0x%08X" $0
WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "$0"
!if "${HOMEPAGE}" != ""
WriteRegStr SHCTX "${UNINSTKEY}" "URLInfoAbout" "${HOMEPAGE}"
WriteRegStr SHCTX "${UNINSTKEY}" "URLUpdateInfo" "${HOMEPAGE}"
WriteRegStr SHCTX "${UNINSTKEY}" "HelpLink" "${HOMEPAGE}"
!endif
; Create start menu shortcut
!insertmacro MUI_STARTMENU_WRITE_BEGIN Application
Call CreateOrUpdateStartMenuShortcut
!insertmacro MUI_STARTMENU_WRITE_END
; Create desktop shortcut for silent and passive installers
; because finish page will be skipped
${If} $PassiveMode = 1
${OrIf} ${Silent}
Call CreateOrUpdateDesktopShortcut
${EndIf}
!ifmacrodef NSIS_HOOK_POSTINSTALL
!insertmacro NSIS_HOOK_POSTINSTALL
!endif
; Auto close this page for passive mode
${If} $PassiveMode = 1
SetAutoClose true
${EndIf}
SectionEnd
Function .onInstSuccess
; Check for `/R` flag only in silent and passive installers because
; GUI installer has a toggle for the user to (re)start the app
${If} $PassiveMode = 1
${OrIf} ${Silent}
${GetOptions} $CMDLINE "/R" $R0
${IfNot} ${Errors}
${GetOptions} $CMDLINE "/ARGS" $R0
nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "$R0"
${EndIf}
${EndIf}
FunctionEnd
Function un.onInit
!insertmacro SetContext
!if "${INSTALLMODE}" == "both"
!insertmacro MULTIUSER_UNINIT
!endif
!insertmacro MUI_UNGETLANGUAGE
${GetOptions} $CMDLINE "/P" $PassiveMode
${IfNot} ${Errors}
StrCpy $PassiveMode 1
${EndIf}
${GetOptions} $CMDLINE "/UPDATE" $UpdateMode
${IfNot} ${Errors}
StrCpy $UpdateMode 1
${EndIf}
FunctionEnd
Section Uninstall
!ifmacrodef NSIS_HOOK_PREUNINSTALL
!insertmacro NSIS_HOOK_PREUNINSTALL
!endif
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
; Delete the app directory and its content from disk
; Copy main executable
Delete "$INSTDIR\${MAINBINARYNAME}.exe"
; Delete resources
{{#each resources}}
Delete "$INSTDIR\\{{this.[1]}}"
{{/each}}
; Delete external binaries
{{#each binaries}}
Delete "$INSTDIR\\{{this}}"
{{/each}}
; Delete app associations
{{#each file_associations as |association| ~}}
{{#each association.ext as |ext| ~}}
!insertmacro APP_UNASSOCIATE "{{ext}}" "{{or association.name ext}}"
{{/each}}
{{/each}}
; Delete deep links
{{#each deep_link_protocols as |protocol| ~}}
ReadRegStr $R7 SHCTX "Software\Classes\\{{protocol}}\shell\open\command" ""
${If} $R7 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""
DeleteRegKey SHCTX "Software\Classes\\{{protocol}}"
${EndIf}
{{/each}}
; Delete uninstaller
Delete "$INSTDIR\uninstall.exe"
{{#each resources_ancestors}}
RMDir /REBOOTOK "$INSTDIR\\{{this}}"
{{/each}}
RMDir "$INSTDIR"
; Remove shortcuts if not updating
${If} $UpdateMode <> 1
!insertmacro DeleteAppUserModelId
; Remove start menu shortcut
!insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder
!insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
Pop $0
${If} $0 = 1
!insertmacro UnpinShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
Delete "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
RMDir "$SMPROGRAMS\$AppStartMenuFolder"
${EndIf}
!insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
Pop $0
${If} $0 = 1
!insertmacro UnpinShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk"
Delete "$SMPROGRAMS\${PRODUCTNAME}.lnk"
${EndIf}
; Remove desktop shortcuts
!insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
Pop $0
${If} $0 = 1
!insertmacro UnpinShortcut "$DESKTOP\${PRODUCTNAME}.lnk"
Delete "$DESKTOP\${PRODUCTNAME}.lnk"
${EndIf}
${EndIf}
; Remove registry information for add/remove programs
!if "${INSTALLMODE}" == "both"
DeleteRegKey SHCTX "${UNINSTKEY}"
!else if "${INSTALLMODE}" == "perMachine"
DeleteRegKey HKLM "${UNINSTKEY}"
!else
DeleteRegKey HKCU "${UNINSTKEY}"
!endif
; Removes the Autostart entry for ${PRODUCTNAME} from the HKCU Run key if it exists.
; This ensures the program does not launch automatically after uninstallation if it exists.
; If it doesn't exist, it does nothing.
; We do this when not updating (to preserve the registry value on updates)
${If} $UpdateMode <> 1
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
${EndIf}
; Delete app data if the checkbox is selected
; and if not updating
${If} $DeleteAppDataCheckboxState = 1
${AndIf} $UpdateMode <> 1
; Clear the install location $INSTDIR from registry
DeleteRegKey SHCTX "${MANUPRODUCTKEY}"
DeleteRegKey /ifempty SHCTX "${MANUKEY}"
; Clear the install language from registry
DeleteRegValue HKCU "${MANUPRODUCTKEY}" "Installer Language"
DeleteRegKey /ifempty HKCU "${MANUPRODUCTKEY}"
DeleteRegKey /ifempty HKCU "${MANUKEY}"
SetShellVarContext current
RmDir /r "$APPDATA\${BUNDLEID}"
RmDir /r "$LOCALAPPDATA\${BUNDLEID}"
${EndIf}
!ifmacrodef NSIS_HOOK_POSTUNINSTALL
!insertmacro NSIS_HOOK_POSTUNINSTALL
!endif
; Auto close if passive mode or updating
${If} $PassiveMode = 1
${OrIf} $UpdateMode = 1
SetAutoClose true
${EndIf}
SectionEnd
Function RestorePreviousInstallLocation
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
StrCmp $4 "" +2 0
StrCpy $INSTDIR $4
FunctionEnd
Function Skip
Abort
FunctionEnd
Function SkipIfPassive
${IfThen} $PassiveMode = 1 ${|} Abort ${|}
FunctionEnd
Function un.SkipIfPassive
${IfThen} $PassiveMode = 1 ${|} Abort ${|}
FunctionEnd
Function CreateOrUpdateStartMenuShortcut
; We used to use product name as MAINBINARYNAME
; migrate old shortcuts to target the new MAINBINARYNAME
StrCpy $R0 0
!insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
Pop $0
${If} $0 = 1
!insertmacro SetShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
StrCpy $R0 1
${EndIf}
!insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
Pop $0
${If} $0 = 1
!insertmacro SetShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
StrCpy $R0 1
${EndIf}
${If} $R0 = 1
Return
${EndIf}
; Skip creating shortcut if in update mode or no shortcut mode
; but always create if migrating from wix
${If} $WixMode = 0
${If} $UpdateMode = 1
${OrIf} $NoShortcutMode = 1
Return
${EndIf}
${EndIf}
!if "${STARTMENUFOLDER}" != ""
CreateDirectory "$SMPROGRAMS\$AppStartMenuFolder"
CreateShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
!insertmacro SetLnkAppUserModelId "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
!else
CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
!insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk"
!endif
FunctionEnd
Function CreateOrUpdateDesktopShortcut
; We used to use product name as MAINBINARYNAME
; migrate old shortcuts to target the new MAINBINARYNAME
!insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
Pop $0
${If} $0 = 1
!insertmacro SetShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
Return
${EndIf}
; Skip creating shortcut if in update mode or no shortcut mode
; but always create if migrating from wix
${If} $WixMode = 0
${If} $UpdateMode = 1
${OrIf} $NoShortcutMode = 1
Return
${EndIf}
${EndIf}
CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
!insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk"
FunctionEnd
-50
Переглянути файл
@@ -965,13 +965,9 @@ export const commands = {
comparison?: ComparisonLaunch | null,
/** `openidea diff a.txt b.txt`: the two files to open in the diff viewer (boxed: most launches have none). */
diff?: DiffFilesLaunch | null,
/** Files requested after the pending diff take focus after it opens. */
diffBeforeFiles?: boolean,
/** Deployment windows: the server and local selection to compare. */
deployment?: DeploymentLaunch | null,
} | null>("window_take_launch"),
/** Release the opening window's reservation after navigation or cancellation. */
windowCompleteLaunch: () => typedError<null, IdeError>(__TAURI_INVOKE("window_complete_launch")),
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
/** Projects open in project windows, in window order (title bar project widget). */
windowOpenProjects: () => typedError<OpenProject[], IdeError>(__TAURI_INVOKE("window_open_projects")),
@@ -1286,12 +1282,6 @@ export const commands = {
dockerRemove: (endpoint: DockerEndpoint, object: DockerObject, ids: string[], force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("docker_remove", { endpoint, object, ids, force })),
/** Pretty-printed `docker inspect` JSON. */
dockerInspect: (endpoint: DockerEndpoint, object: DockerObject, id: string) => typedError<string, IdeError>(__TAURI_INVOKE("docker_inspect", { endpoint, object, id })),
/** Layers of an image (`docker image history`). */
dockerImageHistory: (endpoint: DockerEndpoint, id: string) => typedError<DockerImageLayer[], IdeError>(__TAURI_INVOKE("docker_image_history", { endpoint, id })),
/** Processes running inside a container (`docker top`). */
dockerContainerTop: (endpoint: DockerEndpoint, id: string) => typedError<DockerProcessList, IdeError>(__TAURI_INVOKE("docker_container_top", { endpoint, id })),
/** One-shot resource usage snapshot of a running container (`docker stats --no-stream`). */
dockerContainerStats: (endpoint: DockerEndpoint, id: string) => typedError<DockerContainerStats, IdeError>(__TAURI_INVOKE("docker_container_stats", { endpoint, id })),
/** Streams a container's log lines until it stops or the request is cancelled. */
dockerLogs: (request: RequestId, endpoint: DockerEndpoint, id: string, tail: number, follow: boolean, timestamps: boolean, onLine: Channel<DockerLogLine>) => typedError<null, IdeError>(__TAURI_INVOKE("docker_logs", { request, endpoint, id, tail, follow, timestamps, onLine })),
/** Follows `docker events` until the daemon goes away or the request is cancelled. */
@@ -3556,22 +3546,6 @@ export type DockerContainer = {
composeWorkingDir: string | null,
/** `com.docker.compose.project.config_files` label (comma-separated in docker). */
composeFiles: string[],
/** Mounted volume names or host paths reported by `docker ps` (`Mounts`). */
mounts?: string[],
/** Connected network names reported by `docker ps` (`Networks`). */
networks?: string[],
/** User and tool labels assigned to the container. */
labels?: { [key in string]: string },
};
/** Live resource metrics returned by `docker stats --no-stream --no-trunc --format '{{json .}}'`. */
export type DockerContainerStats = {
cpuPerc: string,
memUsage: string,
memPerc: string,
netIo: string,
blockIo: string,
pids: string,
};
/** Which daemon a docker command talks to. */
@@ -3606,16 +3580,6 @@ export type DockerImage = {
createdSince: string,
};
/** One layer in `docker image history --no-trunc --format '{{json .}}'`. */
export type DockerImageLayer = {
id: string,
createdBy: string,
size: string,
createdSince: string,
createdAt: string,
comment: string,
};
/** A line of `docker logs` output. */
export type DockerLogLine = {
stderr: boolean,
@@ -3628,20 +3592,10 @@ export type DockerNetwork = {
driver: string,
scope: string,
composeProject: string | null,
createdAt?: string,
ipv6?: boolean,
internal?: boolean,
labels?: { [key in string]: string },
};
export type DockerObject = "container" | "image" | "volume" | "network";
/** Process table returned by `docker top <container>`. */
export type DockerProcessList = {
titles: string[],
processes: string[][],
};
/** A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately. */
export type DockerRegistry = {
id: string,
@@ -3676,8 +3630,6 @@ export type DockerVolume = {
driver: string,
mountpoint: string,
composeProject: string | null,
scope?: string,
labels?: { [key in string]: string },
};
/** What the UI needs to show an opened document. */
@@ -5521,8 +5473,6 @@ export type Launch = {
comparison?: ComparisonLaunch | null,
/** `openidea diff a.txt b.txt`: the two files to open in the diff viewer (boxed: most launches have none). */
diff?: DiffFilesLaunch | null,
/** Files requested after the pending diff take focus after it opens. */
diffBeforeFiles?: boolean,
/** Deployment windows: the server and local selection to compare. */
deployment?: DeploymentLaunch | null,
};
-3
Переглянути файл
@@ -33,7 +33,6 @@ import type { LanguageDescription } from "@codemirror/language";
import type { LineEnding } from "@/platform/ipc";
import { create } from "zustand";
import { maybeEditorService } from "@/workbench/contributions";
import { cornerInset } from "@/editor/core/cm/cornerInset";
/** Documents above this size (UTF-16 units) skip per-line decorations. */
export const HEAVY_LIMIT = 8_000_000;
@@ -359,8 +358,6 @@ export function editorCorner(view: EditorView): HTMLElement {
gap: "4px",
});
view.dom.appendChild(el);
// The lines leave room for its measured width, so it never covers a line end.
view.plugin(cornerInset)?.track(el);
return el;
}
+3 -8
Переглянути файл
@@ -6,7 +6,6 @@ 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 {
@@ -739,13 +738,9 @@ export function registerEditorActions(): () => void {
category: "View",
icon: "soft-wrap",
keywords: ["word wrap", "line wrap"],
when: "textEditorActive || softWrapSurfaceFocus",
toggled: () => focusedSoftWrapSurface()?.enabled() ?? activeSlot()?.model.softWrapOn() ?? false,
run: () => {
const surface = focusedSoftWrapSurface();
if (surface) surface.toggle();
else activeSlot()?.model.toggleSoftWrap();
},
when: "textEditorActive",
toggled: () => activeSlot()?.model.softWrapOn() ?? false,
run: () => activeSlot()?.model.toggleSoftWrap(),
},
text("code.foldAll", "Collapse All", (v) => collapseAll(v), { category: "Folding", icon: "collapse-all" }),
text("code.unfoldAll", "Expand All", (v) => expandAll(v), { category: "Folding", icon: "expand-all" }),
-73
Переглянути файл
@@ -1,73 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { editorCorner } from "@/editor/api";
import { cornerInset } from "./cornerInset";
let view: EditorView;
let resize: (() => void) | null = null;
beforeEach(() => {
vi.stubGlobal(
"ResizeObserver",
class {
constructor(callback: () => void) {
resize = callback;
}
observe() {}
disconnect() {
resize = null;
}
},
);
view = new EditorView({
state: EditorState.create({ doc: "const a = 1;", extensions: [cornerInset] }),
parent: document.body,
});
});
afterEach(() => {
view.destroy();
vi.unstubAllGlobals();
});
const inset = () => view.dom.style.getPropertyValue("--cm-corner-inset");
/** The corner's measured width arrives from the ResizeObserver, not from jsdom. */
function resizeTo(width: number) {
const corner = view.dom.querySelector<HTMLElement>(".cm-openidea-corner");
if (!corner) throw new Error("no corner");
corner.getBoundingClientRect = () => ({ width }) as DOMRect;
resize?.();
}
describe("corner inset", () => {
it("leaves the corner's width plus a gap for the text: 20px check, 32+ with counts", () => {
editorCorner(view);
resizeTo(20);
expect(inset()).toBe("24px");
resizeTo(32);
expect(inset()).toBe("36px");
});
it("clears the reserved room when the corner is empty", () => {
editorCorner(view);
resizeTo(20);
resizeTo(0);
expect(inset()).toBe("");
});
it("keeps at least half of the editor width for the text", () => {
Object.defineProperty(view.scrollDOM, "clientWidth", { configurable: true, value: 200 });
editorCorner(view);
resizeTo(400);
expect(inset()).toBe("100px");
});
it("does nothing without the extension", () => {
const plain = new EditorView({ state: EditorState.create({ doc: "x" }), parent: document.body });
expect(() => editorCorner(plain)).not.toThrow();
expect(plain.dom.style.getPropertyValue("--cm-corner-inset")).toBe("");
plain.destroy();
});
});
-81
Переглянути файл
@@ -1,81 +0,0 @@
/**
* Keeps the end of a line clear of the floating corner widgets (`editorCorner()`
* in `editor/api.ts`: the inspection widget, the Review Mode group).
*
* The corner is absolutely positioned in `.cm-editor`, outside `.cm-scroller`:
* scrolling does not move it and it does not count in `scrollWidth`, so at full
* horizontal scroll the last characters of a line land under it. Its width is
* not a constant (a green check, then counts and previous/next buttons as
* problems appear), so the lines' right padding follows its measured width
* through `--cm-corner-inset` (`theme.ts`), the way the fixed line padding
* already reserves room for the overview lane.
*/
import { type EditorView, ViewPlugin } from "@codemirror/view";
/** Space between the corner's left edge and the end of a line. */
const CORNER_GAP = 4;
/** Width changes of the corner that matter: `getBoundingClientRect()` is fractional. */
const round = (width: number) => Math.ceil(width);
class CornerInset {
private corner: HTMLElement | null = null;
private observer: ResizeObserver | null = null;
private inset = -1;
constructor(private readonly view: EditorView) {
this.sync();
}
/** A new corner: `editorCorner()` calls this right after appending it. */
track(corner: HTMLElement) {
if (corner === this.corner) return;
this.observer?.disconnect();
this.corner = corner;
if (typeof ResizeObserver === "undefined") return;
// The widget's content grows and shrinks (diagnostic counts, Review Mode).
this.observer = new ResizeObserver(() => this.measure());
this.observer.observe(corner);
this.measure();
}
update() {
// The corner is created lazily, possibly after this plugin: catch it on the next update.
if (!this.corner) this.sync();
}
private sync() {
const corner = this.view.dom.querySelector<HTMLElement>(":scope > .cm-openidea-corner");
if (corner) this.track(corner);
}
private measure() {
const corner = this.corner;
if (!corner) return;
const width = corner.getBoundingClientRect().width;
let inset = width > 0 ? round(width) + CORNER_GAP : 0;
// A narrow window or a wide corner: keep at least half of the width for text.
const room = this.view.scrollDOM.clientWidth;
if (inset > 0 && room > 0) inset = Math.min(inset, Math.floor(room / 2));
this.apply(inset);
}
private apply(inset: number) {
if (inset === this.inset) return;
this.inset = inset;
const style = this.view.dom.style;
// An empty corner needs no room; the `theme.ts` fallback is 0.
if (inset > 0) style.setProperty("--cm-corner-inset", `${inset}px`);
else style.removeProperty("--cm-corner-inset");
// The line boxes changed: CodeMirror re-measures the content and the scroll extent.
this.view.requestMeasure();
}
destroy() {
this.observer?.disconnect();
this.observer = null;
this.corner = null;
}
}
export const cornerInset = ViewPlugin.fromClass(CornerInset);
-2
Переглянути файл
@@ -34,7 +34,6 @@ import { openideaHighlightStyle } from "./highlight";
import { openideaTheme } from "./theme";
import { caretRowHighlight } from "./caretRow";
import { changeLane, overviewLane } from "./lanes";
import { cornerInset } from "./cornerInset";
import { foldingExtension } from "./folding";
import { syntaxHighlightField } from "./syntaxHighlight";
import { indentGuides } from "./indentGuides";
@@ -371,7 +370,6 @@ export function baseExtensions(o: SetupOptions): Extension {
methodLinesField,
findExtension(),
overviewLane,
cornerInset,
codeLensExtension,
EditorView.contentAttributes.of({
spellcheck: "false",
+2 -5
Переглянути файл
@@ -153,8 +153,7 @@ export const openideaTheme = EditorView.theme({
caretColor: "var(--caret, var(--fg-strong))",
cursor: "text",
},
// The right side also leaves room for the floating corner widgets (core/cm/cornerInset.ts).
".cm-line": { padding: "0 calc(16px + var(--cm-corner-inset, 0px)) 0 6px" },
".cm-line": { padding: "0 16px 0 6px" },
...caretStyles,
"&.cm-openidea-ligatures .cm-scroller, &.cm-openidea-ligatures .cm-openidea-sticky": {
fontVariantLigatures: "normal",
@@ -371,7 +370,5 @@ export const openideaTheme = EditorView.theme({
".cm-openidea-stickyText": { flex: "1", overflow: "hidden" },
// Soft-wrap: continuation rows indent slightly, like IDEA's wrap sign column.
"&.cm-lineWrapping .cm-line, .cm-lineWrapping .cm-line": {
paddingRight: "calc(24px + var(--cm-corner-inset, 0px))",
},
"&.cm-lineWrapping .cm-line, .cm-lineWrapping .cm-line": { paddingRight: "24px" },
});
+1 -4
Переглянути файл
@@ -56,7 +56,6 @@ import {
enforceTabLimit,
findTab,
initialTabsState,
mergeSessionTabs,
moveTab,
moveTabToNewSplit,
neighbourPane,
@@ -532,9 +531,7 @@ export class EditorController implements SlotHost {
this.restoredTabs = new Set(Object.values(state.panes).flatMap((p) => p.tabs.map((t) => t.id)));
this.restoring = true;
try {
// 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(state, true);
} finally {
this.restoring = false;
}
-63
Переглянути файл
@@ -1,63 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorController, LIGHT_EDIT_SESSION, openFilePaths, useTabs } from "./controller";
import { createMemoryBackend } from "./backend";
import { initialTabsState } from "./model/tabs";
import { storeSession } from "./model/session";
import { useProject } from "@/platform/project";
let ctrl: EditorController | null = null;
const initialSettings = useProject.getState().settings;
afterEach(() => {
ctrl?.stop();
ctrl = null;
useTabs.setState(initialTabsState(), true);
useProject.setState({ project: null, lightEdit: false, settings: initialSettings } as never);
try {
localStorage.removeItem(`openidea.editorSession.v1:${LIGHT_EDIT_SESSION}`);
} catch {
/* ignore */
}
});
function activePath() {
const state = useTabs.getState();
const pane = state.panes[state.activePane]!;
return pane.tabs.find((tab) => tab.id === pane.active)?.input.path;
}
function seedLightEditSession() {
storeSession(LIGHT_EDIT_SESSION, {
version: 1,
layout: { kind: "pane", tabs: [{ path: "/p/a.ts" }], active: 0 },
activePane: 0,
files: {},
});
}
describe("lightedit launch (#2229)", () => {
it("admits the launched file after the saved session restores", async () => {
seedLightEditSession();
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b" }));
ctrl.start();
// openFilesHere: window has neither project nor LightEdit -> openLightEdit(b) then openInEditor([b]).
useProject.setState({ project: null, lightEdit: true });
await ctrl.openFile("/p/b.ts", { focus: true });
await new Promise((r) => setTimeout(r, 50));
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
});
it("merges a late saved-session restore with the launched tab instead of replacing it", async () => {
seedLightEditSession();
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b" }));
ctrl.start();
useProject.setState({ project: null, lightEdit: true });
await ctrl.openFile("/p/b.ts", { focus: true });
// A stale/second transition restore landing after the admit (#2229).
ctrl.restoreSession(LIGHT_EDIT_SESSION);
await new Promise((r) => setTimeout(r, 50));
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
expect(activePath()).toBe("/p/b.ts");
});
});
-22
Переглянути файл
@@ -347,28 +347,6 @@ 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", () => {
+3 -9
Переглянути файл
@@ -242,8 +242,9 @@ export class EditorSlot {
this.kept = null;
const i = keptSlots.indexOf(this);
if (i >= 0) keptSlots.splice(i, 1);
this.savedTopLine = topLineAt(view, this.scrollPos.top);
this.scroll = scrollSnapshotAt(view, this.scrollPos);
const top = topLineAt(view, this.scrollPos.top);
this.savedTopLine = top;
this.scroll = EditorView.scrollIntoView(view.state.doc.line(top + 1).from, { y: "start" });
this.stored = view.state;
view.destroy();
}
@@ -398,13 +399,6 @@ 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;
-23
Переглянути файл
@@ -93,29 +93,6 @@ export function openKeys(s: TabsState): Set<string> {
return keys;
}
/**
* Folds restored tabs into the current tabs without losing anything open: tabs
* already open stay (with their active tab), restored tabs missing by key are
* appended to the active pane. An empty window takes the restored state as-is,
* keeping its saved layout and active tab.
*/
export function mergeSessionTabs(current: TabsState, restored: TabsState): TabsState {
const target = current.panes[current.activePane];
if (!target || !Object.values(current.panes).some((p) => p.tabs.length)) return restored;
const seen = openKeys(current);
const additions: Tab[] = [];
for (const pane of Object.values(restored.panes))
for (const tab of pane.tabs) {
if (seen.has(tab.input.key)) continue;
seen.add(tab.input.key);
additions.push(tab);
}
if (!additions.length) return current;
const tabs = [...target.tabs, ...additions];
const mru = [...target.mru, ...additions.map((t) => t.id).filter((id) => !target.mru.includes(id))];
return withPane(current, { ...target, tabs, mru });
}
function withPane(s: TabsState, pane: Pane): TabsState {
return { ...s, panes: { ...s.panes, [pane.id]: pane } };
}
+6 -10
Переглянути файл
@@ -35,7 +35,7 @@ const LENS_KINDS = new Set<SymbolKind>([
const MAX_PER_PASS = 40;
const CONCURRENCY = 4;
/** Lines above/below the viewport that are counted too, so scrolling feels instant. */
const MARGIN_LINES = 10;
const MARGIN_LINES = 60;
const usagesBackoff = featureBackoff();
export interface LensTarget {
@@ -114,8 +114,7 @@ class UsagesLensPlugin {
private outline: { doc: Text; targets: LensTarget[] } | null = null;
private generation = 0;
private pending = new Set<RequestId>();
/** Keys whose count came back incomplete (the server was indexing): not shown, asked again once it settles. */
private incomplete = new Set<string>();
private incomplete = false;
private unsubscribe: () => void;
private offReady: () => void;
private offSettled: () => void;
@@ -130,13 +129,10 @@ class UsagesLensPlugin {
// Counts computed while the server was indexing may be incomplete.
this.offReady = onLspRefresh("codeLens", () => {
this.cache.clear();
this.incomplete.clear();
this.refresh();
});
this.offSettled = onServerSettled(() => {
if (!this.incomplete.size) return;
this.incomplete.clear();
this.refresh();
if (this.incomplete) this.refresh();
});
this.offBlame = onBlameInvalidated(() => this.refresh());
}
@@ -171,11 +167,11 @@ class UsagesLensPlugin {
}
const text = view.state.doc;
const wanted = () => gen === this.generation && view.state.doc === text;
this.incomplete = false;
// Blame runs beside the reference requests; it never holds up the counts.
const blame = authors ? blameFor(doc.path, text) : Promise.resolve(null);
if (this.cacheDoc !== text) {
this.cache = new Map();
this.incomplete = new Set();
this.cacheDoc = text;
}
try {
@@ -191,7 +187,7 @@ class UsagesLensPlugin {
.filter((t) => t.line >= firstLine && t.line <= lastLine)
.slice(0, MAX_PER_PASS);
const key = (t: LensTarget) => `${t.line}:${t.col}:${t.name}`;
const todo = usages ? visible.filter((t) => !this.cache.has(key(t)) && !this.incomplete.has(key(t))) : [];
const todo = usages ? visible.filter((t) => !this.cache.has(key(t))) : [];
let unavailable = false;
for (let i = 0; i < todo.length && !unavailable; i += CONCURRENCY) {
await Promise.all(
@@ -213,7 +209,7 @@ class UsagesLensPlugin {
);
}, wanted);
if (wanted()) {
if (incomplete) this.incomplete.add(key(t));
if (incomplete) this.incomplete = true;
else this.cache.set(key(t), refs.length);
}
} catch (e) {
+3 -8
Переглянути файл
@@ -33,9 +33,8 @@ beforeEach(() => {
document.body.append(tmp);
return {
svg:
`<svg id="${id}"><style>#${id} .flowchart-link{fill:none;}#${id} [id$="-arrow"] path{fill:#9fa2a8;}</style>` +
`<defs><marker id="${id}-arrow" orient="auto"><path d="M0,0L8,4"/></marker></defs>` +
`<path class="flowchart-link" d="M0,4" marker-end="url(#${id}-arrow)"/><text>${text.split("\n")[0]}</text></svg>`,
`<svg id="${id}"><defs><marker id="${id}-arrow" orient="auto"><path d="M0,0L8,4"/></marker></defs>` +
`<path d="M0,4" marker-end="url(#${id}-arrow)"/><text>${text.split("\n")[0]}</text></svg>`,
};
});
mockIPC((cmd, args) => (cmd === "fs_read_image" ? readImage((args as { path: string }).path) : null));
@@ -237,15 +236,11 @@ describe("mermaid diagrams in a reply", () => {
expect(idsOne).toHaveLength(2);
expect(idsTwo).toHaveLength(2);
expect(idsOne.filter((id) => idsTwo.includes(id))).toEqual([]);
// Every marker reference and scoped `<style>` selector resolves inside its own copy.
// Every marker reference resolves inside its own copy.
for (const root of [one.container, two.container]) {
const svg = root.querySelector(".mermaid-output svg")!;
const ref = svg.querySelector("[marker-end]")!.getAttribute("marker-end")!;
expect(new Set(idsOf(root)).has(/url\(#(.+)\)/.exec(ref)![1]!)).toBe(true);
expect(svg.querySelector("style")!.textContent).toContain(
`#${svg.getAttribute("id")} .flowchart-link{fill:none;}`,
);
expect(svg.querySelector("defs [id$='-arrow'] path")).not.toBeNull();
}
});
+2 -7
Переглянути файл
@@ -554,11 +554,8 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
while (entries && start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--;
const dragging = useRef(false);
// When the user last scrolled the conversation (wheel, touch, keys, the scrollbar, Find):
// that leaves the end. WebKit also moves the offset back on its own while rows lay out,
// which comes with a change of the content height; a scroll without one is meant too (the
// scrollbar thumb, a jump), whatever moved it.
// only that leaves the end. WebKit also moves the offset back on its own while rows lay out.
const userScrolled = useRef(-Infinity);
const seenHeight = useRef(0);
const markUserScroll = useCallback(() => {
userScrolled.current = performance.now();
}, []);
@@ -726,9 +723,7 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
onScroll={(e) => {
const el = e.currentTarget;
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
const laidOut = el.scrollHeight !== seenHeight.current;
seenHeight.current = el.scrollHeight;
const byUser = dragging.current || performance.now() - userScrolled.current < 500 || !laidOut;
const byUser = dragging.current || performance.now() - userScrolled.current < 500;
const stick = atEnd || (position.current.stick && !byUser);
// Still following: back to the end the offset was moved away from.
if (stick && !atEnd) el.scrollTop = el.scrollHeight;
+1 -18
Переглянути файл
@@ -362,10 +362,7 @@ describe("scrolling", () => {
let height = 1000;
Object.defineProperty(el, "scrollHeight", { configurable: true, get: () => height });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.scrollTop = 600;
fireEvent.scroll(el);
// The conversation grew after it was scrolled to the end, or WebKit moved the offset back
// while rows laid out: both change the content height.
// The conversation grew after it was scrolled to the end, or WebKit moved the offset back.
height = 1300;
el.scrollTop = 600;
fireEvent.scroll(el);
@@ -379,20 +376,6 @@ describe("scrolling", () => {
expect(await screen.findByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
});
it("leaves the end for a scroll that no layout caused, as dragging the scrollbar thumb", async () => {
render(<SessionEditor input={input("A")} />);
expect(await screen.findByText("Answer A")).toBeInTheDocument();
const el = stream();
Object.defineProperty(el, "scrollHeight", { configurable: true, value: 1000 });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.scrollTop = 600;
fireEvent.scroll(el);
el.scrollTop = 0;
fireEvent.scroll(el);
expect(el.scrollTop).toBe(0);
expect(await screen.findByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
});
it("offers one click back to the latest message after scrolling up", async () => {
render(<SessionEditor input={input("A")} />);
expect(await screen.findByText("Answer A")).toBeInTheDocument();
+5 -261
Переглянути файл
@@ -6,14 +6,9 @@ const projectCurrent = vi.fn();
const windowOpenProject = vi.fn();
const windowOpenFiles = vi.fn();
const windowTakeLaunch = vi.fn();
const windowCompleteLaunch = vi.fn();
const wslResolve = vi.fn();
const cancelClose = vi.fn();
const notify = vi.fn();
const listen = vi.fn();
vi.mock("@tauri-apps/api/webviewWindow", () => ({
getCurrentWebviewWindow: () => ({ listen }),
}));
vi.mock("@/platform/remote", async (original) => ({
...(await original<typeof import("@/platform/remote")>()),
isRemoteWindow: vi.fn(() => false),
@@ -41,7 +36,6 @@ vi.mock("@/platform/ipc", async (orig) => {
windowOpenProject: (...a: unknown[]) => windowOpenProject(...a),
windowOpenFiles: (...a: unknown[]) => windowOpenFiles(...a),
windowTakeLaunch: () => windowTakeLaunch(),
windowCompleteLaunch: () => windowCompleteLaunch(),
wslResolve: (p: string) => wslResolve(p),
lightEditOpen: (p: string) => lightEditOpen(p),
fsReadDir: (p: string) => fsReadDir(p),
@@ -53,20 +47,18 @@ vi.mock("@/platform/project", async (orig) => {
return { ...real, openProject: (p: string) => openProject(p) };
});
const diffs: unknown[] = [];
const openDiff = vi.fn(async (data: unknown) => void diffs.push(data));
vi.mock("@/features/vcs/diffInput", () => ({ openVcsDiff: (data: unknown) => openDiff(data) }));
vi.mock("@/features/vcs/diffInput", () => ({ openVcsDiff: (data: unknown) => void diffs.push(data) }));
const {
openProjectInWindow,
consumeLaunch,
installLaunchHandling,
openFiles,
openPaths,
openLightEditFileAsProject,
openProjectWithPolicy,
windowActions,
} = await import("../windows");
const { useProject, startupLaunchHandled } = await import("@/platform/project");
const { useProject } = await import("@/platform/project");
const { provideEditorService, provideNotificationService } = await import("@/workbench/contributions");
const { isRemoteWindow, connectRemote } = await import("@/platform/remote");
const { IpcError } = await import("@/platform/ipc");
@@ -74,14 +66,11 @@ provideNotificationService({ notify });
const opened: string[] = [];
let activePath: string | null = null;
const openEditorFile = vi.fn<import("@/workbench/contributions").EditorService["openFile"]>(
async (path, options) =>
provideEditorService({
openFile: async (path, options) =>
void opened.push(
`${path}${options?.focus ? " (focus)" : ""}${options?.selection ? ` @${options.selection.line}:${options.selection.col}` : ""}`,
),
);
provideEditorService({
openFile: openEditorFile,
openInput: async () => {},
activePath: () => activePath,
activeCursor: () => null,
@@ -92,29 +81,18 @@ provideEditorService({
const ok = (data: unknown) => ({ status: "ok", data });
const projectState = (root: string) => ({ project: { root, name: root, trusted: true, isGit: false, settings: {} } });
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>((done) => (resolve = done));
return { promise, resolve };
}
beforeEach(() => {
for (const f of [windowOpenProject, windowOpenFiles, windowTakeLaunch, wslResolve]) f.mockReset();
windowTakeLaunch.mockResolvedValue(null);
windowCompleteLaunch.mockReset().mockResolvedValue(ok(null));
wslResolve.mockResolvedValue(null);
vi.mocked(connectRemote).mockClear();
for (const f of [lightEditOpen, fsReadDir, openProject]) f.mockClear();
cancelClose.mockClear();
notify.mockClear();
listen.mockReset();
openEditorFile.mockClear();
openDiff.mockClear();
vi.mocked(isRemoteWindow).mockReturnValue(false);
opened.length = 0;
diffs.length = 0;
activePath = null;
useProject.setState({ project: null, lightEdit: false, settings: null, opening: false, openingPath: null } as never);
useProject.setState({ project: null, lightEdit: false, settings: null } as never);
});
describe("openProjectInWindow", () => {
@@ -294,160 +272,12 @@ describe("Open Containing Folder as Project", () => {
});
describe("launch", () => {
it("subscribes before taking a launch received while the listener is registering", async () => {
const registered = deferred();
const unlisten = vi.fn();
listen.mockImplementationOnce(async () => {
await registered.promise;
windowTakeLaunch.mockResolvedValueOnce({ project: "/p", files: ["/p/late.cs"] });
return unlisten;
});
const dispose = installLaunchHandling();
try {
await vi.waitFor(() => expect(listen).toHaveBeenCalledOnce());
expect(windowTakeLaunch).not.toHaveBeenCalled();
registered.resolve();
await startupLaunchHandled();
expect(opened).toEqual(["/p/late.cs (focus)"]);
} finally {
registered.resolve();
await startupLaunchHandled();
dispose();
}
expect(unlisten).toHaveBeenCalledOnce();
});
it("does not consume a launch after disposal while the listener is registering", async () => {
const registered = deferred();
const unlisten = vi.fn();
listen.mockImplementationOnce(async () => {
await registered.promise;
return unlisten;
});
windowTakeLaunch.mockResolvedValueOnce({ project: "/p", files: ["/p/a.cs"] });
const dispose = installLaunchHandling();
await vi.waitFor(() => expect(listen).toHaveBeenCalledOnce());
dispose();
registered.resolve();
await startupLaunchHandled();
expect(unlisten).toHaveBeenCalledOnce();
expect(windowTakeLaunch).not.toHaveBeenCalled();
expect(opened).toEqual([]);
});
it("serializes launch events while their project is opening", async () => {
const openedProject = deferred();
openProject.mockImplementationOnce(async (path) => {
await openedProject.promise;
const state = projectState(path);
useProject.setState({ ...state, lightEdit: false } as never);
return state.project;
});
let onLaunch: (() => void) | undefined;
listen.mockImplementationOnce(async (_event, handler: () => void) => {
onLaunch = handler;
return () => {};
});
windowTakeLaunch
.mockResolvedValueOnce({ project: "/p", files: ["/p/a.cs"] })
.mockResolvedValueOnce({ files: ["/p/b.cs"], positions: [{ path: "/p/b.cs", line: 10, column: 3 }] });
const dispose = installLaunchHandling();
try {
await vi.waitFor(() => expect(openProject).toHaveBeenCalledOnce());
onLaunch!();
openedProject.resolve();
await startupLaunchHandled();
await consumeLaunch();
expect(lightEditOpen).not.toHaveBeenCalled();
expect(opened).toEqual(["/p/a.cs (focus)", "/p/b.cs (focus) @10:3"]);
expect(openProject).toHaveBeenCalledOnce();
} finally {
openedProject.resolve();
await startupLaunchHandled();
dispose();
}
});
it("waits for an existing project restore before opening a received file", async () => {
useProject.setState({ opening: true, openingPath: "/p" });
windowTakeLaunch.mockResolvedValueOnce({
files: ["/p/a.cs"],
positions: [{ path: "/p/a.cs", line: 8, column: 2 }],
});
const request = consumeLaunch();
try {
await vi.waitFor(() => expect(windowTakeLaunch).toHaveBeenCalledOnce());
await new Promise((resolve) => setTimeout(resolve, 0));
expect(opened).toEqual([]);
expect(lightEditOpen).not.toHaveBeenCalled();
expect(windowCompleteLaunch).not.toHaveBeenCalled();
} finally {
useProject.setState({ ...projectState("/p"), opening: false, openingPath: null } as never);
await request;
}
expect(openProject).not.toHaveBeenCalled();
expect(lightEditOpen).not.toHaveBeenCalled();
expect(opened).toEqual(["/p/a.cs (focus) @8:2"]);
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
});
it("keeps the open project and applies later locations in order", async () => {
useProject.setState(projectState("/p") as never);
for (const line of [5, 8, 12]) {
windowTakeLaunch.mockResolvedValueOnce({
project: "/p",
files: ["/p/a.cs"],
positions: [{ path: "/p/a.cs", line, column: 0 }],
});
}
await Promise.all([consumeLaunch(), consumeLaunch(), consumeLaunch()]);
expect(openProject).not.toHaveBeenCalled();
expect(opened).toEqual(["/p/a.cs (focus) @5:0", "/p/a.cs (focus) @8:0", "/p/a.cs (focus) @12:0"]);
});
it("reports a missing file and still handles the next launch", async () => {
useProject.setState(projectState("/p") as never);
openEditorFile.mockRejectedValueOnce(new Error("File not found"));
windowTakeLaunch.mockResolvedValueOnce({ files: ["/p/missing.cs"] }).mockResolvedValueOnce({ files: ["/p/a.cs"] });
await Promise.all([consumeLaunch(), consumeLaunch()]);
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "File not found" }));
expect(opened).toEqual(["/p/a.cs (focus)"]);
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
});
it.each([
new Error("Project unavailable"),
new IpcError({ kind: "cancelled", message: "Project opening cancelled" }),
])("completes a failed or cancelled project launch and handles the next: %s", async (error) => {
openProject.mockRejectedValueOnce(error);
windowTakeLaunch
.mockResolvedValueOnce({ project: "/p", files: ["/p/a.cs"] })
.mockResolvedValueOnce({ project: "/q", files: ["/q/b.cs"] });
await Promise.all([consumeLaunch(), consumeLaunch()]);
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
expect(opened).toEqual(["/q/b.cs (focus)"]);
expect(useProject.getState().project?.root).toBe("/q");
});
it("keeps handling launches after completing a launch fails", async () => {
useProject.setState(projectState("/p") as never);
windowCompleteLaunch.mockRejectedValueOnce(new Error("Connection interrupted"));
windowTakeLaunch.mockResolvedValueOnce({ files: ["/p/a.cs"] }).mockResolvedValueOnce({ files: ["/p/b.cs"] });
const first = consumeLaunch();
const second = consumeLaunch();
await expect(first).rejects.toThrow("Connection interrupted");
await second;
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
expect(opened).toEqual(["/p/a.cs (focus)", "/p/b.cs (focus)"]);
});
it("opens the pending project once", async () => {
windowTakeLaunch.mockResolvedValueOnce({ project: "/p/launch", files: [] }).mockResolvedValueOnce(null);
await consumeLaunch();
await consumeLaunch();
expect(openProject).toHaveBeenCalledTimes(1);
expect(openProject).toHaveBeenCalledWith("/p/launch");
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
});
it("opens launched files in LightEdit without a project", async () => {
@@ -480,7 +310,6 @@ describe("launch", () => {
windowTakeLaunch.mockResolvedValueOnce({ project: null, files: [], diff: { left: "/x/a.txt", right: "/x/b.txt" } });
await consumeLaunch();
expect(lightEditOpen).toHaveBeenCalledWith("/x/b.txt");
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
expect(diffs).toEqual([
{
path: "/x/b.txt",
@@ -495,7 +324,6 @@ describe("launch", () => {
windowTakeLaunch.mockResolvedValueOnce({ project: null, files: [], diff: { left: "/p/a.txt", right: "/p/b.txt" } });
await consumeLaunch();
expect(lightEditOpen).not.toHaveBeenCalled();
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
expect(diffs).toEqual([
{
path: "/p/b.txt",
@@ -504,90 +332,6 @@ describe("launch", () => {
},
]);
});
it("completes a failed CLI diff and handles the next file launch", async () => {
useProject.setState(projectState("/p") as never);
openDiff.mockRejectedValueOnce(new Error("Diff file unavailable"));
windowTakeLaunch
.mockResolvedValueOnce({ files: [], diff: { left: "/p/a.txt", right: "/p/b.txt" } })
.mockResolvedValueOnce({ files: ["/p/next.cs"], positions: [{ path: "/p/next.cs", line: 8, column: 2 }] });
const first = consumeLaunch();
const next = consumeLaunch();
await expect(first).rejects.toThrow("Diff file unavailable");
await next;
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
expect(opened).toEqual(["/p/next.cs (focus) @8:2"]);
});
it("applies a later source location after a pending diff", async () => {
useProject.setState(projectState("/p") as never);
windowTakeLaunch
.mockResolvedValueOnce({ files: [], diff: { left: "/p/a.txt", right: "/p/b.txt" } })
.mockResolvedValueOnce({ files: ["/p/next.cs"], positions: [{ path: "/p/next.cs", line: 8, column: 2 }] });
await Promise.all([consumeLaunch(), consumeLaunch()]);
expect(diffs).toHaveLength(1);
expect(opened).toEqual(["/p/next.cs (focus) @8:2"]);
expect(openDiff.mock.invocationCallOrder[0]).toBeLessThan(openEditorFile.mock.invocationCallOrder[0]!);
expect(windowCompleteLaunch).toHaveBeenCalledTimes(2);
});
it.each([
{ project: null, diffBeforeFiles: false },
{ project: "/p", diffBeforeFiles: false },
{ project: null, diffBeforeFiles: true },
{ project: "/p", diffBeforeFiles: true },
])(
"preserves the last request's focus for $project (diff first: $diffBeforeFiles)",
async ({ project, diffBeforeFiles }) => {
windowTakeLaunch.mockResolvedValueOnce({
project,
diffBeforeFiles,
files: ["/p/a.cs"],
positions: [{ path: "/p/a.cs", line: 8, column: 2 }],
diff: { left: "/p/left.txt", right: "/p/right.txt" },
});
await consumeLaunch();
expect(opened).toEqual(["/p/a.cs (focus) @8:2"]);
expect(diffs).toHaveLength(1);
const fileCall = openEditorFile.mock.invocationCallOrder[0]!;
const diffCall = openDiff.mock.invocationCallOrder[0]!;
expect(diffBeforeFiles ? diffCall : fileCall).toBeLessThan(diffBeforeFiles ? fileCall : diffCall);
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
},
);
it("opens later files when their preceding diff fails", async () => {
useProject.setState(projectState("/p") as never);
openDiff.mockRejectedValueOnce(new Error("Diff file unavailable"));
windowTakeLaunch.mockResolvedValueOnce({
files: ["/p/next.cs"],
positions: [{ path: "/p/next.cs", line: 8, column: 2 }],
diff: { left: "/p/a.txt", right: "/p/b.txt" },
diffBeforeFiles: true,
});
await consumeLaunch();
expect(opened).toEqual(["/p/next.cs (focus) @8:2"]);
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "Diff file unavailable" }));
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
});
it.each([false, true])(
"does not open a diff when its project launch is cancelled (diff first: %s)",
async (diffBeforeFiles) => {
openProject.mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Project opening cancelled" }));
windowTakeLaunch.mockResolvedValueOnce({
project: "/p",
diffBeforeFiles,
files: ["/p/a.cs"],
diff: { left: "/p/left.txt", right: "/p/right.txt" },
});
await consumeLaunch();
expect(opened).toEqual([]);
expect(diffs).toEqual([]);
expect(lightEditOpen).not.toHaveBeenCalled();
expect(windowCompleteLaunch).toHaveBeenCalledOnce();
},
);
});
describe("Attach", () => {
+25 -58
Переглянути файл
@@ -65,10 +65,10 @@ async function openHere(path: string): Promise<boolean> {
}
}
/** Opens `files` as editor tabs of this window, focusing the last. */
/** Caret positions of files opened from the command line (`--line` / `--column`), 0-based. */
type Positions = ReadonlyArray<{ path: string; line: number; column: number }>;
/** Opens `files` as editor tabs of this window, focusing the last. */
async function openInEditor(files: readonly string[], positions: Positions = []): Promise<void> {
for (const [i, path] of files.entries()) {
const at = positions.find((p) => p.path === path);
@@ -77,7 +77,7 @@ async function openInEditor(files: readonly string[], positions: Positions = [])
focus: i === files.length - 1,
...(at ? { selection: { line: at.line, col: at.column } } : {}),
})
.catch((e) => openFailed(path, e));
.catch((e) => console.warn(`could not open ${path}`, e));
}
}
@@ -213,53 +213,25 @@ async function pickFiles(title: string): Promise<string[]> {
}
/** Takes this window's pending launch (if any) and opens its project, files or diff pair. */
let launchQueue: Promise<void> = Promise.resolve();
export function consumeLaunch(): Promise<void> {
const request = launchQueue.then(consumePendingLaunch);
launchQueue = request.catch(() => {});
return request;
}
async function consumePendingLaunch(): Promise<void> {
export async function consumeLaunch(): Promise<void> {
if (!isTauri()) return;
const launch = await commands.windowTakeLaunch().catch(() => null);
if (!launch) return;
try {
// Session restoration may already be opening this window's project.
if (useProject.getState().opening) {
await new Promise<void>((resolve) => {
const off = useProject.subscribe((state) => {
if (!state.opening) {
off();
resolve();
}
});
});
}
const files = launch.files ?? [];
const positions = launch.positions ?? [];
if (launch.project && !(await openHere(launch.project))) return;
if (launch.diff && launch.diffBeforeFiles) {
const diff = launch.diff;
await openCliDiff(diff).catch((e) => openFailed(diff.right, e));
}
if (launch.project) {
await openInEditor(files, positions);
} else if (files.length) await openFilesHere(files, positions);
else if (launch.remote) {
const { target, path } = launch.remote;
await connectRemote(target, path).catch((e) =>
notifications().notify({
level: "error",
title: t("app.window.openFailed", { name: basename(path) }),
body: errorText(e),
key: `app.open:${path}`,
}),
);
}
if (launch.diff && !launch.diffBeforeFiles) await openCliDiff(launch.diff);
} finally {
await call(commands.windowCompleteLaunch());
const files = launch?.files ?? [];
const positions = launch?.positions ?? [];
if (launch?.project) {
if (await openHere(launch.project)) await openInEditor(files, positions);
} else if (files.length) await openFilesHere(files, positions);
else if (launch?.diff) await openCliDiff(launch.diff);
else if (launch?.remote) {
const { target, path } = launch.remote;
await connectRemote(target, path).catch((e) =>
notifications().notify({
level: "error",
title: t("app.window.openFailed", { name: basename(path) }),
body: errorText(e),
key: `app.open:${path}`,
}),
);
}
}
@@ -545,19 +517,14 @@ export function installLaunchHandling(): () => void {
if (!isTauri()) return () => {};
let disposed = false;
let unlisten: (() => void) | undefined;
const launch = import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => {
const off = await getCurrentWebviewWindow().listen(LAUNCH_EVENT, () => {
if (!disposed) void consumeLaunch().catch(console.warn);
});
if (disposed) off();
else {
unlisten = off;
// Subscribe before taking pending files so launches during startup aren't missed.
await consumeLaunch();
}
});
const launch = consumeLaunch();
provideStartupLaunch(launch);
holdSplash(launch);
void import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => {
const off = await getCurrentWebviewWindow().listen(LAUNCH_EVENT, () => void consumeLaunch());
if (disposed) off();
else unlisten = off;
});
return () => {
disposed = true;
unlisten?.();
+4 -5
Переглянути файл
@@ -6,7 +6,6 @@
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 {
@@ -59,8 +58,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 isBuildFile = (path: string) =>
isGradleBuildInput(path) || /(?:^|[\\/])(?:pom\.xml|mvnw(?:\.cmd)?|gradlew(?:\.bat)?)$/.test(path);
const BUILD_FILE =
/(?:^|\/)(?:pom\.xml|(?:build|settings)\.gradle(?:\.kts)?|mvnw(?:\.cmd)?|gradlew(?:\.bat)?|gradle\.properties|gradle-wrapper\.properties|[^/]+\.versions\.toml)$/;
function expandAll(tool: BuildTool) {
const { model, configs } = useBuild.getState();
@@ -235,10 +234,10 @@ export function activate(): () => void {
if (s.project) void loadModel();
}),
onEditorEvent((e) => {
if (e.type === "docSaved" && isBuildFile(e.path)) noteIdeSave(e.path);
if (e.type === "docSaved" && BUILD_FILE.test(e.path)) noteIdeSave(e.path);
}),
onIdeEvent("fsChanged", (e) => {
const changed = [...e.created, ...e.modified, ...e.removed].filter(isBuildFile);
const changed = [...e.created, ...e.modified, ...e.removed].filter((p) => BUILD_FILE.test(p));
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,7 +3,6 @@ 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";
@@ -113,22 +112,6 @@ 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"));
-51
Переглянути файл
@@ -1,51 +0,0 @@
.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
Переглянути файл
@@ -1,225 +0,0 @@
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
Переглянути файл
@@ -1,125 +0,0 @@
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
Переглянути файл
@@ -1,97 +0,0 @@
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
Переглянути файл
@@ -1,315 +0,0 @@
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,7 +21,6 @@ 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";
@@ -71,7 +70,6 @@ const features: Array<[string, Activate]> = [
["vcs", vcs],
["terminal", terminal],
["run", run],
["dotnet", dotnet],
["run-anything", runAnything],
["macros", macros],
["debugger", debuggerFeature],
+1 -2
Переглянути файл
@@ -9,7 +9,6 @@
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";
@@ -74,7 +73,7 @@ export function touchesManifest(paths: readonly string[]): boolean {
return paths.some(
(p) =>
!/[\\/]node_modules[\\/]/.test(p) &&
(isGradleBuildInput(p) || MANIFESTS.has(p.slice(Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\")) + 1))),
MANIFESTS.has(p.slice(Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\")) + 1)),
);
}
-7
Переглянути файл
@@ -78,13 +78,6 @@ 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);
-13
Переглянути файл
@@ -498,19 +498,6 @@ export function ConsoleView({
const items = virtualizer.getVirtualItems();
return (
<div className={styles.consoleWrap}>
{/* A console whose find bar is not driven by a toolbar (a stack-trace tab, say) still
needs a visible way in: the same Find the Run toolbar offers, over the output. */}
{controlledFindOpen === undefined && !findOpen && (
<button
type="button"
className={styles.consoleFindOpen}
title="Find…"
aria-label="Find in console"
onClick={() => setFindOpen(true)}
>
<Icon name="search" size={14} />
</button>
)}
{findOpen && (
<ConsoleFindBar
query={query}
-25
Переглянути файл
@@ -81,32 +81,7 @@
/* Console */
.consoleFindOpen {
position: absolute;
top: 6px;
right: 14px;
z-index: 2;
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
padding: 0;
border: none;
border-radius: 4px;
color: var(--fg-secondary);
background: var(--bg-toolbar);
opacity: 0.6;
}
.consoleFindOpen:hover,
.consoleFindOpen:focus-visible {
opacity: 1;
color: var(--fg-primary);
}
.consoleWrap {
position: relative;
flex: 1;
display: flex;
flex-direction: column;
+2 -23
Переглянути файл
@@ -12,14 +12,11 @@ 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) ||
@@ -47,7 +44,6 @@ 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"];
@@ -61,8 +57,6 @@ 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 ?? "")
@@ -216,26 +210,11 @@ 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,
content?: string,
): RunConfig | null {
export function testConfigFor(relPath: string, configs: RunConfig[], base?: RunConfig): 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]);
@@ -430,7 +409,7 @@ export function contextConfig(
windows = isWindows(),
): RunConfig | null {
const role = fileRole(relPath, content, windows, hasDjangoTests(configs));
if (role === "test") return testConfigFor(relPath, configs, undefined, content);
if (role === "test") return testConfigFor(relPath, configs);
if (role === "main") return mainConfigFor(relPath, configs) ?? scriptConfigFor(relPath, configs, windows, content);
if (role === "script") return scriptConfigFor(relPath, configs, windows, content);
return null;
-106
Переглянути файл
@@ -1,106 +0,0 @@
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
Переглянути файл
@@ -1,64 +0,0 @@
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;
}
+2 -44
Переглянути файл
@@ -2,7 +2,6 @@ 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;
@@ -21,7 +20,6 @@ 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)] : []),
],
@@ -127,50 +125,10 @@ 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);
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],
};
return { ...line, args: [...line.args, ...parseArgs(p.programArgs || "")] };
},
async prepareLaunch(config) {
const resolved = await prepareDotnetTest(await call(commands.runDotnetResolve(config, false)));
const resolved = await call(commands.runDotnetResolve(config, false));
return { ...resolved, ...dotnetTestType.commandLine(resolved.params ?? {}) };
},
};
-7
Переглянути файл
@@ -44,13 +44,6 @@ function markCount(container: HTMLElement) {
}
describe("Run console find", () => {
it("offers a visible Find entry in a console without a toolbar (stack traces)", () => {
setup();
fireEvent.click(screen.getByRole("button", { name: "Find in console" }));
expect(screen.getByRole("search")).toBeInTheDocument();
expect(input()).toHaveFocus();
});
it("opens on ⌘F, searches as you type and highlights every match", () => {
const { log, view } = setup();
const bar = openFind(log);
+2 -5
Переглянути файл
@@ -126,9 +126,6 @@ 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) } }
: {}),
@@ -746,7 +743,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, undefined, input.content);
const found = testConfigFor(rel, configs);
const test = found && goTestNamed(found, input);
if (test) return { name: test.name, scope: "file", config: test };
}
@@ -1105,7 +1102,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, input.content);
: testConfigFor(rel, [...input.configs], base);
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 -19
Переглянути файл
@@ -45,7 +45,6 @@ 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";
@@ -95,7 +94,6 @@ export interface RunSession {
}
interface SessionRuntime {
dotnetReports?: DotnetReports;
resolveRequest?: { id: RequestId; controller: AbortController };
console: ConsoleModel;
tests: TestResults | null;
@@ -655,7 +653,6 @@ 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: [],
@@ -897,16 +894,12 @@ 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 });
let started =
const 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)));
@@ -1035,15 +1028,6 @@ 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);
@@ -1136,8 +1120,6 @@ 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);
+2 -15
Переглянути файл
@@ -7,7 +7,6 @@
* 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";
@@ -44,10 +43,9 @@ 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" | "csharp" | null;
type Lang = "rust" | "js" | "python" | "php" | "go" | "jvm" | "ruby" | 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";
@@ -357,8 +355,6 @@ 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":
@@ -413,7 +409,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, content);
const file = testConfigFor(relPath, configs, base);
if (!file) return null;
if (target.className && (file.kind === "maven" || file.kind === "gradle"))
return jvmTestConfig(
@@ -431,15 +427,6 @@ 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
Переглянути файл
@@ -1,146 +0,0 @@
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
Переглянути файл
@@ -1,95 +0,0 @@
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
Переглянути файл
@@ -1,81 +0,0 @@
<?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
Переглянути файл
@@ -1,85 +0,0 @@
<?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
Переглянути файл
@@ -1,96 +0,0 @@
<?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
Переглянути файл
@@ -1,113 +0,0 @@
<?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>
+1 -6
Переглянути файл
@@ -23,13 +23,11 @@ export function combinedParser(parsers: TestOutputParser[]): TestOutputParser {
};
}
export type Framework = "cargo" | "js" | "pytest" | "unittest" | "phpunit" | "go" | "jvm" | "ruby" | "dotnet" | "auto";
export type Framework = "cargo" | "js" | "pytest" | "unittest" | "phpunit" | "go" | "jvm" | "ruby" | "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":
@@ -55,7 +53,6 @@ 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";
@@ -113,8 +110,6 @@ 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":
+1 -27
Переглянути файл
@@ -5,12 +5,11 @@
import { selectPluginTests } from "@/workbench/contributions";
import { phpunitArgs, phpunitFilter } from "./phpunit";
import type { RunConfig } from "@/platform/ipc";
import { formatArgs, parseArgs } from "../configs";
import { formatArgs } 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. */
@@ -68,11 +67,6 @@ 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));
@@ -208,26 +202,6 @@ 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;
-1
Переглянути файл
@@ -21,7 +21,6 @@ export const tomcatType: RunConfigTypeContribution = {
deployment: "artifact",
httpPort: "8080",
jmxPort: "1099",
// Build before launch (IDEA default); skipped automatically when the built WAR is current.
buildArtifact: "true",
openBrowser: "true",
...updatePolicyDefaults,
-277
Переглянути файл
@@ -228,280 +228,3 @@
border: 0;
background: none;
}
/* Dashboards, Layers & Processes (Phase 1) */
.dashboard {
flex: 1;
min-height: 0;
overflow: auto;
padding-bottom: 12px;
-webkit-user-select: text;
user-select: text;
}
.dashboardActions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
padding: 8px 12px;
border-bottom: 1px solid var(--border);
}
.sectionBanner {
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px 12px;
font-size: var(--fs-small);
font-weight: 600;
color: var(--fg-secondary);
background: var(--bg-elev);
border-top: 1px solid var(--border);
border-bottom: 1px solid var(--border);
}
.propList {
display: flex;
flex-direction: column;
}
.propRow {
display: grid;
grid-template-columns: 140px 1fr;
gap: 8px;
align-items: baseline;
padding: 5px 12px;
border-bottom: 1px solid var(--border);
}
.propName {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.propVal {
min-width: 0;
overflow-wrap: anywhere;
color: var(--fg);
}
.inlineRow {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.mono {
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.codeInline {
display: inline-block;
padding: 1px 6px;
border-radius: var(--radius-small);
background: var(--bg-elev);
font-family: var(--font-mono);
font-size: var(--fs-code);
overflow-wrap: anywhere;
}
.mutedMeta {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.statusBadge {
display: inline-flex;
align-items: center;
padding: 1px 6px;
border-radius: var(--radius-small);
font-size: var(--fs-small);
font-family: var(--font-mono);
}
.badgeOk {
color: var(--success);
background: color-mix(in srgb, var(--success) 16%, transparent);
}
.badgeWarn {
color: var(--warning);
background: color-mix(in srgb, var(--warning) 16%, transparent);
}
.badgeDanger {
color: var(--danger);
background: color-mix(in srgb, var(--danger) 16%, transparent);
}
.badgeMuted {
color: var(--fg-secondary);
background: var(--bg-elev);
}
.statusDot {
width: 7px;
height: 7px;
border-radius: 50%;
flex: none;
}
.dotOk {
background: var(--success);
}
.dotMuted {
background: var(--fg-subtle);
}
.metricBlock {
display: flex;
flex-direction: column;
gap: 4px;
max-width: 320px;
}
.lineProgress {
height: 5px;
width: 100%;
border-radius: 3px;
background: var(--bg-elev);
overflow: hidden;
}
.lineProgressFill {
height: 100%;
border-radius: 3px;
}
.progressNormal {
background: var(--accent);
}
.progressWarning {
background: var(--warning);
}
.progressDanger {
background: var(--danger);
}
.chipGroup {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 8px 12px;
}
.chipGroupInline {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.entityChip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 2px 8px;
border-radius: var(--radius-small);
border: 1px solid var(--border-strong);
background: var(--bg-elev);
color: var(--fg);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.entityChip:disabled {
cursor: default;
}
span.entityChip {
cursor: default;
}
button.entityChip:not(:disabled):hover {
background: var(--bg-hover);
border-color: var(--accent);
}
.portChipLink {
color: var(--link);
}
.chipMeta {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.emptySection {
padding: 8px 12px;
color: var(--fg-subtle);
font-size: var(--fs-small);
display: flex;
align-items: center;
gap: 6px;
}
.kvTable {
display: flex;
flex-direction: column;
}
.kvRow {
display: grid;
grid-template-columns: minmax(140px, 240px) 1fr;
gap: 10px;
padding: 4px 12px;
border-bottom: 1px solid var(--border);
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.kvKey {
color: var(--fg-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.kvVal {
color: var(--fg);
overflow-wrap: anywhere;
}
.dataTable {
display: flex;
flex-direction: column;
}
.dataRow {
display: grid;
grid-template-columns: 72px minmax(120px, 1fr) minmax(140px, 1.3fr) 56px;
gap: 8px;
align-items: center;
padding: 4px 12px;
border-bottom: 1px solid var(--border);
font-size: var(--fs-small);
}
.dataHeader {
color: var(--fg-secondary);
font-weight: 600;
}
.subToolbar {
height: 28px;
flex: none;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 8px 0 12px;
border-bottom: 1px solid var(--border);
}
.subToolbarTitle {
color: var(--fg-secondary);
font-size: var(--fs-small);
font-weight: 600;
}
.tableScroll {
flex: 1;
min-height: 0;
overflow: auto;
-webkit-user-select: text;
user-select: text;
}
.gridTable {
width: 100%;
border-collapse: collapse;
font-size: var(--fs-small);
}
.gridTable th {
position: sticky;
top: 0;
text-align: left;
padding: 5px 10px;
color: var(--fg-secondary);
background: var(--bg-elev);
border-bottom: 1px solid var(--border);
font-weight: 600;
white-space: nowrap;
}
.gridTable td {
padding: 4px 10px;
border-bottom: 1px solid var(--border);
vertical-align: top;
}
.layerCmd {
max-width: 520px;
overflow-wrap: anywhere;
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.layerSizeCell {
min-width: 96px;
white-space: nowrap;
}
-14
Переглянути файл
@@ -40,7 +40,6 @@ import {
useServicesTree,
} from "./tree";
import styles from "./Services.module.css";
import { viewFilterMenu } from "./ops";
import { selectionActions, selectionMenu, selectedServices } from "./selection";
export const SERVICES_VIEW_FOCUS = "servicesViewFocus";
@@ -89,7 +88,6 @@ export function ServicesTreeView() {
const selectedKeys = useServicesTree((s) => s.selectedKeys);
const expanded = useServicesTree((s) => s.expanded);
const addRef = useRef<HTMLButtonElement>(null);
const filterRef = useRef<HTMLButtonElement>(null);
const roots = useMemo(() => orderedRoots(rootsByProvider, providers), [rootsByProvider, providers]);
const index = useMemo(() => indexTree(rootsByProvider), [rootsByProvider]);
@@ -183,18 +181,6 @@ export function ServicesTreeView() {
disabled={!roots.length}
onClick={() => setExpanded(new Set())}
/>
<IconButton
ref={filterRef}
icon="filter"
size="small"
iconSize={16}
title="View Options"
disabled={!roots.length}
onClick={() => {
const r = filterRef.current?.getBoundingClientRect();
showContextMenu({ x: r?.left ?? 140, y: (r?.bottom ?? 100) + 2 }, viewFilterMenu());
}}
/>
{actions.length > 0 && <span className={styles.sep} />}
{actions.map((a) => (
<IconButton
File diff suppressed because it is too large. Load diff
+36 -142
Переглянути файл
@@ -10,7 +10,6 @@ import { Channel } from "@tauri-apps/api/core";
import type {
DockerAvailability,
DockerConnection,
DockerContainer,
DockerEndpoint,
DockerLogLine,
DockerObject,
@@ -29,7 +28,6 @@ import {
import { confirm } from "@/workbench/messages";
import { openConnectionDialog, openRegistryDialog } from "./dialogs";
import {
DEFAULT_DOCKER_FILTERS,
DOCKER_KEY,
childrenOf,
connectionKey,
@@ -42,20 +40,9 @@ import {
registryKey,
rootNodes,
treeKey,
type DockerFilters,
type DockerTarget,
type ServiceNode,
} from "./model";
import {
ComposeProjectDashboard,
ContainerDashboard,
ContainerProcessesView,
ImageDashboard,
ImageLayersView,
NetworkDashboard,
VolumeDashboard,
} from "./dashboard";
import { openContainerLogInEditor } from "./logEditor";
import {
canRemove,
canRestart,
@@ -81,7 +68,6 @@ import {
useServices,
watch,
type ConnectionState,
type DetailTab,
} from "./store";
import { useServicesTree } from "./tree";
import styles from "./Services.module.css";
@@ -115,12 +101,11 @@ export function dockerItems(
connections: readonly DockerConnection[],
registries: readonly DockerRegistry[],
conns: Record<string, ConnectionState>,
filters: DockerFilters = DEFAULT_DOCKER_FILTERS,
): ServiceTreeItem[] {
const items: ServiceTreeItem[] = connections.map((c) => {
const state = conns[c.id] ?? { snapshot: null, loading: false, error: null };
const snap = state.snapshot;
const children = childrenOf(snap, filters);
const children = childrenOf(snap);
const convert = (n: ServiceNode): ServiceTreeItem => {
const kids = children(n);
return {
@@ -136,14 +121,13 @@ export function dockerItems(
return {
key: connectionKey(c.id),
label: c.name,
icon: snap?.availability.kind === "ready" ? "docker-connected" : "file-docker",
icon: "file-docker",
detail: connectionDetail(state),
dim: snap?.availability.kind !== "ready",
children: children(root)?.map(convert) ?? [],
};
});
for (const r of registries)
items.push({ key: registryKey(r.id), label: r.name, icon: "docker-registry", detail: r.address });
for (const r of registries) items.push({ key: registryKey(r.id), label: r.name, icon: "package", detail: r.address });
return items;
}
@@ -221,7 +205,7 @@ function actions(item: ServiceTreeItem): ServiceItemAction[] {
disabled: !container || !isRunning(container),
run: () => execShell(t),
},
{ id: "pull", title: "Pull Image…", icon: "docker-pull", run: () => void pullPrompt(t.conn) },
{ id: "pull", title: "Pull Image…", icon: "git-pull", run: () => void pullPrompt(t.conn) },
];
}
@@ -291,23 +275,14 @@ export function DockerTaskBanner() {
}
/** Follows a container's log while shown. */
function LogView({ conn, container, running }: { conn: string; container: DockerContainer; running: boolean }) {
function LogView({ conn, id, running }: { conn: string; id: string; running: boolean }) {
const tx = useTx();
const id = container.id;
return (
<div className={styles.detailBody}>
<LogPane
sourceKey={`${conn}:${id}:${running}`}
live={running}
toggles={[{ id: "timestamps", label: "Timestamps" }]}
actions={
<IconButton
icon="external-link"
size="small"
title="Open Log in Editor"
onClick={() => openContainerLogInEditor(conn, container)}
/>
}
ariaLabel={tx("Container log")}
start={(onLine, onError, on) => {
const request = nextRequestId();
@@ -325,43 +300,21 @@ function LogView({ conn, container, running }: { conn: string; container: Docker
);
}
function useObjectInspect(conn: string, object: DockerObject | null, id: string | null) {
const [state, setState] = useState<{ key: string; text: string | null; error: string | null }>({
key: "",
text: null,
error: null,
});
const currentKey = object && id ? `${conn}:${object}:${id}` : "";
function InspectView({ conn, object, id }: { conn: string; object: DockerObject; id: string }) {
const tx = useTx();
const [text, setText] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!object || !id) return;
const reqKey = `${conn}:${object}:${id}`;
let alive = true;
call(commands.dockerInspect(endpointOf(conn), object, id))
.then((t) => alive && setState({ key: reqKey, text: t, error: null }))
.catch((e) => alive && setState({ key: reqKey, text: null, error: errorMessage(e) }));
.then((t) => alive && setText(t))
.catch((e) => alive && setError(errorMessage(e)));
return () => {
alive = false;
};
}, [conn, object, id]);
return state.key === currentKey ? { text: state.text, error: state.error } : { text: null, error: null };
}
function InspectView({ text, error }: { text: string | null; error: string | null }) {
const tx = useTx();
return (
<div className={styles.detailBody}>
<div className={styles.subToolbar}>
<span className={styles.subToolbarTitle}>
<T>Inspect JSON</T>
</span>
<IconButton
icon="copy"
size="small"
title="Copy"
disabled={!text}
onClick={() => text && void navigator.clipboard?.writeText(text)}
/>
</div>
<pre
tabIndex={0}
onKeyDown={copySelectionOnKeyDown}
@@ -409,26 +362,10 @@ function DockerDetail({ item }: { item: ServiceTreeItem }) {
const state = useServices((s) => (parsed ? connectionState(parsed.conn, s) : null));
const target = resolveTarget(item.key);
const registry = settings?.registries.find((r) => registryKey(r.id) === item.key);
const node = target?.node ?? null;
const object: DockerObject | null =
node && (node.kind === "container" || node.kind === "image" || node.kind === "volume" || node.kind === "network")
? node.kind
: null;
const objectId =
node?.kind === "container"
? node.container.id
: node?.kind === "image"
? node.image.id
: node?.kind === "volume"
? node.volume.name
: node?.kind === "network"
? node.network.id
: null;
const inspect = useObjectInspect(parsed?.conn ?? "default", object, objectId);
if (registry) return <RegistryDetail registry={registry} />;
if (!target || !parsed || !state || !node) return <EmptyState title="Select service to view details" />;
if (!target || !parsed || !state) return <EmptyState title="Select service to view details" />;
const conn = connectionOf(parsed.conn);
const node = target.node;
const snapshot = state.snapshot;
if (!snapshot)
return (
@@ -442,14 +379,7 @@ function DockerDetail({ item }: { item: ServiceTreeItem }) {
);
if (snapshot.availability.kind !== "ready")
return <Unavailable availability={snapshot.availability} conn={parsed.conn} />;
if (node.kind === "compose") {
return (
<div className={styles.detailPane}>
<ComposeProjectDashboard conn={parsed.conn} project={node.project} containers={node.containers} />
</div>
);
}
if (node.kind === "docker" || node.kind === "group") {
if (node.kind === "docker" || node.kind === "group" || node.kind === "compose") {
const a = snapshot.availability;
return (
<div className={styles.detailPane}>
@@ -458,7 +388,9 @@ function DockerDetail({ item }: { item: ServiceTreeItem }) {
<span className={styles.bannerText}>{snapshot.errors.join("; ")}</span>
</div>
)}
<EmptyState title={conn?.name ?? "Docker"}>
<EmptyState
title={node.kind === "compose" ? txTemplate(`Compose project '${node.project}'`) : (conn?.name ?? "Docker")}
>
<div>
{txTemplate(`Engine ${a.serverVersion} · CLI ${a.clientVersion}`)}
{a.context ? txTemplate(` · context ${a.context}`) : ""}
@@ -471,66 +403,32 @@ function DockerDetail({ item }: { item: ServiceTreeItem }) {
</div>
);
}
const tabItems: Array<{ id: DetailTab; label: string }> =
const object: DockerObject = node.kind;
const id =
node.kind === "container"
? [
{ id: "dashboard", label: "Dashboard" },
{ id: "log", label: "Log" },
{ id: "processes", label: "Processes" },
{ id: "inspect", label: "Inspect" },
]
? node.container.id
: node.kind === "image"
? [
{ id: "dashboard", label: "Dashboard" },
{ id: "layers", label: "Layers" },
{ id: "inspect", label: "Inspect" },
]
: [
{ id: "dashboard", label: "Dashboard" },
{ id: "inspect", label: "Inspect" },
];
const activeId: DetailTab = tabItems.some((t) => t.id === tab) ? tab : "dashboard";
const id = objectId!;
? node.image.id
: node.kind === "volume"
? node.volume.name
: node.network.id;
const showLog = node.kind === "container" && tab === "log";
return (
<div className={styles.detailPane}>
<Tabs
variant="compact"
activeId={activeId}
onSelect={(t) => useServices.setState({ detailTab: t as DetailTab })}
activeId={showLog ? "log" : "inspect"}
onSelect={(t) => useServices.setState({ detailTab: t as "log" | "inspect" })}
aria-label="Details"
items={tabItems}
items={[
...(node.kind === "container" ? [{ id: "log", label: "Log" }] : []),
{ id: "inspect", label: "Inspect" },
]}
/>
{activeId === "log" && node.kind === "container" ? (
<LogView key={id} conn={parsed.conn} container={node.container} running={isRunning(node.container)} />
) : activeId === "processes" && node.kind === "container" ? (
<ContainerProcessesView key={id} conn={parsed.conn} id={id} running={isRunning(node.container)} />
) : activeId === "layers" && node.kind === "image" ? (
<ImageLayersView key={id} conn={parsed.conn} id={id} />
) : activeId === "inspect" ? (
<InspectView key={id} text={inspect.text} error={inspect.error} />
) : node.kind === "container" ? (
<ContainerDashboard
key={id}
conn={parsed.conn}
container={node.container}
snapshot={snapshot}
inspectText={inspect.text}
/>
) : node.kind === "image" ? (
<ImageDashboard key={id} conn={parsed.conn} image={node.image} snapshot={snapshot} inspectText={inspect.text} />
) : node.kind === "volume" ? (
<VolumeDashboard key={id} conn={parsed.conn} volume={node.volume} snapshot={snapshot} />
{showLog ? (
<LogView key={id} conn={parsed.conn} id={id} running={isRunning(node.container)} />
) : (
<NetworkDashboard
key={id}
conn={parsed.conn}
network={node.network}
snapshot={snapshot}
inspectText={inspect.text}
/>
<InspectView key={id} conn={parsed.conn} object={object} id={id} />
)}
</div>
);
@@ -539,11 +437,7 @@ function DockerDetail({ item }: { item: ServiceTreeItem }) {
function useRoots(): ServiceTreeItem[] {
const settings = useServices((s) => s.settings);
const conns = useServices((s) => s.conns);
const filters = useServices((s) => s.filters);
return useMemo(
() => dockerItems(settings?.connections ?? [], settings?.registries ?? [], conns, filters),
[settings, conns, filters],
);
return useMemo(() => dockerItems(settings?.connections ?? [], settings?.registries ?? [], conns), [settings, conns]);
}
export const dockerProvider: ServiceProviderContribution = {
@@ -562,7 +456,7 @@ export const dockerProvider: ServiceProviderContribution = {
detail: DockerDetail,
banner: DockerTaskBanner,
addMenu: () => [
{ label: "Docker Registry…", icon: "docker-registry", run: () => openRegistryDialog() },
{ label: "Docker Registry…", icon: "package", run: () => openRegistryDialog() },
{ label: "Docker Connection…", icon: "file-docker", run: () => openConnectionDialog() },
],
};
+2 -71
Переглянути файл
@@ -12,7 +12,6 @@ import { registerActions } from "@/platform/actions";
import { registerEditorContribution } from "@/editor/api";
import {
SERVICES_WINDOW,
registerEditorKind,
registerOverlay,
registerServiceProvider,
registerServiceView,
@@ -23,7 +22,6 @@ import { dockerGutter } from "./dockerGutter";
import { registerDockerRunTypes } from "./runTypes";
import { ServicesDialogHost } from "./dialogs";
import { dockerProvider, selectedTarget } from "./docker";
import { DOCKER_LOG_EDITOR_KIND, DockerLogEditor, dockerLogEditorTitle, openContainerLogInEditor } from "./logEditor";
import {
canRemove,
canStart,
@@ -39,7 +37,7 @@ import {
} from "./ops";
import { SERVICES_VIEW_FOCUS, ServicesTreeView, showAddServiceMenu } from "./ServicesTree";
import { ServicesHeaderActions, ServicesHost, ServicesTabs } from "./ServicesHost";
import { connections, refresh, setDockerFilters, useServices } from "./store";
import { connections, refresh } from "./store";
import { SERVICES_TREE_VIEW } from "./tree";
import { isRunning } from "./model";
import type { PruneTarget } from "@/platform/ipc";
@@ -70,13 +68,6 @@ export function activate(): () => void {
component: ServicesTreeView,
}),
registerServiceProvider(dockerProvider),
registerEditorKind({
kind: DOCKER_LOG_EDITOR_KIND,
component: DockerLogEditor,
title: dockerLogEditorTitle,
icon: () => "file-log",
keepAlive: true,
}),
registerOverlay({ id: "services.dialogs", component: ServicesDialogHost }),
registerEditorContribution({ id: "services.dockerGutter", order: 56, extensions: dockerGutter }),
registerDockerRunTypes(),
@@ -144,17 +135,6 @@ export function activate(): () => void {
when: PROJECT,
run: () => (canRemove(selectedTarget()) ? remove(selectedTarget()) : undefined),
},
{
id: "docker.showDashboard",
title: "Show Docker Dashboard",
category: "Docker",
icon: "layout",
when: PROJECT,
run: () => {
showDetail("dashboard");
showServiceView(SERVICES_TREE_VIEW, true);
},
},
{
id: "docker.showLog",
title: "Show Container Log",
@@ -165,39 +145,6 @@ export function activate(): () => void {
showServiceView(SERVICES_TREE_VIEW, true);
},
},
{
id: "docker.openLogInEditor",
title: "Open Container Log in Editor",
category: "Docker",
icon: "file-log",
when: PROJECT,
run: () => {
const t = selectedTarget();
if (t?.node.kind === "container") openContainerLogInEditor(t.conn, t.node.container);
},
},
{
id: "docker.showProcesses",
title: "Show Container Processes",
category: "Docker",
icon: "list",
when: PROJECT,
run: () => {
showDetail("processes");
showServiceView(SERVICES_TREE_VIEW, true);
},
},
{
id: "docker.showLayers",
title: "Show Image Layers",
category: "Docker",
icon: "list",
when: PROJECT,
run: () => {
showDetail("layers");
showServiceView(SERVICES_TREE_VIEW, true);
},
},
{
id: "docker.inspect",
title: "Inspect Docker Object",
@@ -209,22 +156,6 @@ export function activate(): () => void {
showServiceView(SERVICES_TREE_VIEW, true);
},
},
{
id: "docker.toggleStoppedContainers",
title: "Toggle Stopped Containers",
category: "Docker",
icon: "filter",
when: PROJECT,
run: () => setDockerFilters({ showStoppedContainers: !useServices.getState().filters.showStoppedContainers }),
},
{
id: "docker.toggleUntaggedImages",
title: "Toggle Untagged Images",
category: "Docker",
icon: "filter",
when: PROJECT,
run: () => setDockerFilters({ showUntaggedImages: !useServices.getState().filters.showUntaggedImages }),
},
{
id: "docker.execShell",
title: "Create Terminal in Container",
@@ -241,7 +172,7 @@ export function activate(): () => void {
id: "docker.pullImage",
title: "Pull Docker Image…",
category: "Docker",
icon: "docker-pull",
icon: "git-pull",
when: PROJECT,
run: () => {
const conn = currentConnection();
-442
Переглянути файл
@@ -1,442 +0,0 @@
/**
* Container log in a regular CodeMirror 6 Editor Tab (`DOCKER_LOG_EDITOR_KIND`),
* with log syntax highlighting, line numbers, Timestamps & Soft-wrap toggles,
* Find (`⌘F`) and font zoom (`⌘=` / `⌘-` / `⌘0`), matching `PluginLogEditor`.
*/
import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { Channel } from "@tauri-apps/api/core";
import { Compartment, EditorState, Prec, type StateEffect } from "@codemirror/state";
import { EditorView, highlightSpecialChars, keymap } from "@codemirror/view";
import { defaultKeymap } from "@codemirror/commands";
import { LanguageSupport, syntaxHighlighting } from "@codemirror/language";
import { caretRowHighlight } from "@/editor/core/cm/caretRow";
import { findExtension, findResultLines, findScope, type FindOptions } from "@/editor/core/cm/find";
import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
import { overviewLane } from "@/editor/core/cm/lanes";
import { logLanguage } from "@/editor/core/cm/log";
import { caretExtension, fontZoom, setFontZoom, softWrapActive, stepFontZoom } from "@/editor/core/cm/prefs";
import { fontExtension, heavyExtension, lineNumbersExtension, prefsOf } from "@/editor/core/cm/setup";
import { openideaTheme } from "@/editor/core/cm/theme";
import { FindPanel, searchAgain, seedFind, type FindTarget } from "@/editor/core/view/FindBar";
import { editorPrefs } from "@/platform/editorSettings";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled, nextRequestId, type DockerContainer, type DockerLogLine } from "@/platform/ipc";
import { bindingsFor, normalizeBinding, registerKeyClaim, strokeOf } from "@/platform/keymap";
import { useProject } from "@/platform/project";
import { EmptyState, IconButton, Toggle, selectableText } from "@/ui";
import logStyles from "@/ui/LogPane.module.css";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { isRunning } from "./model";
import { connectionState, endpointOf, errorMessage, useServices } from "./store";
export const DOCKER_LOG_EDITOR_KIND = "dockerLog";
export interface DockerLogEditorData {
conn: string;
containerId: string;
containerName: string;
}
export function dockerLogEditorTitle(input: EditorInput): string {
const data = input.data as Partial<DockerLogEditorData> | undefined;
return data?.containerName ? `${data.containerName} (Log)` : input.key;
}
export function openContainerLogInEditor(conn: string, container: DockerContainer): void {
const data: DockerLogEditorData = {
conn,
containerId: container.id,
containerName: container.name,
};
void editorService().openInput({
kind: DOCKER_LOG_EDITOR_KIND,
key: `${DOCKER_LOG_EDITOR_KIND}:${conn}:${container.id}`,
data,
});
}
const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g; // eslint-disable-line no-control-regex
function boundedLog(text: string): string {
let result = text.slice(-(1 << 20));
if (/^[\uDC00-\uDFFF]/.test(result)) result = result.slice(1);
const lines = result.split("\n");
if (lines.length > 5000) result = lines.slice(-5000).join("\n");
return result;
}
function isActionStroke(stroke: string | null, actionId: string): boolean {
return !!stroke && bindingsFor(actionId).some((b) => normalizeBinding(b) === stroke);
}
const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
export function DockerLogEditor({ input }: { input: EditorInput }) {
const data = input.data as DockerLogEditorData | undefined;
if (!data || !data.containerId) {
return <EmptyState title={tx("Invalid log stream configuration")} />;
}
return <DockerLogEditorBody input={input} data={data} />;
}
function DockerLogEditorBody({ input, data }: { input: EditorInput; data: DockerLogEditorData }) {
const initialWrap = useMemo(() => {
const s = useProject.getState().settings?.editor;
return softWrapActive(s?.softWrap ?? true, prefsOf(s), "stream.log");
}, []);
const [timestamps, setTimestamps] = useState(false);
const [wrap, setWrap] = useState<boolean>(initialWrap);
const [find, setFind] = useState<{ seq: number } | null>(null);
const [viewGen, setViewGen] = useState(0);
const running = useServices((s) => {
const c = connectionState(data.conn, s).snapshot?.containers.find((x) => x.id === data.containerId);
return c ? isRunning(c) : true;
});
const rootRef = useRef<HTMLDivElement>(null);
const hostRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
const wrapSlotRef = useRef(new Compartment());
const stickRef = useRef(true);
const receivedRef = useRef(false);
const findOpenRef = useRef(false);
const findWatchersRef = useRef(new Set<(u: { docChanged: boolean; selectionSet: boolean }) => void>());
const findEscapeRef = useRef<() => boolean>(() => false);
const findId = useId();
const title = `${data.containerName} (Log)`;
const findTarget = useMemo<FindTarget>(
() => ({
id: `dockerLog:${findId}:${input.key}`,
view: () => viewRef.current,
watch(fn) {
findWatchersRef.current.add(fn);
return () => void findWatchersRef.current.delete(fn);
},
isOpen: () => findOpenRef.current,
results(options: FindOptions) {
const view = viewRef.current;
if (!view) return null;
const state = view.state;
const scope = state.field(findScope, false) ?? { from: 0, to: state.doc.length };
return {
title: tx`Occurrences of '${options.search}'`,
query: {
pattern: options.search,
isRegex: options.regexp,
caseSensitive: options.caseSensitive,
wholeWord: options.wholeWord,
context: options.context,
include: [],
exclude: [],
scope: { kind: "files", paths: [title] },
maxMatches: 0,
},
read: () => ({
path: title,
relPath: title,
matches: findResultLines(
viewRef.current?.state ?? state,
options,
state.field(findScope, false)
? ((viewRef.current?.state ?? state).field(findScope, false) ?? scope)
: { from: 0, to: (viewRef.current?.state ?? state).doc.length },
),
}),
};
},
}),
[findId, input.key, title],
);
const openFind = () => {
if (!viewRef.current) return;
findOpenRef.current = true;
seedFind(findTarget, false);
setFind((f) => ({ seq: (f?.seq ?? 0) + 1 }));
};
const closeFind = () => {
findOpenRef.current = false;
setFind(null);
viewRef.current?.focus();
};
findEscapeRef.current = () => {
if (!findOpenRef.current) return false;
closeFind();
return true;
};
useEffect(() => {
const host = hostRef.current;
if (!host) return;
const fontSlot = new Compartment();
const caretSlot = new Compartment();
const lineNumbersSlot = new Compartment();
const heavySlot = new Compartment();
const wrapSlot = wrapSlotRef.current;
const editorSettings = () => useProject.getState().settings?.editor;
const view = new EditorView({
parent: host,
state: EditorState.create({
doc: tx("Waiting for output…"),
extensions: [
fontSlot.of(fontExtension(editorSettings())),
caretSlot.of(caretExtension(editorPrefs())),
lineNumbersSlot.of(lineNumbersExtension(editorSettings())),
wrapSlot.of(wrap ? EditorView.lineWrapping : []),
heavySlot.of(heavyExtension(0, editorSettings())),
fontZoom,
wheelZoom,
caretRowHighlight,
openideaTheme,
highlightSpecialChars(),
syntaxHighlighting(openideaHighlightStyle),
new LanguageSupport(logLanguage),
findExtension(),
overviewLane,
Prec.high(keymap.of([{ key: "Escape", run: () => findEscapeRef.current() }])),
keymap.of(defaultKeymap),
EditorState.readOnly.of(true),
EditorView.editable.of(false),
EditorView.contentAttributes.of({
"aria-label": title,
class: selectableText,
tabindex: "0",
}),
EditorView.updateListener.of((u) => {
if (u.docChanged || u.selectionSet) {
findWatchersRef.current.forEach((fn) => fn(u));
}
}),
],
}),
});
viewRef.current = view;
setViewGen((g) => g + 1);
const onScroll = () => {
const el = view.scrollDOM;
stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 32;
};
view.scrollDOM.addEventListener("scroll", onScroll, { passive: true });
let prevAppearance = editorPrefs().appearance;
let prevEditor = editorSettings();
const offSettings = useProject.subscribe(() => {
const effects: StateEffect<unknown>[] = [];
const nextPrefs = editorPrefs();
const nextEditor = editorSettings();
if (JSON.stringify(nextPrefs.appearance) !== JSON.stringify(prevAppearance)) {
prevAppearance = nextPrefs.appearance;
effects.push(caretSlot.reconfigure(caretExtension(nextPrefs)));
}
if (nextEditor !== prevEditor) {
prevEditor = nextEditor;
effects.push(
fontSlot.reconfigure(fontExtension(nextEditor)),
lineNumbersSlot.reconfigure(lineNumbersExtension(nextEditor)),
heavySlot.reconfigure(heavyExtension(view.state.doc.length, nextEditor)),
);
}
if (effects.length) view.dispatch({ effects });
});
return () => {
offSettings();
view.scrollDOM.removeEventListener("scroll", onScroll);
view.destroy();
viewRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [title]);
useEffect(() => {
const view = viewRef.current;
if (!view) return;
view.dispatch({
effects: wrapSlotRef.current.reconfigure(wrap ? EditorView.lineWrapping : []),
});
}, [wrap]);
useEffect(() => {
return registerKeyClaim((e, stroke) => {
if (!rootRef.current?.contains(e.target as Node)) return false;
const view = viewRef.current;
if (!view) return false;
if (isActionStroke(stroke, "find.inFile") || stroke === "Meta+F" || stroke === "Ctrl+F") {
e.preventDefault();
e.stopPropagation();
openFind();
return true;
}
if (isActionStroke(stroke, "find.next") || isActionStroke(stroke, "find.previous")) {
e.preventDefault();
e.stopPropagation();
if (!searchAgain(findTarget, isActionStroke(stroke, "find.next"))) openFind();
return true;
}
if (
isActionStroke(stroke, "editor.increaseFontSize") ||
stroke === "Meta+=" ||
stroke === "Meta+Shift+=" ||
stroke === "Ctrl+=" ||
stroke === "Ctrl+Shift+=" ||
stroke === "Meta+NumpadAdd" ||
stroke === "Ctrl+NumpadAdd"
) {
e.preventDefault();
e.stopPropagation();
stepFontZoom(view, 1);
return true;
}
if (
isActionStroke(stroke, "editor.decreaseFontSize") ||
stroke === "Meta+-" ||
stroke === "Meta+Shift+-" ||
stroke === "Ctrl+-" ||
stroke === "Ctrl+Shift+-" ||
stroke === "Meta+NumpadSubtract" ||
stroke === "Ctrl+NumpadSubtract"
) {
e.preventDefault();
e.stopPropagation();
stepFontZoom(view, -1);
return true;
}
if (isActionStroke(stroke, "editor.resetFontSize") || stroke === "Meta+0" || stroke === "Ctrl+0") {
e.preventDefault();
e.stopPropagation();
view.dispatch({ effects: setFontZoom.of(0) });
return true;
}
if (stroke === "Escape" && findOpenRef.current) {
e.preventDefault();
e.stopPropagation();
closeFind();
return true;
}
return false;
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [findTarget]);
const onKeyDown = (e: KeyboardEvent) => {
if (e.defaultPrevented) return;
const stroke = strokeOf(e.nativeEvent);
const view = viewRef.current;
if (!view || !stroke) return;
if (isActionStroke(stroke, "find.inFile") || stroke === "Meta+F" || stroke === "Ctrl+F") {
openFind();
} else if (isActionStroke(stroke, "find.next") || isActionStroke(stroke, "find.previous")) {
if (!searchAgain(findTarget, isActionStroke(stroke, "find.next"))) openFind();
} else if (
isActionStroke(stroke, "editor.increaseFontSize") ||
stroke === "Meta+=" ||
stroke === "Meta+Shift+=" ||
stroke === "Ctrl+="
) {
stepFontZoom(view, 1);
} else if (
isActionStroke(stroke, "editor.decreaseFontSize") ||
stroke === "Meta+-" ||
stroke === "Meta+Shift+-" ||
stroke === "Ctrl+-"
) {
stepFontZoom(view, -1);
} else if (isActionStroke(stroke, "editor.resetFontSize") || stroke === "Meta+0" || stroke === "Ctrl+0") {
view.dispatch({ effects: setFontZoom.of(0) });
} else if (e.key === "Escape" && findOpenRef.current) {
closeFind();
} else {
return;
}
e.preventDefault();
e.stopPropagation();
};
useEffect(() => {
const view = viewRef.current;
if (!view) return;
receivedRef.current = false;
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: tx("Waiting for output…") } });
stickRef.current = true;
let stopped = false;
let buffer: string[] = [];
let frame = 0;
const append = (chunk: string) => {
if (stopped || !viewRef.current) return;
const v = viewRef.current;
const previous = receivedRef.current ? v.state.doc.toString() : "";
receivedRef.current = true;
const joined = previous ? `${previous}\n${chunk}` : chunk;
const result = boundedLog(joined);
const stick = stickRef.current;
v.dispatch({ changes: { from: 0, to: v.state.doc.length, insert: result } });
if (stick && !findOpenRef.current) v.scrollDOM.scrollTop = v.scrollDOM.scrollHeight;
};
const flush = () => {
frame = 0;
if (!buffer.length) return;
const lines = buffer;
buffer = [];
append(lines.join("\n"));
};
const request = nextRequestId();
const channel = new Channel<DockerLogLine>();
channel.onmessage = (line) => {
if (stopped) return;
buffer.push(line.text.replace(ANSI, ""));
frame ||= requestAnimationFrame(flush);
};
call(
commands.dockerLogs(request, endpointOf(data.conn), data.containerId, 1000, running, timestamps, channel),
).catch((e) => {
if (!stopped && !isCancelled(e)) {
append(`Error: ${errorMessage(e)}`);
}
});
return () => {
stopped = true;
if (frame) cancelAnimationFrame(frame);
void commands.cancelRequest(request);
};
}, [data.conn, data.containerId, running, timestamps]);
const clearLogs = () => {
const view = viewRef.current;
if (!view) return;
receivedRef.current = true;
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: "" },
});
};
return (
<div ref={rootRef} className={logStyles.pane} onKeyDown={onKeyDown}>
<div className={logStyles.toolbar}>
<Toggle checked={timestamps} onChange={setTimestamps} label="Timestamps" aria-label="Timestamps" />
<Toggle checked={wrap} onChange={setWrap} label="Soft-wrap" aria-label="Soft-wrap" />
<span className={logStyles.flex} />
<IconButton icon="search" size="small" title="Find in Logs" onClick={openFind} />
<IconButton icon="trash" size="small" title="Clear" onClick={clearLogs} />
</div>
{find && <FindPanel target={findTarget} version={viewGen} replace={false} seq={find.seq} onClose={closeFind} />}
<div ref={hostRef} className={logStyles.output} />
</div>
);
}
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff. Show more