mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 16:04:21 +00:00
feat(python): update imports when a module or package is renamed or moved (#5171)
Renaming or moving a Python module or package left every import of it broken: basedpyright has no `workspace/willRenameFiles`, so no reference updates reached the move preview. `refactor_file_move_edits` now maps the moved paths to dotted module names from the project's Python roots (`src/` layout or the project root, `tests/`), and `Syntax::python_import_edits` rewrites the import statements of each project `.py`/`.pyi` file from its tree-sitter tree. It covers `import a.b` (with qualified uses `a.b.X`), `import a.b as c`, `from a.b import X`, `from a import b`, relative imports (kept relative, also in the moved files themselves) and package moves; when a rename changes the name an import binds, the import keeps it with an alias. The edits join the existing move preview and undo. A Python server that answers `willRenameFiles` still wins. The Python language smoke now checks file moves. Closes #5146 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
co-authored by
wildcatDownstairs
parent
a67b27c33a
commit
e75d438f70
@@ -3,10 +3,14 @@
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use ide_core::{IdeResult, RequestId, WorkspaceEdit};
|
||||
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
|
||||
use ide_language::Syntax;
|
||||
use ide_lsp::types::FileRenameEdits;
|
||||
use ide_workspace::file_moves::moved_path;
|
||||
use ide_workspace::roots::{ProjectRoots, RootKind};
|
||||
use ide_workspace::{FileMove, UndoOutcome};
|
||||
use std::path::PathBuf;
|
||||
use parking_lot::Mutex;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::doc::blocking;
|
||||
|
||||
@@ -24,16 +28,110 @@ pub async fn refactor_file_move_edits(
|
||||
) -> IdeResult<FileRenameEdits> {
|
||||
let project = host.project(window)?;
|
||||
let token = host.begin_request(request);
|
||||
let result = project.lsp.will_rename_files(&pairs(&moves), token).await;
|
||||
let result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await;
|
||||
host.end_request(request);
|
||||
let mut result = result?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
|
||||
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
|
||||
let python = python_import_edits(&project, &syntax, &moves, &|| token.is_cancelled());
|
||||
result.edit.files.extend(python.files);
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut result.edit)?;
|
||||
Ok(result)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn is_python(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e == "py" || e == "pyi")
|
||||
}
|
||||
|
||||
/// The dotted name of a Python module file or package folder, from its project's Python roots
|
||||
/// (`src/a/b.py` → `a.b` in a `src` layout).
|
||||
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<String> {
|
||||
let rel = path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/");
|
||||
let base = roots
|
||||
.root_for(&rel)
|
||||
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
|
||||
.map_or("", |r| r.path.as_str());
|
||||
let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') };
|
||||
let inner = if is_dir { inner } else { inner.strip_suffix(".py").or_else(|| inner.strip_suffix(".pyi"))? };
|
||||
let inner = inner.strip_suffix("/__init__").unwrap_or(inner);
|
||||
let valid = |s: &str| {
|
||||
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
|
||||
};
|
||||
(!inner.is_empty() && inner.split('/').all(valid)).then(|| inner.replace('/', "."))
|
||||
}
|
||||
|
||||
/// The package relative imports in `file` start from.
|
||||
fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
|
||||
let Some(module) = python_module(root, roots, file, false) else { return String::new() };
|
||||
if file.file_stem().is_some_and(|s| s == "__init__") {
|
||||
module
|
||||
} else {
|
||||
module.rsplit_once('.').map_or(String::new(), |(p, _)| p.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Import updates in the project's Python files for `moves` (paths before the move).
|
||||
fn python_import_edits(
|
||||
project: &crate::project::Project,
|
||||
syntax: &Syntax,
|
||||
moves: &[FileMove],
|
||||
cancelled: &(dyn Fn() -> bool + Sync),
|
||||
) -> WorkspaceEdit {
|
||||
let root = &project.root;
|
||||
let roots = project.roots();
|
||||
let renames: Vec<(String, String)> = moves
|
||||
.iter()
|
||||
.filter_map(|m| {
|
||||
let is_dir = m.from.is_dir();
|
||||
if !is_dir && (!is_python(&m.from) || m.from.file_stem().is_some_and(|s| s == "__init__")) {
|
||||
return None;
|
||||
}
|
||||
let old = python_module(root, &roots, &m.from, is_dir)?;
|
||||
let new = python_module(root, &roots, &m.to, is_dir)?;
|
||||
(old != new).then_some((old, new))
|
||||
})
|
||||
.collect();
|
||||
if renames.is_empty() {
|
||||
return WorkspaceEdit::default();
|
||||
}
|
||||
let names: Vec<&str> = renames.iter().map(|(old, _)| old.rsplit('.').next().unwrap_or(old)).collect();
|
||||
let found: Mutex<Vec<(PathBuf, Vec<ide_core::TextEdit>)>> = Mutex::new(Vec::new());
|
||||
ide_vfs::walk_files(root, &project.exclude_globs(), |path| {
|
||||
if cancelled() || !is_python(path) {
|
||||
return;
|
||||
}
|
||||
let moved = moved_path(path, moves);
|
||||
let text = match project.documents.text_of(path) {
|
||||
Some(t) => t,
|
||||
None => match std::fs::read_to_string(path) {
|
||||
Ok(t) => t,
|
||||
Err(_) => return,
|
||||
},
|
||||
};
|
||||
if moved == path && !names.iter().any(|n| text.contains(n)) {
|
||||
return;
|
||||
}
|
||||
let edits = syntax.python_import_edits(
|
||||
&text,
|
||||
&python_package(root, &roots, path),
|
||||
&python_package(root, &roots, &moved),
|
||||
&renames,
|
||||
);
|
||||
if !edits.is_empty() {
|
||||
found.lock().push((path.to_path_buf(), edits));
|
||||
}
|
||||
});
|
||||
let mut files = found.into_inner();
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let files = files.into_iter().map(|(path, edits)| FileEdit::Edit { path: path.into(), edits, version: None });
|
||||
WorkspaceEdit { files: files.collect(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Applies `edit` (from [`refactor_file_move_edits`], possibly empty), moves the
|
||||
/// files and notifies the servers. Returns the id for [`refactor_undo_file_move`].
|
||||
#[command(trust = always)]
|
||||
@@ -111,3 +209,29 @@ ide_command::domain!(
|
||||
refactor_move_files,
|
||||
refactor_undo_file_move,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_workspace::roots::SourceFolder;
|
||||
|
||||
#[test]
|
||||
fn python_module_names_follow_the_roots() {
|
||||
let root = Path::new("/p");
|
||||
let folder = |path: &str, kind| SourceFolder { path: path.into(), kind, detected_from: None };
|
||||
let roots = ProjectRoots::compute(
|
||||
vec![folder("src", RootKind::Source), folder("tests", RootKind::Test)],
|
||||
&Default::default(),
|
||||
);
|
||||
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir);
|
||||
assert_eq!(name("src/tasks/models.py", false).as_deref(), Some("tasks.models"));
|
||||
assert_eq!(name("src/tasks/__init__.py", false).as_deref(), Some("tasks"));
|
||||
assert_eq!(name("src/tasks", true).as_deref(), Some("tasks"));
|
||||
assert_eq!(name("tests/test_models.py", false).as_deref(), Some("test_models"));
|
||||
assert_eq!(name("scripts/run.pyi", false).as_deref(), Some("scripts.run"));
|
||||
assert_eq!(name("my-scripts/run.py", false), None);
|
||||
assert_eq!(name("src/tasks/notes.txt", false), None);
|
||||
assert_eq!(python_package(root, &roots, &root.join("src/tasks/cli.py")), "tasks");
|
||||
assert_eq!(python_package(root, &roots, &root.join("src/tasks/__init__.py")), "tasks");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -742,8 +742,8 @@ const PYTHON: Checks = Checks {
|
||||
typed("src/tasks/models.py", "from enum import IntEnum", "import abc"),
|
||||
Imports::Before("import os"),
|
||||
)),
|
||||
// basedpyright has no `workspace/willRenameFiles`.
|
||||
file_move: None,
|
||||
// basedpyright has no `workspace/willRenameFiles`: the IDE rewrites the imports.
|
||||
file_move: Some(("src/tasks/models.py", "src/tasks/domain.py", "src/tasks/cli.py", "from .domain import")),
|
||||
};
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
|
||||
@@ -12,6 +12,7 @@ mod literals;
|
||||
mod outline;
|
||||
mod php_align;
|
||||
mod python_facts;
|
||||
mod python_imports;
|
||||
mod rst;
|
||||
mod selection;
|
||||
mod sfc;
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! Import updates for moved Python modules and packages, which basedpyright leaves to the
|
||||
//! client (no `workspace/willRenameFiles`). Works on dotted module names; the caller maps
|
||||
//! files to them from the project's roots.
|
||||
|
||||
use super::lines::LineIndex;
|
||||
use crate::{LanguageId, Syntax};
|
||||
use ide_core::TextEdit;
|
||||
use tree_sitter::{Node, Tree};
|
||||
|
||||
impl Syntax {
|
||||
/// Edits that keep the imports of a Python `text` resolving after `moves` (old → new
|
||||
/// dotted names; a package covers its submodules). `package` is the package relative
|
||||
/// imports start from (`a.b` for `a/b/c.py` and `a/b/__init__.py`), `new_package` the
|
||||
/// same after the move.
|
||||
pub fn python_import_edits(
|
||||
&self,
|
||||
text: &str,
|
||||
package: &str,
|
||||
new_package: &str,
|
||||
moves: &[(String, String)],
|
||||
) -> Vec<TextEdit> {
|
||||
self.analyze(&LanguageId::new("python"), text, |_, tree, text| {
|
||||
Some(Rewrite { text, idx: LineIndex::new(text), package, new_package, moves, edits: Vec::new() }.run(tree))
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
struct Rewrite<'a> {
|
||||
text: &'a str,
|
||||
idx: LineIndex<'a>,
|
||||
package: &'a str,
|
||||
new_package: &'a str,
|
||||
moves: &'a [(String, String)],
|
||||
edits: Vec<TextEdit>,
|
||||
}
|
||||
|
||||
impl Rewrite<'_> {
|
||||
fn run(mut self, tree: &Tree) -> Vec<TextEdit> {
|
||||
let mut imports = Vec::new();
|
||||
let mut chains = Vec::new();
|
||||
collect(tree.root_node(), &mut |n| match n.kind() {
|
||||
"import_statement" | "import_from_statement" => imports.push(n),
|
||||
"attribute" if !inside_import(n) => chains.push(n),
|
||||
_ => {}
|
||||
});
|
||||
let mut renamed: Vec<(String, String)> = Vec::new();
|
||||
for node in imports {
|
||||
if node.kind() == "import_statement" {
|
||||
self.import(node, &mut renamed);
|
||||
} else {
|
||||
self.import_from(node);
|
||||
}
|
||||
}
|
||||
// `import a.b` is used as `a.b.x`: those chains follow the import.
|
||||
for node in chains {
|
||||
let t = self.src(node);
|
||||
if let Some((_, new)) = renamed.iter().find(|(old, _)| *old == t) {
|
||||
self.edit(node, new.clone());
|
||||
}
|
||||
}
|
||||
self.edits.sort_by_key(|e| (e.range.start.line, e.range.start.col));
|
||||
self.edits
|
||||
}
|
||||
|
||||
fn src(&self, n: Node) -> &str {
|
||||
self.text.get(n.byte_range()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn edit(&mut self, n: Node, new_text: String) {
|
||||
self.edits.push(TextEdit { range: self.idx.range(n.start_byte(), n.end_byte()), new_text });
|
||||
}
|
||||
|
||||
/// `import a.b`, `import a.b as c`.
|
||||
fn import(&mut self, node: Node, renamed: &mut Vec<(String, String)>) {
|
||||
let mut cursor = node.walk();
|
||||
for item in node.children_by_field_name("name", &mut cursor) {
|
||||
let (name, aliased) = match item.kind() {
|
||||
"aliased_import" => match item.child_by_field_name("name") {
|
||||
Some(n) => (n, true),
|
||||
None => continue,
|
||||
},
|
||||
_ => (item, false),
|
||||
};
|
||||
let old = self.src(name).to_owned();
|
||||
let Some(new) = map_module(&old, self.moves) else { continue };
|
||||
if aliased {
|
||||
self.edit(name, new);
|
||||
} else if old.contains('.') {
|
||||
renamed.push((old, new.clone()));
|
||||
self.edit(name, new);
|
||||
} else {
|
||||
// The bound name stays, so the rest of the file needs no change.
|
||||
self.edit(name, format!("{new} as {old}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `from m import x`, `from .m import x as y`, `from . import m`.
|
||||
fn import_from(&mut self, node: Node) {
|
||||
let Some(module) = node.child_by_field_name("module_name") else { return };
|
||||
let relative = (module.kind() == "relative_import").then(|| {
|
||||
let mut cursor = module.walk();
|
||||
let dots = module
|
||||
.children(&mut cursor)
|
||||
.find(|c| c.kind() == "import_prefix")
|
||||
.map_or(0, |p| self.src(p).matches('.').count());
|
||||
let rest = module.child(1).filter(|c| c.kind() == "dotted_name").map_or("", |c| self.src(c));
|
||||
(dots, rest.to_owned())
|
||||
});
|
||||
let source = match &relative {
|
||||
Some((dots, rest)) => match resolve(*dots, rest, self.package) {
|
||||
Some(s) => s,
|
||||
None => return,
|
||||
},
|
||||
None => self.src(module).to_owned(),
|
||||
};
|
||||
let target = map_module(&source, self.moves).unwrap_or_else(|| source.clone());
|
||||
|
||||
// Imported submodules that moved on their own (`from pkg import models`).
|
||||
let mut cursor = node.walk();
|
||||
let names: Vec<Node> = node.children_by_field_name("name", &mut cursor).collect();
|
||||
let mut moved: Vec<(Node, String, String, String)> = Vec::new(); // (item, parent, name, bound)
|
||||
for &item in &names {
|
||||
let (name, alias) = match item.kind() {
|
||||
"aliased_import" => (item.child_by_field_name("name"), item.child_by_field_name("alias")),
|
||||
_ => (Some(item), None),
|
||||
};
|
||||
let Some(name) = name else { continue };
|
||||
let n = self.src(name).to_owned();
|
||||
let full = join(&source, &n);
|
||||
let Some(new) = map_module(&full, self.moves) else { continue };
|
||||
if new == join(&target, &n) {
|
||||
continue;
|
||||
}
|
||||
let (parent, last) =
|
||||
new.rsplit_once('.').map_or((String::new(), new.clone()), |(p, l)| (p.into(), l.into()));
|
||||
let bound = alias.map_or(n, |a| self.src(a).to_owned());
|
||||
moved.push((item, parent, last, bound));
|
||||
}
|
||||
let as_name =
|
||||
|last: &str, bound: &str| if last == bound { last.to_owned() } else { format!("{last} as {bound}") };
|
||||
// Renamed inside the same package: only the name changes.
|
||||
let in_place: Vec<(Node, String)> =
|
||||
moved.iter().filter(|m| m.1 == target).map(|m| (m.0, as_name(&m.2, &m.3))).collect();
|
||||
moved.retain(|m| m.1 != target);
|
||||
let render = |module: &str, rw: &Self| match &relative {
|
||||
Some((dots, rest)) if resolve(*dots, rest, rw.new_package).as_deref() == Some(module) => None,
|
||||
Some(_) => Some(relative_to(module, rw.new_package).unwrap_or_else(|| module.to_owned())),
|
||||
None => Some(module.to_owned()),
|
||||
};
|
||||
|
||||
let all_one_parent = !moved.is_empty()
|
||||
&& moved.len() == names.len()
|
||||
&& moved.iter().all(|m| m.1 == moved[0].1 && !m.1.is_empty());
|
||||
if all_one_parent {
|
||||
let parent = moved[0].1.clone();
|
||||
if let Some(m) = render(&parent, self).filter(|m| m != self.src(module)) {
|
||||
self.edit(module, m);
|
||||
}
|
||||
for (item, _, last, bound) in moved {
|
||||
let new = as_name(&last, &bound);
|
||||
if new != self.src(item) {
|
||||
self.edit(item, new);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if moved.is_empty() {
|
||||
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
|
||||
self.edit(module, m);
|
||||
}
|
||||
for (item, text) in in_place {
|
||||
self.edit(item, text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// ponytail: a split statement loses a multi-line names list's layout; fine for the rare
|
||||
// "some names of one `from` moved elsewhere" case.
|
||||
let indent = line_indent(self.text, node.start_byte());
|
||||
let mut parents: Vec<&str> = Vec::new();
|
||||
for m in &moved {
|
||||
if !parents.contains(&m.1.as_str()) {
|
||||
parents.push(&m.1);
|
||||
}
|
||||
}
|
||||
let mut added: Vec<String> = Vec::new();
|
||||
for parent in parents {
|
||||
let items: Vec<String> = moved.iter().filter(|m| m.1 == parent).map(|m| as_name(&m.2, &m.3)).collect();
|
||||
added.push(if parent.is_empty() {
|
||||
format!("import {}", items.join(", "))
|
||||
} else {
|
||||
let from = render(parent, self).unwrap_or_else(|| self.src(module).to_owned());
|
||||
format!("from {from} import {}", items.join(", "))
|
||||
});
|
||||
}
|
||||
let kept: Vec<String> = names
|
||||
.iter()
|
||||
.filter(|n| !moved.iter().any(|m| m.0 == **n))
|
||||
.map(|n| in_place.iter().find(|(i, _)| i == n).map_or_else(|| self.src(*n).to_owned(), |(_, t)| t.clone()))
|
||||
.collect();
|
||||
let sep = format!("\n{indent}");
|
||||
if kept.is_empty() {
|
||||
self.edit(node, added.join(&sep));
|
||||
return;
|
||||
}
|
||||
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
|
||||
self.edit(module, m);
|
||||
}
|
||||
let (first, last) = (names[0], names[names.len() - 1]);
|
||||
let range = self.idx.range(first.start_byte(), last.end_byte());
|
||||
self.edits.push(TextEdit { range, new_text: kept.join(", ") });
|
||||
let end = self.idx.pos(node.end_byte());
|
||||
self.edits.push(TextEdit {
|
||||
range: ide_core::Range { start: end, end },
|
||||
new_text: format!("{sep}{}", added.join(&sep)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn collect<'t>(node: Node<'t>, f: &mut impl FnMut(Node<'t>)) {
|
||||
f(node);
|
||||
let mut cursor = node.walk();
|
||||
for child in node.children(&mut cursor) {
|
||||
collect(child, f);
|
||||
}
|
||||
}
|
||||
|
||||
fn inside_import(mut n: Node) -> bool {
|
||||
while let Some(p) = n.parent() {
|
||||
if matches!(p.kind(), "import_statement" | "import_from_statement" | "future_import_statement") {
|
||||
return true;
|
||||
}
|
||||
n = p;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn line_indent(text: &str, byte: usize) -> &str {
|
||||
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
|
||||
&text[start..byte]
|
||||
}
|
||||
|
||||
fn join(a: &str, b: &str) -> String {
|
||||
match (a.is_empty(), b.is_empty()) {
|
||||
(true, _) => b.to_owned(),
|
||||
(_, true) => a.to_owned(),
|
||||
_ => format!("{a}.{b}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` after `moves` (the longest moved prefix wins), if it changed.
|
||||
fn map_module(name: &str, moves: &[(String, String)]) -> Option<String> {
|
||||
moves
|
||||
.iter()
|
||||
.filter(|(from, _)| name == from || name.strip_prefix(from.as_str()).is_some_and(|r| r.starts_with('.')))
|
||||
.max_by_key(|(from, _)| from.len())
|
||||
.map(|(from, to)| format!("{to}{}", &name[from.len()..]))
|
||||
.filter(|new| new != name)
|
||||
}
|
||||
|
||||
/// The absolute module `from <dots><rest> import` names inside `package`.
|
||||
fn resolve(dots: usize, rest: &str, package: &str) -> Option<String> {
|
||||
let segs: Vec<&str> = package.split('.').filter(|s| !s.is_empty()).collect();
|
||||
let keep = segs.len().checked_sub(dots.checked_sub(1)?)?;
|
||||
if keep == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(join(&segs[..keep].join("."), rest))
|
||||
}
|
||||
|
||||
/// The shortest relative form of `module` from `package`, if they share a top-level package.
|
||||
fn relative_to(module: &str, package: &str) -> Option<String> {
|
||||
let segs: Vec<&str> = package.split('.').filter(|s| !s.is_empty()).collect();
|
||||
(1..=segs.len()).find_map(|dots| {
|
||||
let base = segs[..segs.len() + 1 - dots].join(".");
|
||||
let rest = if module == base { "" } else { module.strip_prefix(&base)?.strip_prefix('.')? };
|
||||
Some(format!("{}{rest}", ".".repeat(dots)))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::syntax::lines::byte_at;
|
||||
|
||||
fn apply(text: &str, package: &str, new_package: &str, moves: &[(&str, &str)]) -> String {
|
||||
let moves: Vec<(String, String)> = moves.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
|
||||
let mut edits = Syntax::new().python_import_edits(text, package, new_package, &moves);
|
||||
edits.sort_by_key(|e| std::cmp::Reverse((e.range.start.line, e.range.start.col)));
|
||||
let mut out = text.to_owned();
|
||||
for e in edits {
|
||||
let (s, t) = (byte_at(&out, e.range.start).unwrap(), byte_at(&out, e.range.end).unwrap());
|
||||
out.replace_range(s..t, &e.new_text);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
const RENAME: &[(&str, &str)] = &[("pkg.models", "pkg.domain")];
|
||||
|
||||
#[test]
|
||||
fn absolute_imports() {
|
||||
let src = "import pkg.models\nimport pkg.models as m\nfrom pkg.models import Task, Priority\nimport pkg.modelsx\n\nx = pkg.models.Task()\ny = m.Task\n";
|
||||
assert_eq!(
|
||||
apply(src, "app", "app", RENAME),
|
||||
"import pkg.domain\nimport pkg.domain as m\nfrom pkg.domain import Task, Priority\nimport pkg.modelsx\n\nx = pkg.domain.Task()\ny = m.Task\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bound_names_keep_their_alias() {
|
||||
let src = "from pkg import models\nfrom pkg import models as mo, cli\nimport models\n";
|
||||
let moves = &[("pkg.models", "pkg.domain"), ("models", "domain")];
|
||||
assert_eq!(
|
||||
apply(src, "app", "app", moves),
|
||||
"from pkg import domain as models\nfrom pkg import domain as mo, cli\nimport domain as models\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_imports() {
|
||||
let src = "from .models import Task\nfrom . import models\nfrom . import cli\n";
|
||||
assert_eq!(
|
||||
apply(src, "pkg", "pkg", RENAME),
|
||||
"from .domain import Task\nfrom . import domain as models\nfrom . import cli\n"
|
||||
);
|
||||
let src = "from ..models import Task\nfrom .. import models, cli\n";
|
||||
assert_eq!(
|
||||
apply(src, "pkg.sub", "pkg.sub", RENAME),
|
||||
"from ..domain import Task\nfrom .. import domain as models, cli\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_moved_to_another_package() {
|
||||
let moves = &[("pkg.models", "core.models")];
|
||||
assert_eq!(apply("from .models import Task\n", "pkg", "pkg", moves), "from core.models import Task\n");
|
||||
assert_eq!(apply("from pkg import models\n", "app", "app", moves), "from core import models\n");
|
||||
assert_eq!(
|
||||
apply("def f():\n from pkg import cli, models\n", "app", "app", moves),
|
||||
"def f():\n from pkg import cli\n from core import models\n"
|
||||
);
|
||||
let moves = &[("pkg.models", "core.models"), ("pkg.cli", "pkg.main"), ("pkg.util", "util")];
|
||||
assert_eq!(
|
||||
apply("from pkg import cli, models, util, other\n", "app", "app", moves),
|
||||
"from pkg import main as cli, other\nfrom core import models\nimport util\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply("from . import models\n", "pkg.sub", "pkg.sub", &[("pkg.sub.models", "pkg.models")]),
|
||||
"from .. import models\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_moved_file_keeps_its_relative_imports_resolving() {
|
||||
// pkg/cli.py → other/cli.py: `.models` (pkg.models) did not move.
|
||||
let moves = &[("pkg.cli", "other.cli")];
|
||||
assert_eq!(apply("from .models import Task\n", "pkg", "other", moves), "from pkg.models import Task\n");
|
||||
// pkg/sub/cli.py → pkg/cli.py
|
||||
let moves = &[("pkg.sub.cli", "pkg.cli")];
|
||||
assert_eq!(apply("from ..models import Task\n", "pkg.sub", "pkg", moves), "from .models import Task\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_moves() {
|
||||
let moves = &[("pkg", "lib.pkg")];
|
||||
let src =
|
||||
"import pkg\nimport pkg.models\nfrom pkg.models import Task\nfrom pkg import models\n\npkg.models.Task()\n";
|
||||
assert_eq!(
|
||||
apply(src, "", "", moves),
|
||||
"import lib.pkg as pkg\nimport lib.pkg.models\nfrom lib.pkg.models import Task\nfrom lib.pkg import models\n\nlib.pkg.models.Task()\n"
|
||||
);
|
||||
// Inside the moved package, relative imports still resolve.
|
||||
assert_eq!(
|
||||
apply("from .models import Task\nfrom . import cli\n", "pkg", "lib.pkg", moves),
|
||||
"from .models import Task\nfrom . import cli\n"
|
||||
);
|
||||
// Absolute self-imports follow it.
|
||||
assert_eq!(
|
||||
apply("from pkg.models import Task\n", "pkg", "lib.pkg", moves),
|
||||
"from lib.pkg.models import Task\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_imports_are_untouched() {
|
||||
let src = "from __future__ import annotations\nimport os\nfrom datetime import date\nfrom pkgx import models\nfrom . import *\n";
|
||||
assert_eq!(apply(src, "pkg", "pkg", RENAME), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helpers() {
|
||||
assert_eq!(resolve(1, "m", "a.b").as_deref(), Some("a.b.m"));
|
||||
assert_eq!(resolve(2, "", "a.b").as_deref(), Some("a"));
|
||||
assert_eq!(resolve(3, "m", "a.b"), None);
|
||||
assert_eq!(relative_to("a.b.m", "a.b").as_deref(), Some(".m"));
|
||||
assert_eq!(relative_to("a.c", "a.b").as_deref(), Some("..c"));
|
||||
assert_eq!(relative_to("x.c", "a.b"), None);
|
||||
assert_eq!(map_module("pkg.models.sub", RENAME_OWNED.as_slice()).as_deref(), Some("pkg.domain.sub"));
|
||||
}
|
||||
|
||||
static RENAME_OWNED: std::sync::LazyLock<Vec<(String, String)>> =
|
||||
std::sync::LazyLock::new(|| vec![("pkg.models".into(), "pkg.domain".into())]);
|
||||
}
|
||||
@@ -62,7 +62,7 @@ When the language server cannot help, Introduce Variable and Introduce Constant
|
||||
|
||||
## Move, copy and rename files
|
||||
|
||||
In the Project view, **Rename…** (`⇧F6` / `Shift+F6`), **Move…** (`F6`, drag and drop, or cut and paste) and **Copy…** (`F5`, copy and paste, or `⌥`-drag / `Alt`-drag) open a dialog. With **Search for references** on, references to the file are updated through the language servers that support it (for example imports in TypeScript); **Search in comments and strings** also looks there. The changes are shown in a preview first.
|
||||
In the Project view, **Rename…** (`⇧F6` / `Shift+F6`), **Move…** (`F6`, drag and drop, or cut and paste) and **Copy…** (`F5`, copy and paste, or `⌥`-drag / `Alt`-drag) open a dialog. With **Search for references** on, references to the file are updated through the language servers that support it (for example imports in TypeScript); Python imports are updated by the IDE itself; **Search in comments and strings** also looks there. The changes are shown in a preview first.
|
||||
|
||||
In the editor, **Move…** on a symbol runs the server's move refactoring, where the language has one. In Java it asks where to: a top-level class goes to another package (its package declaration, imports and every reference follow), a static member or nested class to another class, an instance method to the class of one of its fields or parameters; warnings are confirmed in **Problems Detected** first.
|
||||
|
||||
|
||||
@@ -21,6 +21,8 @@ basedpyright starts in its `standard` type-checking mode instead of its own stri
|
||||
|
||||
Ruff starts only for files below a Ruff configuration: a `ruff.toml`, a `.ruff.toml`, or a `pyproject.toml` that contains a `[tool.ruff]` table. basedpyright has no formatter, so formatting comes from Ruff.
|
||||
|
||||
Moving or renaming a module or package in the Project view with **Search for references** on updates the `import` and `from … import` statements that refer to it, relative imports included, in the same preview as the move. basedpyright has no file-move support, so the IDE finds these imports itself from the syntax tree. When a rename changes the name an import binds, the import keeps it as an alias: `from pkg import models` becomes `from pkg import domain as models`.
|
||||
|
||||
To pick the type checker yourself, open **Settings › Languages & Frameworks › Language Servers**, select any of the four servers and change **Language server for Python**. **Automatic** uses the first installed one in the order above; you can also choose one server or **None**.
|
||||
|
||||
## Setup
|
||||
|
||||
@@ -57,7 +57,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
|
||||
|
||||
## 移动、复制和重命名文件
|
||||
|
||||
在项目视图中,**重命名…**(`⇧F6` / `Shift+F6`)、**移动…**(`F6`、拖放或剪切后粘贴)和 **复制…**(`F5`、复制后粘贴,或按住 `⌥` / `Alt` 拖动)会打开对话框。勾选 **搜索引用** 后,支持此功能的语言服务器会更新对该文件的引用(例如 TypeScript 的 import);**在注释和字符串中搜索** 会把注释和字符串也算进去。改动会先显示预览。
|
||||
在项目视图中,**重命名…**(`⇧F6` / `Shift+F6`)、**移动…**(`F6`、拖放或剪切后粘贴)和 **复制…**(`F5`、复制后粘贴,或按住 `⌥` / `Alt` 拖动)会打开对话框。勾选 **搜索引用** 后,支持此功能的语言服务器会更新对该文件的引用(例如 TypeScript 的 import),Python 的 import 由 IDE 自己更新;**在注释和字符串中搜索** 会把注释和字符串也算进去。改动会先显示预览。
|
||||
|
||||
在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。在 Java 中会先询问目标:顶层类移动到其他包(包声明、import 和所有引用随之更新),静态成员或嵌套类移动到其他类,实例方法移动到其某个字段或形参的类;有警告时先在 **检测到问题** 中确认。
|
||||
|
||||
|
||||
@@ -21,6 +21,8 @@ basedpyright 以 `standard` 类型检查模式启动,而不是它自带的更
|
||||
|
||||
Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`,或包含 `[tool.ruff]` 表的 `pyproject.toml`。basedpyright 本身不提供格式化,格式化由 Ruff 负责。
|
||||
|
||||
移动或重命名模块、包时(项目视图中,勾选 **搜索引用**),引用它的 `import` 和 `from … import` 语句(包括相对导入)会一起更新,和移动操作显示在同一个预览里。basedpyright 不支持文件移动,所以这些导入由 IDE 根据语法树自己查找。如果重命名改变了导入绑定的名字,导入会用别名保留原名:`from pkg import models` 变成 `from pkg import domain as models`。
|
||||
|
||||
想手动指定类型检查器,打开 **设置 › 语言和框架 › 语言服务器**,选中这四个服务器中的任意一个,修改 **Python 语言服务器**。**自动** 会按上表顺序使用第一个已安装的服务器;也可以固定选一个,或选 **无**。
|
||||
|
||||
## 环境配置
|
||||
|
||||
Reference in New Issue
Block a user