Файли
openidea/crates/ide-host/tests/replace_all.rs
T
Mr0Bread b60b743843 refactor(ide-host): shared test HostConfig constructors replace ~100 copied literals (#5501)
`HostConfig` (9 fields) was written out as a full struct literal in about 100 tests of `ide-host`, almost all of them the same boilerplate, so a new field meant editing ~100 places. This adds one base constructor for tests and migrates every literal that is a plain variant of it. Tests that differ keep struct-update overrides (`HostConfig { sink_for: .., ..HostConfig::for_test(&base) }`). No builder.
- Unit tests (`src/`): `#[cfg(test)] pub(crate) fn HostConfig::for_test(base: &Path)` in `lib.rs`.
- Integration tests (`tests/`): `tests/common/mod.rs` with `host_config(base: &Path)`, pulled in with `mod common;`. It builds the same value as `for_test`.
Both build: `config`, `data`, and `data` again as the machine-local dir (the layout most tests used), `LanguageRegistry::load(None)`, empty syntax, a sink that drops events, identity owner, `Handle::current()`, `project_environment: false`.
Why not one constructor for both: integration tests compile against the crate without `cfg(test)`, so a shared one needs a new `testing` cargo feature plus a dev-dependency on the crate itself (nothing in `ide-host` does that today). Two small definitions need no feature, no `Cargo.toml` change and no public item.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:02:21 +08:00

223 рядки
8.9 KiB
Rust

//! Replace All when the search hit its match limit (#4083): every match in the
//! scope is replaced, not just the listed ones.
mod common;
use ide_core::{Pos, RequestId};
use ide_host::{Host, ops};
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery};
use std::sync::{Arc, Mutex};
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
serde_json::from_value(serde_json::json!({"pattern": pattern, "isRegex": is_regex, "caseSensitive": true, "wholeWord": false, "include": [], "exclude": [], "scope": {"kind": "project"}, "maxMatches": 2000})).unwrap()
}
struct Case {
name: &'static str,
files: Vec<(&'static str, String)>,
pattern: &'static str,
is_regex: bool,
replacement: &'static str,
/// `(file, positions)` sent as targets: `skip` with `all_in_scope`, else `only`.
targets: Vec<(&'static str, Vec<Pos>)>,
all_in_scope: bool,
expected: Vec<(&'static str, String)>,
replaced: u32,
}
fn lines(n: usize, text: &str) -> String {
format!("{text}\n").repeat(n)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn replace_all_covers_matches_past_the_limit() {
let cases = vec![
Case {
name: "one file, 2001 matches (the report)",
files: vec![("repeated.txt", lines(2001, "CAP_PROBE"))],
pattern: "CAP_PROBE",
is_regex: false,
replacement: "CAP_CHANGED",
targets: vec![],
all_in_scope: true,
expected: vec![("repeated.txt", lines(2001, "CAP_CHANGED"))],
replaced: 2001,
},
Case {
name: "several files, unlisted ones too",
files: vec![("a.txt", lines(1500, "CAP")), ("b.txt", lines(1500, "CAP")), ("sub/c.txt", "x CAP\n".into())],
pattern: "CAP",
is_regex: false,
replacement: "Z",
targets: vec![],
all_in_scope: true,
expected: vec![("a.txt", lines(1500, "Z")), ("b.txt", lines(1500, "Z")), ("sub/c.txt", "x Z\n".into())],
replaced: 3001,
},
Case {
name: "excluded usages are kept",
files: vec![("repeated.txt", lines(2001, "CAP_PROBE"))],
pattern: "CAP_PROBE",
is_regex: false,
replacement: "CAP_CHANGED",
targets: vec![("repeated.txt", vec![Pos::new(0, 0), Pos::new(2000, 0)])],
all_in_scope: true,
expected: vec![("repeated.txt", format!("CAP_PROBE\n{}CAP_PROBE\n", lines(1999, "CAP_CHANGED")))],
replaced: 1999,
},
Case {
name: "regex with groups",
files: vec![("repeated.txt", lines(2001, "CAP_PROBE"))],
pattern: r"CAP_(\w+)",
is_regex: true,
replacement: "${1}_CAP",
targets: vec![],
all_in_scope: true,
expected: vec![("repeated.txt", lines(2001, "PROBE_CAP"))],
replaced: 2001,
},
Case {
name: "Replace Selected keeps to the selected usages",
files: vec![("repeated.txt", lines(3, "CAP_PROBE"))],
pattern: "CAP_PROBE",
is_regex: false,
replacement: "CAP_CHANGED",
targets: vec![("repeated.txt", vec![Pos::new(1, 0)])],
all_in_scope: false,
expected: vec![("repeated.txt", "CAP_PROBE\nCAP_CHANGED\nCAP_PROBE\n".into())],
replaced: 1,
},
];
for case in cases {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
for (path, text) in &case.files {
let path = root.join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let targets = case
.targets
.iter()
.map(|(path, at)| {
let path = root.join(path).into();
if case.all_in_scope {
ReplaceTarget { path, only: None, skip: Some(at.clone()) }
} else {
ReplaceTarget { path, only: Some(at.clone()), skip: None }
}
})
.collect();
let summary = Arc::new(Mutex::new(ReplaceSummary::default()));
let out = summary.clone();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
query(case.pattern, case.is_regex),
case.replacement.into(),
false,
targets,
case.all_in_scope,
ops::Channel::new(move |e| {
if let ReplaceEvent::Done { summary } = e {
*out.lock().unwrap() = summary;
}
}),
)
.await
.unwrap();
for (path, text) in &case.expected {
assert_eq!(&std::fs::read_to_string(root.join(path)).unwrap(), text, "{}: {path}", case.name);
}
assert_eq!(summary.lock().unwrap().replacements, case.replaced, "{}", case.name);
host.close_project("main");
}
}
/// #4202: a file the search preview holds open (no unsaved changes) is saved like a closed
/// one; a buffer with unsaved edits is replaced in place and left for the editor to save.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
std::fs::write(root.join(name), "TOKEN\n").unwrap();
}
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let project = host.project("main").unwrap();
project.documents.open(&root.join("previewed.txt")).unwrap();
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
query("TOKEN", false),
"DONE".into(),
false,
vec![],
true,
ops::Channel::new(|_| {}),
)
.await
.unwrap();
let disk = |name: &str| std::fs::read_to_string(root.join(name)).unwrap();
assert_eq!(disk("previewed.txt"), "DONE\n");
assert_eq!(disk("closed.txt"), "DONE\n");
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
host.close_project("main");
}
/// Replace All past the limit replaces what the search lists: only the matches its Search
/// Context keeps (comments, string literals or code), as below the limit.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn replace_all_past_the_limit_keeps_to_the_search_context() {
use ide_search::SearchContext as C;
let comments = |word: &str| lines(2001, &format!("// {word}"));
let code = |name: &str, string: &str| format!("fn {name}() -> &'static str {{ \"{string}\" }}\n");
let original = format!("{}{}", comments("tok"), code("tok", "tok"));
let cases = [
(C::Any, format!("{}{}", comments("X"), code("X", "X"))),
(C::InComments, format!("{}{}", comments("X"), code("tok", "tok"))),
(C::InStringLiterals, format!("{}{}", comments("tok"), code("tok", "X"))),
(C::ExceptComments, format!("{}{}", comments("tok"), code("X", "X"))),
(C::ExceptStringLiterals, format!("{}{}", comments("X"), code("X", "tok"))),
(C::ExceptCommentsAndStringLiterals, format!("{}{}", comments("tok"), code("X", "tok"))),
];
for (context, expected) in cases {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("lib.rs"), &original).unwrap();
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
SearchQuery { context, ..query("tok", false) },
"X".into(),
false,
vec![],
true,
ops::Channel::new(|_| {}),
)
.await
.unwrap();
assert_eq!(std::fs::read_to_string(root.join("lib.rs")).unwrap(), expected, "{context:?}");
host.close_project("main");
}
}