Файли
openidea/crates/ide-host/tests/python_rename_comments.rs
T
LU XIANGRUIтаwildcatDownstairs fa0783ab03 feat(python): search in comments and strings when renaming a symbol (#7679)
The Python Rename dialog offers Search in comments and strings (off by default, remembered; in-place rename follows it). Whole-word, case-sensitive matches in comments and string text are merged into the language server's workspace edit, so they preview, apply and undo with it; a rename that gains text matches is always previewed with the matches under Non-code usages, and applying fails if a matched file changed after the preview. Locals and parameters are searched in their function, other symbols in the project's .py / .pyi files including unsaved buffers; symlinks leading out of the project are skipped.

Refs #4968

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 17:23:45 +08:00

174 рядки
8.1 KiB
Rust

//! Python rename's "Search in comments and strings" against the real basedpyright: the rename, the
//! merged edit the preview shows, applying it and undoing it in one step. Needs
//! `basedpyright-langserver` on PATH:
//! `cargo test -p ide-host --test python_rename_comments -- --ignored`
mod common;
use ide_core::{IdeEvent, Pos, RequestId, WorkspaceEdit};
use ide_host::{Host, HostConfig, ops};
use parking_lot::Mutex;
use std::{path::Path, sync::Arc, time::Duration};
const LIB: &str = r#"__all__ = ["load_user"]
def load_user(user_id):
"""Run load_user(user_id) for one user_id.
>>> load_user(1)
"""
# load_user reads user_id; reload_user and load_users stay.
label = f"load_user {user_id} \"user_id\" \nuser_id"
return user_id, label
class Repo:
def load_user(self):
# unrelated method of the same name
return None
def other():
# user_id outside load_user
return "user_id"
"#;
const APP: &str = r#"from lib import load_user
# 😀 café: load_user
print("😀 load_user", load_user(user_id=1))
"#;
/// The position of the first `needle` in `file`.
fn at(text: &str, needle: &str) -> Pos {
let byte = text.find(needle).unwrap();
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
Pos::new(text[..byte].matches('\n').count() as u32, text[start..byte].encode_utf16().count() as u32)
}
async fn rename(host: &Host, doc: ide_core::DocId, pos: Pos, old: &str, new: &str, files: usize) -> WorkspaceEdit {
for _ in 0..120 {
let renamed = ops::lsp::lsp_rename(host, "main", RequestId(1), doc, pos, new.into()).await;
if let Ok(renamed) = renamed
&& renamed.edit.files.len() >= files
{
return ops::refactor::refactor_python_mention_edits(
host,
"main",
RequestId(2),
old.into(),
new.into(),
renamed.edit,
)
.await
.unwrap()
.edit;
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
panic!("basedpyright did not rename {old}");
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path).unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs basedpyright-langserver on PATH"]
async fn python_rename_searches_comments_and_strings() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(&root).unwrap();
let (lib, app, notes, closed) =
(root.join("lib.py"), root.join("app.py"), root.join("notes.md"), root.join("x.py"));
std::fs::write(&lib, LIB).unwrap();
std::fs::write(&app, APP).unwrap();
std::fs::write(&notes, "load_user\n").unwrap();
// A file that is not open and has no code reference, with a BOM and CRLF.
std::fs::write(&closed, "\u{feff}# load_user\r\nload_user = 1\r\n").unwrap();
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink = events.clone();
let host = Host::new(HostConfig {
sink_for: Box::new(move |_| {
let sink = sink.clone();
Arc::new(move |e| sink.lock().push(e))
}),
..common::host_config(&tmp.path().join("ide"))
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let doc = ops::doc::doc_open(&host, "main", lib.clone()).await.unwrap();
let app_doc = ops::doc::doc_open(&host, "main", app.clone()).await.unwrap();
// An unsaved comment line exists only in the buffer.
let end = APP.encode_utf16().count() as u32;
let changes = ide_core::ChangeSet {
changes: vec![ide_core::TextChange { from: end, to: end, insert: "# unsaved load_user\n".into() }],
};
ops::doc::doc_edit(&host, "main", app_doc.id, app_doc.version, changes).await.unwrap();
// A local (a parameter): only its own function's mentions change, not the same text in another one.
let edit = rename(&host, doc.id, at(LIB, "user_id):"), "user_id", "uid", 1).await;
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
let after = ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text;
assert!(after.contains("def load_user(uid):\n \"\"\"Run load_user(uid) for one uid."), "{after}");
assert!(after.contains(r#"f"load_user {uid} \"uid\" \nuid""#), "{after}");
assert!(after.contains("# user_id outside load_user\n return \"user_id\""), "{after}");
let undo = |events: &Mutex<Vec<IdeEvent>>| {
events.lock().iter().rev().find_map(|e| match e {
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
_ => None,
})
};
ops::lsp::undo_workspace_edit(&host, "main", undo(&events).unwrap()).await.unwrap();
assert_eq!(ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text, LIB);
// A module-level function: comments and strings in all of the project's Python files.
let edit = rename(&host, doc.id, at(LIB, "load_user(user_id):"), "load_user", "fetch_user", 2).await;
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
let lib_after = ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text;
assert!(lib_after.starts_with("__all__ = [\"fetch_user\"]"), "{lib_after}");
assert!(lib_after.contains(">>> fetch_user(1)"), "{lib_after}");
assert!(lib_after.contains("# fetch_user reads user_id; reload_user and load_users stay."), "{lib_after}");
// An unrelated method with the same name: its code is left alone.
assert!(lib_after.contains("def load_user(self):"), "{lib_after}");
let app_after = ops::doc::doc_snapshot(&host, "main", app_doc.id).await.unwrap().text;
assert_eq!(app_after, format!("{APP}# unsaved load_user\n").replace("load_user", "fetch_user"));
let closed_after = read(&closed);
assert!(closed_after.contains("# fetch_user\r\nload_user = 1"), "{closed_after:?}");
assert_eq!(read(&notes), "load_user\n");
ops::lsp::undo_workspace_edit(&host, "main", undo(&events).unwrap()).await.unwrap();
assert_eq!(ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text, LIB);
assert_eq!(read(&closed), "\u{feff}# load_user\r\nload_user = 1\r\n");
// Renaming a parameter from a keyword argument in another file: comments change in its function, not at the caller.
let (base, caller) = (root.join("base.py"), root.join("caller.py"));
std::fs::write(&base, "class Base:\n def run(self, speed):\n return speed # base speed\n").unwrap();
let call = "from base import Base\n\n# outside speed\nBase().run(speed=1)\n";
std::fs::write(&caller, call).unwrap();
let caller_doc = ops::doc::doc_open(&host, "main", caller.clone()).await.unwrap();
let edit = rename(&host, caller_doc.id, at(call, "speed=1"), "speed", "pace", 2).await;
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
assert!(read(&base).contains("return pace # base pace"), "{}", read(&base));
assert!(read(&caller).contains("# outside speed"));
ops::lsp::undo_workspace_edit(&host, "main", undo(&events).unwrap()).await.unwrap();
// A symlink in the project to a file outside it is not changed.
#[cfg(unix)]
{
let outside = tmp.path().join("outside.py");
std::fs::write(&outside, "# load_user\n").unwrap();
std::os::unix::fs::symlink(&outside, root.join("link.py")).unwrap();
let edit = rename(&host, doc.id, at(LIB, "load_user(user_id):"), "load_user", "get_user", 2).await;
let text = format!("{:?}", edit.files);
assert!(!text.contains("outside.py") && !text.contains("link.py"), "{text}");
}
// A file with only comment matches changed after the preview: applying must fail rather than write at stale positions.
let edit = rename(&host, doc.id, at(LIB, "load_user(user_id):"), "load_user", "get_user", 2).await;
std::fs::write(&closed, "keep = 'untouched line'\n# load_user\n").unwrap();
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap_err();
assert_eq!(read(&closed), "keep = 'untouched line'\n# load_user\n");
assert_eq!(read(&lib), LIB);
}