//! Move top-level Python functions, classes and variables to another module. The IDE reads the //! files and updates `from … import` with its module-move rewriter; `python_move.py` moves the code //! and rewrites `module.name` uses. Nothing is written here: the answer is a workspace edit. use crate::Host; use crate::ops::refactor::{is_python, python_module, python_package}; use crate::python_signature::{Context, run, to_edit}; use ide_core::error::ErrorKind; use ide_core::{CancellationToken, DocId, FileEdit, IdeError, IdeResult, IpcPath, Pos, Range, TextEdit, WorkspaceEdit}; use ide_lsp::types::{ProblemSeverity, RefactoringProblem, ServerRefactored}; use ide_workspace::file_moves::read_text; use parking_lot::Mutex; use serde::Deserialize; use serde_json::{Value, json}; use std::collections::BTreeMap; use std::hash::{Hash, Hasher}; use std::path::{Component, Path, PathBuf}; use std::sync::Arc; const HELPER: &str = include_str!("python_move.py"); /// What the dialog sends back to accept the warnings of the first answer. const CONFIRMATION: &str = "python-move"; #[derive(Deserialize)] struct Arguments { names: Vec, /// The destination module file, absolute or relative to the project. file: String, } #[derive(Deserialize)] struct Moved { files: BTreeMap, warnings: Vec, } fn open(host: &Host, window: &str, doc: DocId) -> IdeResult<(Arc, PathBuf, String)> { let project = host.project(window)?; project.require_trust()?; let snap = project.documents.snapshot(doc)?; if !snap.path.0.is_absolute() || !snap.path.0.starts_with(&*project.root) { return Err(IdeError::invalid("Move needs a Python file of this project")); } Ok((project.clone(), snap.path.0.clone(), snap.text)) } fn context(project: &crate::Project, file: PathBuf, line: u32) -> Context { Context { root: project.root.to_path_buf(), file, pos: Pos::new(line, 0), overlay: BTreeMap::new() } } /// The movable names of the module (`{name, kind, selected}`); `args` carries the caret `line`. pub async fn symbols( host: &Host, window: &str, doc: DocId, args: Value, cancel: CancellationToken, ) -> IdeResult> { let (project, file, text) = open(host, window, doc)?; let line = args["line"].as_u64().unwrap_or(0) as u32; let request = json!({ "op": "symbols", "text": text }); match run(host, HELPER, request, &context(&project, file, line), &cancel).await? { Value::Array(found) => Ok(found), _ => Err(IdeError::new(ErrorKind::Protocol, "unexpected answer")), } } /// The destination as an absolute path inside the project. fn destination(root: &Path, file: &str) -> IdeResult { let path = root.join(file.trim()); let inside = path.starts_with(root) && !path.components().any(|c| matches!(c, Component::ParentDir)); if !inside || path.extension().is_none_or(|e| e != "py") { return Err(IdeError::invalid("The destination must be a .py file inside the project")); } // a linked folder may lead outside the project let real = path.ancestors().find_map(|p| dunce::canonicalize(p).ok()); if !real.zip(dunce::canonicalize(root).ok()).is_some_and(|(real, root)| real.starts_with(root)) { return Err(IdeError::invalid("The destination must be a .py file inside the project")); } // `utils.py` next to the package `utils/` (or inside a folder shadowed by `pkg.py`) is never imported let package = |p: &Path| p.join("__init__.py").is_file(); let shadowed = path.ancestors().skip(1).take_while(|p| *p != root).any(|p| p.with_extension("py").is_file() && !package(p)); if package(&path.with_extension("")) || shadowed { return Err(IdeError::invalid("A package and a module of the same name exist there")); } Ok(path) } struct Request { json: Value, /// The text each file had when the request was built. before: BTreeMap, create: Option, } fn request( project: &crate::Project, syntax: &ide_language::Syntax, source: &Path, text: String, args: Arguments, cancel: &CancellationToken, ) -> IdeResult { let root: &Path = &project.root; let roots = project.roots(); let dest = destination(root, &args.file)?; if dest == source { return Err(IdeError::invalid("The destination is the file itself")); } let show = |p: &Path| p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/"); let module = |p: &Path| { python_module(root, &roots, p, false) .map(|(m, _)| m) .ok_or_else(|| IdeError::invalid(format!("{} can't be imported as a Python module", show(p)))) }; let (old, new) = (module(source)?, module(&dest)?); if old == new { return Err(IdeError::invalid("The destination has the same module name")); } let existing = if dest.exists() { Some(read_text(&project.documents, &dest)?) } else { None }; let mut before = BTreeMap::from([(source.to_path_buf(), text.clone())]); if let Some(existing) = &existing { before.insert(dest.clone(), existing.clone()); } let moves: Vec<(String, String)> = args.names.iter().map(|n| (format!("{old}.{n}"), format!("{new}.{n}"))).collect(); let last = old.rsplit('.').next().unwrap_or(&old); let init = source.file_stem().is_some_and(|s| s == "__init__"); // (path, the file as it is, the file with its `from … import` updated) let found: Mutex> = Mutex::new(Vec::new()); ide_vfs::walk_files(root, &project.exclude_globs(), |path| { if cancel.is_cancelled() || !is_python(path) || path == source || path == dest { return; } // An unsaved buffer may mention the module although the file on disk doesn't. let open = project.documents.text_of(path); // Names a package defines are also reached as `from . import name`. let mentions = |text: &str| text.contains(last) || (init && args.names.iter().any(|n| text.contains(n))); // UTF-16 can't be searched as bytes. let may = |b: Vec| { b.starts_with(&[0xff, 0xfe]) || b.starts_with(&[0xfe, 0xff]) || mentions(&String::from_utf8_lossy(&b)) }; if open.is_none() && !std::fs::read(path).is_ok_and(may) { return; } let Ok(text) = open.map_or_else(|| read_text(&project.documents, path), Ok) else { return }; if !mentions(&text) { return; } let package = python_package(root, &roots, path); let mut updated = ide_text::Document::new(&text); if updated.apply_edits(&syntax.python_import_edits(&text, &package, &package, &moves)).is_ok() { found.lock().push((path.to_path_buf(), text, updated.text())); } }); let mut others = serde_json::Map::new(); for (path, text, updated) in found.into_inner() { let entry = json!({ "text": updated, "package": python_package(root, &roots, &path), "show": show(&path) }); others.insert(path.to_string_lossy().into_owned(), entry); before.insert(path, text); } let side = |path: &Path, module: &str, text: Option<&String>| { json!({ "path": path, "show": show(path), "module": module, "text": text, "package": python_package(root, &roots, path), }) }; let json = json!({ "op": "move", "names": args.names, "source": side(source, &old, Some(&text)), "dest": side(&dest, &new, existing.as_ref()), "others": others, }); Ok(Request { json, before, create: existing.is_none().then_some(dest) }) } /// Checks the move and computes its edit. Warnings (strings naming the module, import cycles…) /// come back first, with a token that accepts them. pub async fn move_symbols( host: &Host, window: &str, doc: DocId, args: Value, confirmation: Option, cancel: CancellationToken, ) -> IdeResult { let (project, source, text) = open(host, window, doc)?; let args: Arguments = serde_json::from_value(args).map_err(|e| IdeError::invalid(format!("invalid refactoring arguments: {e}")))?; let syntax = host.syntax(); let built = { let (project, source, cancel) = (project.clone(), source.clone(), cancel.clone()); crate::ops::blocking(move || request(&project, &syntax, &source, text, args, &cancel)).await? }; if cancel.is_cancelled() { return Err(IdeError::cancelled()); } let result = run(host, HELPER, built.json, &context(&project, source, 0), &cancel).await?; let mut moved: Moved = serde_json::from_value(result).map_err(|e| IdeError::new(ErrorKind::Protocol, e.to_string()))?; let problems: Vec = moved .warnings .into_iter() .map(|message| RefactoringProblem { severity: ProblemSeverity::Warning, message }) .collect(); // The token names the warnings shown: others that appear meanwhile are asked about again. let mut hasher = std::hash::DefaultHasher::new(); problems.iter().for_each(|p| p.message.hash(&mut hasher)); let token = format!("{CONFIRMATION}:{:x}", hasher.finish()); if !problems.is_empty() && confirmation.as_deref() != Some(&token) { return Ok(ServerRefactored { problems, edit: None, confirmation: Some(token) }); } let mut edit = WorkspaceEdit::default(); if let Some(dest) = built.create { let text = moved.files.remove(&dest).unwrap_or_default(); if dest.exists() { return Err(IdeError::invalid("The destination was created meanwhile; run it again")); } let start = Range::new(Pos::new(0, 0), Pos::new(0, 0)); edit.files.push(FileEdit::Create { path: IpcPath(dest.clone()), overwrite: false }); edit.files.push(FileEdit::Edit { path: IpcPath(dest), edits: vec![TextEdit { range: start, new_text: text }], version: None, }); } edit.files.extend(to_edit(&project, moved.files, &built.before)?.files); Ok(ServerRefactored { problems: Vec::new(), edit: Some(edit), confirmation: None }) }