diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index daf74282c7..34a1b44add 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -25,6 +25,7 @@ mod phpstan; pub mod plugins; mod project; mod proxy; +mod python_move; mod python_signature; pub mod relay; mod requests; diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index a89dc703ed..227e5130cc 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -1660,9 +1660,15 @@ pub async fn lsp_java_move_destinations( ) -> IdeResult> { // Where a Java Move code action of `kind` can go; `args` (JSON) carries the code action's own // arguments back unchanged, and each destination comes back as JSON. + // For Python (`python_move`), the movable names of the module. let args = json_argument(&args)?; let project = host.project(window)?; let cancel = host.begin_request(request); + if project.documents.snapshot(doc)?.language.as_str() == "python" { + let found = crate::python_move::symbols(host, window, doc, args, cancel).await; + host.end_request(request); + return found.map(json_strings); + } let result = project.lsp.java_move_destinations(doc, kind, args, cancel).await; host.end_request(request); result.map(json_strings) @@ -1699,7 +1705,11 @@ pub async fn lsp_java_move( let args = json_argument(&args)?; let project = host.project(window)?; let cancel = host.begin_request(request); - let result = project.lsp.java_move(doc, kind, args, confirmation, cancel).await; + let result = if project.documents.snapshot(doc)?.language.as_str() == "python" { + crate::python_move::move_symbols(host, window, doc, args, confirmation, cancel).await + } else { + project.lsp.java_move(doc, kind, args, confirmation, cancel).await + }; host.end_request(request); let mut moved = result?; blocking(move || { diff --git a/crates/ide-host/src/ops/refactor.rs b/crates/ide-host/src/ops/refactor.rs index cc1a024a0c..2861b7eecc 100644 --- a/crates/ide-host/src/ops/refactor.rs +++ b/crates/ide-host/src/ops/refactor.rs @@ -70,7 +70,7 @@ pub async fn refactor_file_move_edits( result } -fn is_python(path: &Path) -> bool { +pub(crate) fn is_python(path: &Path) -> bool { path.extension().is_some_and(|e| e == "py" || e == "pyi") } @@ -91,7 +91,7 @@ fn rel_path(root: &Path, path: &Path) -> Option { /// The dotted name of a Python module file or package folder and the root it is imported from /// (`src/a/b.py` → `a.b` from `src` in a `src` layout). -fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<(String, String)> { +pub(crate) fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<(String, String)> { let rel = rel_path(root, path)?; let base = python_root(roots, &rel); let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') }; @@ -104,7 +104,7 @@ fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) - } /// The package relative imports in `file` start from. -fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String { +pub(crate) 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 diff --git a/crates/ide-host/src/python_move.py b/crates/ide-host/src/python_move.py new file mode 100644 index 0000000000..6ad51e17a4 --- /dev/null +++ b/crates/ide-host/src/python_move.py @@ -0,0 +1,532 @@ +"""Move top-level functions, classes and variables of a Python module to another module. + +Run by the IDE like `python_signature.py`: one JSON request on stdin, one JSON answer on stdout. +It only turns texts into texts: the IDE reads the files, updates their `from … import` statements +with its module-move rewriter, and passes the results here. This script moves the code, writes the +imports the two modules need and rewrites `module.name` uses. rope's `MoveGlobal` is not used: it +overwrites nothing but happily defines a name twice, empties re-exports and drops imports. +""" + +import ast +import json +import re +import sys + + +class Refused(Exception): + """A move that can't be carried out; the message is shown to the user.""" + + +class Unparsable(Refused): + """A file with a syntax error.""" + + +def parse(text, path): + try: + return ast.parse(text) + except SyntaxError as e: + raise Unparsable(f"Syntax error in {path}: {e.msg} (line {e.lineno})") + + +def lines_of(text): + return [line for line in re.split(r"(?<=\n)", text) if line] + + +class Src: + def __init__(self, text): + self.text, self.lines, self.starts = text, lines_of(text), [0] + for line in self.lines: + self.starts.append(self.starts[-1] + len(line)) + + def off(self, lineno, col): # `ast` columns are UTF-8 byte offsets + line = self.lines[lineno - 1] + return self.starts[lineno - 1] + len(line.encode("utf-8")[:col].decode("utf-8", "ignore")) + + def span(self, node): + return self.off(node.lineno, node.col_offset), self.off(node.end_lineno, node.end_col_offset) + + +def splice(text, edits): + for start, end, new in sorted(set(edits), reverse=True): + text = text[:start] + new + text[end:] + return text + + +# ---------------------------------------------------------------- what a module defines + + +def targets(node): + """The names a top-level statement defines that can be moved.""" + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + return [(node.name, "function")] + if isinstance(node, ast.ClassDef): + return [(node.name, "class")] + if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): + return [(node.targets[0].id, "variable")] + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None: + return [(node.target.id, "variable")] + return [] + + +def first_line(node): + return min([node.lineno] + [d.lineno for d in getattr(node, "decorator_list", [])]) + + +def resolve(level, module, package): + """The absolute module of `from import …` inside `package`.""" + if not level: + return module or "" + parts = package.split(".") if package else [] + keep = len(parts) - (level - 1) + if keep <= 0: + raise Refused("A relative import reaches above the top-level package") + return ".".join(parts[:keep] + ([module] if module else [])) + + +class Binding: + def __init__(self, statement=None, defined=False, conditional=False): + # `statement`: the import that recreates the name elsewhere + self.statement, self.defined, self.conditional = statement, defined, conditional + self.statements = [] # `import a.b` and `import a.c` both bind `a` + self.count = 0 + + +def bindings(tree, package): + """Every name bound at module level, through `if` / `try` / `with` / loops.""" + found = {} + + def add(name, conditional, statement=None, defined=False): + b = found.setdefault(name, Binding(statement, defined, conditional)) + b.count += 1 + if statement and statement not in b.statements: + b.statements.append(statement) + + def walk(node, conditional): + if isinstance(node, ast.Import): + for a in node.names: + if a.asname: + add(a.asname, conditional, f"import {a.name} as {a.asname}") + else: + add(a.name.split(".")[0], conditional, f"import {a.name}") + elif isinstance(node, ast.ImportFrom): + module = resolve(node.level, node.module, package) + for a in node.names: + if a.name != "*": + tail = f" as {a.asname}" if a.asname else "" + add(a.asname or a.name, conditional, f"from {module} import {a.name}{tail}") + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + add(node.name, conditional, defined=True) + elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + add(node.id, conditional, defined=True) + elif not isinstance(node, (ast.Lambda, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): + inner = conditional or isinstance(node, (ast.If, ast.Try, ast.For, ast.While, ast.With, getattr(ast, "Match", ()))) + for child in ast.iter_child_nodes(node): + walk(child, inner) + + for statement in tree.body: + walk(statement, False) + return found + + +def names_read(nodes): + """Every name the code reads, string annotations included.""" + found = set() + for node in nodes: + for n in ast.walk(node): + if isinstance(n, ast.Name) and not isinstance(n.ctx, ast.Store): + found.add(n.id) + for note in (getattr(n, "annotation", None), getattr(n, "returns", None)): + for c in ast.walk(note) if note is not None else (): + if isinstance(c, ast.Constant) and isinstance(c.value, str): + try: + found |= names_read([ast.parse(c.value, mode="eval")]) + except SyntaxError: + pass + return found + + +# ---------------------------------------------------------------- editing a module + + +def import_position(src, tree): + """The line index new imports go to: after the leading imports, the docstring or the comments.""" + last = 0 + for i, node in enumerate(tree.body): + docstring = i == 0 and isinstance(node, ast.Expr) and isinstance(getattr(node.value, "value", None), str) + if not docstring and not isinstance(node, (ast.Import, ast.ImportFrom)): + break + last = node.end_lineno + if not last: + while last < len(src.lines) and src.lines[last].startswith("#"): + last += 1 + return last + + +def add_imports(text, statements, path): + if not statements: + return text + src, tree = Src(text), parse(text, path) + future = [s for s in statements if s.startswith("from __future__ ")] + rest = [s for s in statements if s not in future] + at = import_position(src, tree) + head, tail = "".join(src.lines[:at]), "".join(src.lines[at:]) + if head and not head.endswith("\n"): + head += "\n" + if future: # must precede every other import + first = next((n for n in tree.body if isinstance(n, (ast.Import, ast.ImportFrom))), None) + cut = src.starts[first.lineno - 1] if first else len(head) + head = head[:cut] + "".join(s + "\n" for s in future) + head[cut:] + block = "".join(s + "\n" for s in rest) + if block and head and not any(isinstance(n, (ast.Import, ast.ImportFrom)) for n in tree.body): + block = "\n" + block + if tail.strip() and not tail.startswith("\n") and (rest or future): + tail = "\n\n" + tail + return head + block + tail + + +def cut_blocks(src, tree, nodes): + """(line ranges, texts) of the statements to move, with their decorators and leading comments.""" + ranges, texts = [], [] + for node in nodes: + start, end = first_line(node) - 1, node.end_lineno + for other in tree.body: + if other is not node and first_line(other) <= end and other.end_lineno > start: + raise Refused("A statement shares its line with another one; split them first") + above = max((o.end_lineno for o in tree.body if o.end_lineno <= start), default=0) + top = start + while top > above and src.lines[top - 1].startswith("#") and not re.match(r"#!|#.*coding[:=]", src.lines[top - 1]): + top -= 1 + # comments reaching the top of the file are its header (copyright, license), not the node's + if top and any(line.strip() and not line.startswith("#") for line in src.lines[:top]): + start = top + # indented comments after the body belong to it + probe = end + while probe < len(src.lines) and (not src.lines[probe].strip() or src.lines[probe][0] in " \t"): + if src.lines[probe].strip().startswith("#"): + end = probe + 1 + elif src.lines[probe].strip(): + break + probe += 1 + ranges.append((start, end)) + texts.append("".join(src.lines[start:end]).rstrip("\n")) + return ranges, texts + + +def remove_ranges(src, ranges): + lines = list(src.lines) + for start, end in sorted(ranges, reverse=True): + before, after = "".join(lines[:start]).rstrip("\n"), "".join(lines[end:]).lstrip("\n") + if before and after: + joined = before + "\n\n\n" + after + else: + joined = before + "\n" if before else after + lines = lines_of(joined) + return "".join(lines) + + +# ---------------------------------------------------------------- `module.name` uses + + +def chain(node): + parts = [] + while isinstance(node, ast.Attribute): + parts.append(node.attr) + node = node.value + return ".".join([node.id] + parts[::-1]) if isinstance(node, ast.Name) else None + + +def takes(tree, module): + """Whether the first part of `module` is already bound here to something else.""" + root = module.split(".")[0] + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store) and node.id == root: + return True + if isinstance(node, ast.arg) and node.arg == root: + return True + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and node.name == root: + return True + if isinstance(node, ast.ImportFrom) and any((a.asname or a.name) == root for a in node.names): + return True + if isinstance(node, ast.Import) and any(a.asname == root and a.name != root for a in node.names): + return True + return False + + +def rewrite_uses(path, text, package, names, source, dest, is_dest, warnings, show): + """`source.name` uses become `dest.name` (a bare `name` in the destination itself).""" + src, tree = Src(text), parse(text, path) + modules = {} # how this file spells the source module -> its import statements + stars = [] + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for a in node.names: + if a.name == source: + modules.setdefault(a.asname or a.name, []).append(node) + elif isinstance(node, ast.ImportFrom): + try: + module = resolve(node.level, node.module, package) + except Refused: + continue + for a in node.names: + if a.name == "*" and module == source: + stars.append(node) + elif a.name != "*" and f"{module}.{a.name}".lstrip(".") == source: + modules.setdefault(a.asname or a.name, []).append(node) + rebound = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)} + rebound |= {n.arg for n in ast.walk(tree) if isinstance(n, ast.arg)} + edits, after = [], {} # after: import node -> statements to put behind it + for node in ast.walk(tree): + if isinstance(node, ast.Constant) and isinstance(node.value, str): + if any(node.value == f"{source}.{n}" or node.value.startswith(f"{source}.{n}.") for n in names): + warnings.append(f"{show}:{node.lineno}: the string '{node.value}' still names the old module.") + if not (isinstance(node, ast.Attribute) and node.attr in names): + continue + spelled = chain(node.value) + if spelled not in modules: + continue + if spelled.split(".")[0] in rebound: + warnings.append(f"{show}:{node.lineno}: '{spelled}' is also a local name here; '{spelled}.{node.attr}' was not updated.") + continue + start, end = src.span(node) + if is_dest: + edits.append((start, end, node.attr)) + else: + if takes(tree, dest): + raise Refused(f"{show} already uses the name '{dest.split('.')[0]}' for something else") + edits.append((start, end, f"{dest}.{node.attr}")) + for statement in modules[spelled]: + after.setdefault(statement, set()).add(f"import {dest}") + used = names_read([tree]) + for node in stars: + wanted = sorted(used & set(names)) + if wanted and not is_dest: + after.setdefault(node, set()).add(f"from {dest} import {', '.join(wanted)}") + warnings.append(f"{show}:{node.lineno}: 'import *' no longer brings {', '.join(wanted)}; an explicit import was added.") + for node, statements in after.items(): + start, end = src.span(node) + before = src.text[src.starts[node.lineno - 1]:start] + rest = src.text[end:src.starts[node.end_lineno]].strip() + if before.strip() or (rest and not rest.startswith("#")): + # shares its line (`import a; a.f()`, `try: import a`) + edits.append((end, end, "".join(f"; {s}" for s in sorted(statements)))) + else: + end = src.starts[node.end_lineno - 1] + len(src.lines[node.end_lineno - 1].rstrip("\r\n")) + edits.append((end, end, "".join(f"\n{before}{s}" for s in sorted(statements)))) + return splice(text, edits) + + +# ---------------------------------------------------------------- where the code goes + +DEFS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) + + +def import_time(node): + """The parts of a statement that run when its module is imported.""" + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + args = node.args + notes = [a.annotation for a in args.posonlyargs + args.args + args.kwonlyargs + [args.vararg, args.kwarg] if a] + return [n for n in node.decorator_list + args.defaults + args.kw_defaults + notes + [node.returns] if n] + if isinstance(node, ast.ClassDef): + head = node.decorator_list + node.bases + [k.value for k in node.keywords] + return head + [part for child in node.body for part in import_time(child)] + return [node] + + +def is_main_guard(node): + return isinstance(node, ast.If) and "__name__" in names_read([node.test]) + + +def place(text, code, moved_nodes, names, path): + """`text` with `code` after what it needs to be defined and before what needs it at import.""" + src, tree = Src(text), parse(text, path) + needs = names_read([part for n in moved_nodes for part in import_time(n)]) - set(names) + # local functions and classes that read a moved name: calling them at import needs it too + users, grew = set(names), True + while grew: + grew = False + for node in tree.body: + if isinstance(node, DEFS) and node.name not in users and names_read([node]) & users: + users.add(node.name) + grew = True + lower, upper = 0, None + for node in tree.body: + if isinstance(node, (ast.Import, ast.ImportFrom)): + bound = {(a.asname or a.name).split(".")[0] for a in node.names} + elif isinstance(node, DEFS): + bound = {node.name} + else: + bound = {n.id for n in ast.walk(node) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)} + if upper is None and (is_main_guard(node) or names_read(import_time(node)) & users): + upper = first_line(node) - 1 + if bound & needs: + if upper is not None: + raise Refused(f"{path} uses a moved name before what the moved code needs is defined") + lower = node.end_lineno + if upper is None: + return (text.rstrip("\n") + "\n\n\n" if text.strip() else "") + code + "\n" + while upper > lower and src.lines[upper - 1].startswith("#"): + upper -= 1 + # as early as the imports and the needed definitions allow when something below uses it + at = upper + head, tail = "".join(src.lines[:at]).rstrip("\n"), "".join(src.lines[at:]).lstrip("\n") + return (head + "\n\n\n" if head else "") + code + "\n\n\n" + tail + + +# ---------------------------------------------------------------- the move + + +def symbols(req): + """The movable names of the module; `selected` marks the one at the caret line.""" + tree = parse(req["text"], "the file") + line = req["line"] + 1 + out = [] + for node in tree.body: + for name, kind in targets(node): + if all(s["name"] != name for s in out): + out.append({"name": name, "kind": kind, "selected": first_line(node) <= line <= node.end_lineno}) + if not out: + raise Refused("There are no top-level functions, classes or variables to move") + return out + + +def move(req): + source, dest, names = req["source"], req["dest"], req["names"] + if not names: + raise Refused("Select something to move") + src, tree = Src(source["text"]), parse(source["text"], source["show"]) + dest_text = dest["text"] or "" + dest_tree = parse(dest_text, dest["show"]) + here = bindings(tree, source["package"]) + there = bindings(dest_tree, dest["package"]) + warnings = [] + + nodes = [n for n in tree.body if any(name in names for name, _ in targets(n))] + missing = set(names) - {name for n in nodes for name, _ in targets(n)} + if missing: + raise Refused(f"'{sorted(missing)[0]}' is not a top-level function, class or variable") + for name in names: + if here[name].count > 1: + raise Refused(f"'{name}' is assigned or defined in several places; move it by hand") + for node in ast.walk(tree): + if isinstance(node, ast.Global) and set(node.names) & set(names): + raise Refused(f"'{sorted(set(node.names) & set(names))[0]}' is written through 'global'") + for node in (n for m in nodes for n in ast.walk(m)): + if isinstance(node, ast.Global) and set(node.names) - set(names): + raise Refused(f"The moved code writes the global '{node.names[0]}' of its module") + + # the destination may already import what is moving there + own_imports = {f"from {source['module']} import {n}": n for n in names} + for name in names: + existing = there.get(name) + if existing and (existing.defined or existing.statement not in own_imports): + raise Refused(f"'{name}' is already defined in {dest['show']}") + + # what the moved code needs where it lands + read = names_read(nodes) + needed, from_source = [], [] + for name in sorted(read - set(names)): + b = here.get(name) + if b is None: + continue + wanted = [f"from {source['module']} import {name}"] if b.defined else b.statements + if any(w.startswith(f"from {dest['module']} import ") for w in wanted): + continue # it comes from the destination itself + if not b.defined and b.conditional and len(wanted) > 1 and not all(w.startswith("import ") for w in wanted): + wanted = wanted[:1] # `try: import ujson as json` / `except: import json` + other = there.get(name) + if other: + # `import a.b` and `import a.c` agree on what `a` is + plain = all(w.startswith("import ") and " as " not in w for w in wanted + other.statements) + if other.defined or not (plain or set(wanted) & set(other.statements)): + raise Refused(f"'{name}' means something else in {dest['show']}") + wanted = [w for w in wanted if w not in other.statements] + if wanted and b.conditional and not b.defined: + warnings.append(f"'{name}' is imported conditionally; {dest['show']} imports it unconditionally.") + (from_source if b.defined else needed).extend(wanted) + for node in tree.body: + if isinstance(node, ast.ImportFrom): + if node.module == "__future__": + statement = f"from __future__ import {', '.join(a.name for a in node.names)}" + if statement not in ast.unparse(dest_tree).split("\n"): + needed.append(statement) + elif any(a.name == "*" for a in node.names): + warnings.append(f"{source['show']} uses 'import *'; check that {dest['show']} imports what the moved code needs.") + for name in sorted(read & {"__file__", "__name__", "__package__"}): + warnings.append(f"The moved code reads {name}, which changes with the module.") + + ranges, blocks = cut_blocks(src, tree, nodes) + + # the source keeps importing what it still uses + left = remove_ranges(src, ranges) + left_tree = parse(left, source["show"]) + exported = { + c.value + for n in left_tree.body if isinstance(n, (ast.Assign, ast.AnnAssign, ast.AugAssign)) + if any(isinstance(t, ast.Name) and t.id == "__all__" for t in ast.walk(n)) + for c in ast.walk(n) if isinstance(c, ast.Constant) + } + still = sorted(set(names) & (names_read([left_tree]) | exported)) + if still: + left = add_imports(left, [f"from {dest['module']} import {', '.join(still)}"], source["show"]) + if still and from_source: + warnings.append(f"{source['show']} and {dest['show']} would import each other.") + + # the destination: drop its imports of the moved names, add what is needed, then the code + edits, dest_src = [], Src(dest_text) + for node in ast.walk(dest_tree): + if isinstance(node, ast.ImportFrom) and resolve(node.level, node.module, dest["package"]) == source["module"]: + if any(a.name in names and a.asname for a in node.names): + raise Refused(f"{dest['show']} imports a moved name under another name; remove the alias first") + kept = [a for a in node.names if a.name not in names] + if len(kept) == len(node.names): + continue + start, end = dest_src.span(node) + alone = node in dest_tree.body and not dest_src.text[end:dest_src.starts[node.end_lineno]].strip() + if kept: + node.names = kept + edits.append((start, end, ast.unparse(node))) + elif alone and not node.col_offset: + edits.append((dest_src.starts[node.lineno - 1], dest_src.starts[node.end_lineno], "")) + else: + edits.append((start, end, "pass")) + new = splice(dest_text, edits) + new = rewrite_uses(dest["show"], new, dest["package"], names, source["module"], dest["module"], True, warnings, dest["show"]) + new = add_imports(new, needed + from_source, dest["show"]) + new = place(new, "\n\n\n".join(blocks), nodes, names, dest["show"]) + + files = {source["path"]: left, dest["path"]: new} + for path, other in req["others"].items(): + try: + files[path] = rewrite_uses( + path, other["text"], other["package"], names, source["module"], dest["module"], False, warnings, other["show"] + ) + except Unparsable: + warnings.append(f"{other['show']} has a syntax error and was not checked.") + for path, text in files.items(): + original = other_text(req, path) + if text != original: + try: + ast.parse(text) + except SyntaxError as e: + raise Refused(f"The move would make {path} invalid: {e.msg} (line {e.lineno})") + return {"files": files, "warnings": sorted(set(warnings), key=warnings.index)} + + +def other_text(req, path): + for side in (req["source"], req["dest"]): + if side["path"] == path: + return side["text"] + return req["others"][path]["text"] + + +def main(): + req = json.loads(sys.stdin.buffer.read()) + try: + out = {"ok": True, "result": symbols(req) if req["op"] == "symbols" else move(req)} + except Refused as e: + out = {"ok": False, "error": str(e)} + json.dump(out, sys.stdout) + + +if __name__ == "__main__": + main() diff --git a/crates/ide-host/src/python_move.rs b/crates/ide-host/src/python_move.rs new file mode 100644 index 0000000000..800ccb02b6 --- /dev/null +++ b/crates/ide-host/src/python_move.rs @@ -0,0 +1,230 @@ +//! 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 }) +} diff --git a/crates/ide-host/src/python_signature.rs b/crates/ide-host/src/python_signature.rs index b87a4519ee..f2f1f17939 100644 --- a/crates/ide-host/src/python_signature.rs +++ b/crates/ide-host/src/python_signature.rs @@ -61,11 +61,11 @@ struct Changed { warnings: Vec, } -struct Context { - root: PathBuf, - file: PathBuf, - pos: Pos, - overlay: BTreeMap, +pub(crate) struct Context { + pub(crate) root: PathBuf, + pub(crate) file: PathBuf, + pub(crate) pos: Pos, + pub(crate) overlay: BTreeMap, } fn context(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<(std::sync::Arc, Context)> { @@ -90,7 +90,13 @@ fn context(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<(std::s } /// Runs the helper with `request`; its answer is the `result`, a refusal is an invalid-input error. -async fn run(host: &Host, mut request: Value, cx: &Context, cancel: &CancellationToken) -> IdeResult { +pub(crate) async fn run( + host: &Host, + helper: &str, + mut request: Value, + cx: &Context, + cancel: &CancellationToken, +) -> IdeResult { request["root"] = json!(cx.root); request["file"] = json!(cx.file); request["line"] = json!(cx.pos.line); @@ -107,7 +113,7 @@ async fn run(host: &Host, mut request: Value, cx: &Context, cancel: &Cancellatio let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start Python: {e}")))?; let pid = child.id(); let mut stdin = child.stdin.take().expect("piped"); - let payload = format!("{}\n{HELPER}{request}", HELPER.len()); + let payload = format!("{}\n{helper}{request}", helper.len()); tokio::spawn(async move { let _ = stdin.write_all(payload.as_bytes()).await; }); @@ -149,7 +155,7 @@ pub async fn signature_info( cancel: CancellationToken, ) -> IdeResult { let (_, cx) = context(host, window, doc, pos)?; - let info: Info = serde_json::from_value(run(host, json!({ "op": "info" }), &cx, &cancel).await?) + let info: Info = serde_json::from_value(run(host, HELPER, json!({ "op": "info" }), &cx, &cancel).await?) .map_err(|e| IdeError::new(ErrorKind::Protocol, e.to_string()))?; Ok(MethodSignature { method_identifier: String::new(), @@ -184,7 +190,7 @@ pub async fn change_signature( let (project, cx) = context(host, window, doc, pos)?; // Calls a type-aware server resolves and rope can't (`def f(o: Base): o.run()`). They are asked // for at the function's own name: the caret may be on something else in its header. - let info: Info = serde_json::from_value(run(host, json!({ "op": "info" }), &cx, &cancel).await?) + let info: Info = serde_json::from_value(run(host, HELPER, json!({ "op": "info" }), &cx, &cancel).await?) .map_err(|e| IdeError::new(ErrorKind::Protocol, e.to_string()))?; let at = if info.file == cx.file { Pos::new(info.line, info.col) } else { pos }; let sites = match project.lsp.references_streaming(doc, at, false, true, false, cancel.clone(), None).await { @@ -212,7 +218,7 @@ pub async fn change_signature( "sites": sites, "change": { "name": signature.method_name, "params": rows, "hierarchy": true }, }); - let changed: Changed = serde_json::from_value(run(host, request, &cx, &cancel).await?) + let changed: Changed = serde_json::from_value(run(host, HELPER, request, &cx, &cancel).await?) .map_err(|e| IdeError::new(ErrorKind::Protocol, e.to_string()))?; let problems: Vec = changed .warnings @@ -256,7 +262,7 @@ fn line_edits(before: &str, after: &str) -> Vec { edits } -fn to_edit( +pub(crate) fn to_edit( project: &crate::Project, files: BTreeMap, computed_from: &BTreeMap, diff --git a/crates/ide-host/tests/python_move.rs b/crates/ide-host/tests/python_move.rs new file mode 100644 index 0000000000..441d559c8b --- /dev/null +++ b/crates/ide-host/tests/python_move.rs @@ -0,0 +1,400 @@ +//! Python Move through the commands the app calls, on real files: each moved project is run with +//! Python before and after, and must print the same. `#[ignore]`d: it needs `pylsp` on `PATH` +//! (the helper runs with that environment's Python). + +mod common; + +use ide_core::{ChangeSet, IdeEvent, RequestId, SharedSink, TextChange}; +use ide_host::{Host, HostConfig, ops}; +use ide_lsp::types::ServerRefactored; +use parking_lot::Mutex; +use serde_json::json; +use std::path::PathBuf; +use std::sync::Arc; + +struct Project { + _tmp: tempfile::TempDir, + root: PathBuf, + host: Host, + events: Arc>>, +} + +impl Project { + async fn new(files: &[(&str, &str)]) -> Self { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap().join("app"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"app\"\n").unwrap(); + for (name, text) in files { + let path = root.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + let events: Arc>> = Arc::default(); + let sink: SharedSink = { + let events = events.clone(); + Arc::new(move |event| events.lock().push(event)) + }; + let host = Host::new(HostConfig { + sink_for: Box::new(move |_| sink.clone()), + ..common::host_config(&root.join(".app")) + }); + host.set_project_trust(&root, true, false).await.unwrap(); + host.open_project("main", &root).unwrap(); + Self { _tmp: tmp, root, host, events } + } + + /// Moves `names` of `source` to `dest`, accepting any warnings, and applies the edit. + async fn try_move(&self, source: &str, names: &[&str], dest: &str) -> Result, String> { + let doc = ops::doc::doc_open(&self.host, "main", self.root.join(source)).await.unwrap(); + let args = json!({ "names": names, "file": dest }).to_string(); + let send = |confirmation| { + ops::lsp::lsp_java_move( + &self.host, + "main", + RequestId(1), + doc.id, + "python".into(), + args.clone(), + confirmation, + ) + }; + let mut answer: ServerRefactored = send(None).await.map_err(|e| e.message)?; + let mut warnings = Vec::new(); + if answer.confirmation.is_some() { + assert!(answer.edit.is_none(), "nothing before the confirmation"); + warnings = answer.problems.iter().map(|p| p.message.clone()).collect(); + answer = send(answer.confirmation).await.map_err(|e| e.message)?; + } + ops::lsp::apply_workspace_edit(&self.host, "main", answer.edit.expect("an edit")).await.unwrap(); + Ok(warnings) + } + + async fn text(&self, file: &str) -> String { + let doc = ops::doc::doc_open(&self.host, "main", self.root.join(file)).await.unwrap(); + ops::doc::doc_snapshot(&self.host, "main", doc.id).await.unwrap().text + } + + /// Writes the editors' texts out and runs `main.py`. + async fn output(&self) -> String { + self.output_without(&[]).await + } + + async fn output_without(&self, skipped: &[&str]) -> String { + for file in walk(&self.root).into_iter().filter(|f| !skipped.contains(&f.as_str())) { + let text = self.text(&file).await; + std::fs::write(self.root.join(file), text).unwrap(); + } + let out = std::process::Command::new(if cfg!(windows) { "python" } else { "python3" }) + .args(["-B", "main.py"]) + .current_dir(&self.root) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n") + } +} + +fn walk(root: &std::path::Path) -> Vec { + let mut found = Vec::new(); + let mut folders = vec![root.to_path_buf()]; + while let Some(folder) = folders.pop() { + for entry in std::fs::read_dir(folder).unwrap().flatten() { + let path = entry.path(); + if path.is_dir() && !entry.file_name().to_string_lossy().starts_with('.') { + folders.push(path); + } else if path.extension().is_some_and(|e| e == "py") { + found.push(path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/")); + } + } + } + found +} + +const LIB: &str = r#""""Library.""" +import os +from math import floor + +SEP = os.sep +LIMIT: int = 3 + + +def helper(x): + return floor(x) + LIMIT + + +# The thing to move. +# 中文注释 🎉 +@staticmethod +def double(x) -> "int": + return helper(x) * 2 + + +class Box: + def __init__(self, v=LIMIT): + self.v = double(v) + + +def keep(): + return Box().v +"#; + +const MAIN: &str = r#"import pkg.lib +import pkg.lib as aliased +from pkg import lib +from pkg.lib import Box, double as twice, keep +from pkg import Box as Exported + +print(pkg.lib.Box(1).v, aliased.double(1), lib.double(2)) +print(Box(2).v, twice(3), keep(), Exported().v) +"#; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn moves_into_a_new_module_and_updates_every_spelling_then_undoes_it() { + let p = Project::new(&[ + ("pkg/__init__.py", "from .lib import Box\n"), + ("pkg/lib.py", LIB), + ("pkg/rel.py", "from . import lib\nfrom .lib import Box\n\n\ndef f():\n return lib.Box().v + Box().v\n"), + ("main.py", &format!("{MAIN}from pkg.rel import f\nprint(f())\n")), + ]) + .await; + let before = p.output().await; + let warnings = p.try_move("pkg/lib.py", &["double", "Box"], "pkg/shapes/box.py").await.unwrap(); + assert!(warnings.iter().any(|w| w.contains("import each other")), "{warnings:?}"); + + let lib = p.text("pkg/lib.py").await; + assert!(lib.contains("from pkg.shapes.box import Box\n"), "{lib}"); + assert!(!lib.contains("def double") && !lib.contains("class Box") && !lib.contains("中文"), "{lib}"); + let moved = p.text("pkg/shapes/box.py").await; + assert!(moved.contains("# The thing to move.\n# 中文注释 🎉\n@staticmethod\ndef double"), "{moved}"); + assert!(moved.contains("from pkg.lib import LIMIT\n") && moved.contains("from pkg.lib import helper\n"), "{moved}"); + assert_eq!(p.text("pkg/__init__.py").await, "from .shapes.box import Box\n"); + // The two modules now import each other, which is the one warning. + assert_eq!(warnings.len(), 1, "{warnings:?}"); + + let id = p + .events + .lock() + .iter() + .find_map(|e| match e { + IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id), + _ => None, + }) + .unwrap(); + ops::lsp::undo_workspace_edit(&p.host, "main", id).await.unwrap(); + assert!(!p.root.join("pkg/shapes").join("box.py").exists(), "the new module is removed again"); + assert_eq!(p.text("pkg/lib.py").await, LIB); + assert_eq!(p.output().await, before); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn the_moved_project_runs_the_same() { + let p = Project::new(&[ + ("pkg/__init__.py", "from .lib import Box\n"), + ( + "pkg/lib.py", + "from __future__ import annotations\n\nimport json\nfrom . import consts\nfrom .consts import N as COUNT\n\n\nclass Box:\n v: int = COUNT + consts.N\n\n def dump(self) -> str:\n return json.dumps(self.v)\n\n\ndef make():\n return Box()\n\n\nprint(make().dump())\n", + ), + ("pkg/consts.py", "N = 2\n"), + ("pkg/other.py", "\"\"\"Doc.\"\"\"\nimport sys\n\nHAVE = sys.maxsize > 0\n"), + ( + "main.py", + "import pkg.lib\nfrom pkg.lib import *\nfrom pkg import lib as l\nfrom pkg import Box as B\n\nprint(Box().dump(), l.make().v, pkg.lib.Box.v, B.v, make().v)\n", + ), + ]) + .await; + let before = p.output().await; + let warnings = p.try_move("pkg/lib.py", &["Box"], "pkg/other.py").await.unwrap(); + assert!(warnings.iter().any(|w| w.contains("import *")), "{warnings:?}"); + let other = p.text("pkg/other.py").await; + assert!(other.starts_with("\"\"\"Doc.\"\"\"\nfrom __future__ import annotations\n"), "{other}"); + assert!(other.contains("from pkg.consts import N as COUNT\n") && other.contains("import json\n"), "{other}"); + assert_eq!(p.output().await, before); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn a_destination_that_uses_the_name_gets_it_defined_first() { + let p = Project::new(&[ + ("a.py", "def f():\n return 1\n\n\ndef g():\n return 2\n"), + ("b.py", "import a\nfrom a import f, g\n\nX = f() + a.f() + g()\n"), + ("main.py", "import b\nprint(b.X, b.f())\n"), + ]) + .await; + let before = p.output().await; + // unsaved: a use that exists only in the editor + let doc = ops::doc::doc_open(&p.host, "main", p.root.join("main.py")).await.unwrap(); + let at = doc.text.len() as u32; + let change = + ChangeSet { changes: vec![TextChange { from: at, to: at, insert: "import a\nprint(a.f())\n".into() }] }; + ops::doc::doc_edit(&p.host, "main", doc.id, doc.version, change).await.unwrap(); + p.try_move("a.py", &["f"], "b.py").await.unwrap(); + let b = p.text("b.py").await; + assert!(b.find("def f").unwrap() < b.find("X = ").unwrap(), "{b}"); + assert!(b.contains("X = f() + f() + g()"), "{b}"); + assert!(p.text("main.py").await.contains("print(b.f())"), "{}", p.text("main.py").await); + assert_eq!(p.output().await, format!("{before}1\n")); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn refuses_what_it_cannot_move_safely_and_changes_nothing() { + let source = "import os\n\nA = 1\nA = 2\n\n\ndef f():\n return os.sep\n\n\ndef g():\n global C\n C = 1\n\n\nC = 0\nD = 1; E = 2\n"; + let p = Project::new(&[ + ("a.py", source), + ("taken.py", "def f():\n pass\n"), + ("os_is_mine.py", "os = 1\n"), + ("alias.py", "from a import f as h\n"), + ("broken.py", "def (:\n"), + ]) + .await; + for (names, dest, reason) in [ + (vec!["f"], "taken.py", "already defined"), + (vec!["f"], "os_is_mine.py", "means something else"), + (vec!["f"], "alias.py", "another name"), + (vec!["f"], "broken.py", "Syntax error"), + (vec!["f"], "a.py", "itself"), + (vec!["f"], "new.txt", ".py file"), + (vec!["f"], "../out.py", ".py file"), + (vec!["f"], "1bad.py", "Python module"), + (vec!["A"], "new.py", "several places"), + (vec!["g"], "new.py", "global"), + (vec!["C"], "new.py", "global"), + (vec!["D"], "new.py", "shares its line"), + (vec!["missing"], "new.py", "not a top-level"), + (vec![], "new.py", "Select"), + ] { + let error = p.try_move("a.py", &names, dest).await.unwrap_err(); + assert!(error.contains(reason), "{names:?} -> {dest}: {error}"); + } + assert_eq!(p.text("a.py").await, source); + assert!(!p.root.join("new.py").exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn reports_what_it_leaves_alone() { + let p = Project::new(&[ + ("a.py", "def f():\n return __name__\n"), + ("use.py", "import a\n\nTARGET = 'a.f'\n\n\ndef g(a):\n return a.f\n"), + ("broken.py", "import a\ndef (:\n"), + ]) + .await; + let warnings = p.try_move("a.py", &["f"], "b.py").await.unwrap(); + for part in ["__name__", "the string 'a.f'", "local name", "syntax error"] { + assert!(warnings.iter().any(|w| w.contains(part)), "{part}: {warnings:?}"); + } + assert!(p.text("use.py").await.ends_with("def g(a):\n return a.f\n")); + assert_eq!(p.text("a.py").await, ""); + assert_eq!(p.text("b.py").await, "def f():\n return __name__\n"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn lists_the_movable_names_and_marks_the_one_at_the_caret() { + let p = Project::new(&[("lib.py", LIB)]).await; + let doc = ops::doc::doc_open(&p.host, "main", p.root.join("lib.py")).await.unwrap(); + let line = LIB.lines().position(|l| l == "@staticmethod").unwrap(); + let args = json!({ "line": line }).to_string(); + let found = ops::lsp::lsp_java_move_destinations(&p.host, "main", RequestId(1), doc.id, "python".into(), args) + .await + .unwrap(); + let found: Vec = found.iter().map(|s| serde_json::from_str(s).unwrap()).collect(); + let names: Vec<_> = found.iter().map(|s| s["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["SEP", "LIMIT", "helper", "double", "Box", "keep"]); + let selected: Vec<_> = found.iter().filter(|s| s["selected"] == true).map(|s| &s["name"]).collect(); + assert_eq!(selected, ["double"]); +} + +/// Order at import time: moved code goes after what it needs and before what needs it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn places_the_code_where_the_destination_still_runs() { + let p = Project::new(&[ + ("a.py", "def f():\n return 1\n # end of f\n\n\nclass C(__import__('b').Base):\n pass\n"), + ( + "b.py", + "class Base:\n pass\n\n\ndef main():\n print(f())\n\n\nif __name__ == '__main__':\n main()\n\n\ndef lazy():\n from a import f\n return f()\n", + ), + ("main.py", "import runpy\n\nimport b\n\nrunpy.run_path('b.py', run_name='__main__')\nprint(b.lazy())\n"), + ]) + .await; + p.try_move("a.py", &["f"], "b.py").await.unwrap(); + let b = p.text("b.py").await; + assert!(b.find("def f").unwrap() < b.find("if __name__").unwrap(), "{b}"); + assert!(b.contains("# end of f") && !p.text("a.py").await.contains("end of f"), "{b}"); + assert_eq!(p.output().await, "1\n1\n"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn every_import_of_the_module_gets_the_new_one() { + let p = Project::new(&[ + ("a.py", "import urllib.parse\nimport urllib.request\n\n\ndef f():\n return urllib.parse.quote(' '), urllib.request.__name__\n"), + ( + "main.py", + "def g():\n import a\n return a.f()\n\n\ndef h():\n import a\n return a.f()\n\n\nimport a; print(a.f())\ntry: import a\nexcept ImportError: pass\nprint(g(), h(), a.f())\n", + ), + ]) + .await; + let before = p.output().await; + p.try_move("a.py", &["f"], "b.py").await.unwrap(); + assert_eq!(p.output().await, before); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn refuses_shadowed_names_and_shadowed_destinations() { + let source = "def f():\n pass\n"; + let p = Project::new(&[ + ("a.py", source), + ("use.py", "import a\n\n\ndef g(b):\n return a.f(), b\n"), + ("utils/__init__.py", ""), + ("pkg.py", ""), + ("early.py", "X = f()\n\n\nclass Base:\n pass\n"), + ("c.py", "from early import Base\n\n\nclass D(Base):\n pass\n"), + ]) + .await; + for (dest, reason) in [("b.py", "already uses the name 'b'"), ("utils.py", "same name"), ("pkg/x.py", "same name")] + { + let error = p.try_move("a.py", &["f"], dest).await.unwrap_err(); + assert!(error.contains(reason), "{dest}: {error}"); + } + p.try_move("c.py", &["D"], "early.py").await.unwrap(); + assert!(p.text("early.py").await.find("class Base").unwrap() < p.text("early.py").await.find("class D").unwrap()); + assert_eq!(p.text("a.py").await, source); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn refuses_a_destination_behind_a_link_out_of_the_project() { + let p = Project::new(&[("a.py", "def f():\n pass\n")]).await; + let outside = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(outside.path(), p.root.join("linked")).unwrap(); + let error = p.try_move("a.py", &["f"], "linked/b.py").await.unwrap_err(); + assert!(error.contains("inside the project"), "{error}"); +} + +/// Closed files keep their byte order mark and encoding; a package's `from . import name` follows. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "needs pylsp on PATH"] +async fn closed_files_in_other_encodings_and_package_imports() { + let p = Project::new(&[ + ("pkg/__init__.py", "# Copyright ACME\ndef helper():\n return 1\n"), + ("pkg/rel.py", "from . import helper\n\nX = helper()\n"), + ("bom.py", "\u{feff}import os\nfrom pkg import helper\nprint(helper(), os.sep != '')\n"), + ("main.py", "import bom\nfrom pkg.rel import X\nprint(X)\n"), + ]) + .await; + // GBK, not UTF-8 + std::fs::write(p.root.join("gbk.py"), b"# -*- coding: gbk -*-\n# \xd6\xd0\nimport os\n").unwrap(); + let before = p.output_without(&["gbk.py"]).await; + p.try_move("pkg/__init__.py", &["helper"], "pkg/tools.py").await.unwrap(); + assert!(std::fs::read(p.root.join("bom.py")).unwrap().starts_with("\u{feff}import os\n".as_bytes())); + assert!(p.text("pkg/__init__.py").await.starts_with("# Copyright ACME")); + assert!(p.text("pkg/rel.py").await.contains("tools import helper"), "{}", p.text("pkg/rel.py").await); + assert_eq!(p.output_without(&["gbk.py"]).await, before); +} diff --git a/docs/en/guide/refactoring.mdx b/docs/en/guide/refactoring.mdx index 1d93034cfc..730bb92c22 100644 --- a/docs/en/guide/refactoring.mdx +++ b/docs/en/guide/refactoring.mdx @@ -27,7 +27,7 @@ The **Refactor** menu has IntelliJ IDEA's refactorings with their usual shortcut | **Extract Interface…** | — | — | Java (dialog); TypeScript: language server | | **Extract Type Alias…** | — | — | TypeScript, JavaScript (`@typedef`): language server | | **Inline…** | `⌥⌘N` | `Ctrl+Alt+N` | Language server | -| **Move…** | `F6` | `F6` | Language server (symbols); the IDE (files and folders) | +| **Move…** | `F6` | `F6` | Language server or Python (symbols); the IDE (files) | | **Safe Delete…** | `⌘⌦` | `Alt+Delete` | The IDE, using the server's references | | **Pull Members Up…** | — | — | Java; PHP with Phoxite | | **Push Members Down…** | — | — | Java; PHP with Phoxite | @@ -67,6 +67,8 @@ In the Project view, **Rename…** (`⇧F6` / `Shift+F6`), **Move…** (`F6`, dr 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. +In Python, **Move…** (`F6`) in a `.py` file moves top-level functions, classes and variables to another module. The dialog lists them (the one at the caret is checked) and takes the destination **To file**, a `.py` path inside the project that may not exist yet. Decorators and the comments above move along, both modules get the imports they need, and `from … import` statements and `module.name` uses across the project, unsaved editors included, point to the new module. A name already defined at the destination is refused; import cycles, `import *`, strings naming the old module and similar cases are listed in a confirmation first. Class methods are not moved. It runs with the Python of **pylsp-rope (Python refactorings)**. + ## Safe Delete diff --git a/docs/zh/guide/refactoring.mdx b/docs/zh/guide/refactoring.mdx index e0b12b4435..7953dfe833 100644 --- a/docs/zh/guide/refactoring.mdx +++ b/docs/zh/guide/refactoring.mdx @@ -27,7 +27,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安 | **提取接口…** | — | — | Java(对话框);TypeScript:语言服务器 | | **提取类型别名…** | — | — | TypeScript、JavaScript(`@typedef`):语言服务器 | | **内联…** | `⌥⌘N` | `Ctrl+Alt+N` | 语言服务器 | -| **移动…** | `F6` | `F6` | 语言服务器(符号);IDE(文件和文件夹) | +| **移动…** | `F6` | `F6` | 语言服务器或 Python(符号);IDE(文件) | | **安全删除…** | `⌘⌦` | `Alt+Delete` | IDE,借助服务器查找引用 | | **上拉成员…** | — | — | Java;PHP(使用 Phoxite) | | **下推成员…** | — | — | Java;PHP(使用 Phoxite) | @@ -62,6 +62,8 @@ description: "重命名、引入与提取、内联、移动、更改签名和安 在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。在 Java 中会先询问目标:顶层类移动到其他包(包声明、import 和所有引用随之更新),静态成员或嵌套类移动到其他类,实例方法移动到其某个字段或形参的类;有警告时先在 **检测到问题** 中确认。 +在 Python 的 `.py` 文件中,**移动…**(`F6`)把顶层的函数、类和变量移到另一个模块。对话框列出它们(光标所在的那个默认勾选),在 **目标文件** 中填写项目内的 `.py` 路径,可以是尚不存在的文件。装饰器和上方的注释一起移动,两个模块各自补齐需要的 import,项目中(包括未保存的编辑器)的 `from … import` 语句和 `模块.名称` 用法改为指向新模块。目标模块已定义同名内容时会拒绝;循环导入、`import *`、仍写着旧模块名的字符串等情况会先列出请你确认。类的方法不能移动。它使用 **pylsp-rope(Python 重构)** 环境中的 Python 运行。 + ## 安全删除 diff --git a/src/editor/lsp/index.ts b/src/editor/lsp/index.ts index e6ea0eb6bc..68848064d3 100644 --- a/src/editor/lsp/index.ts +++ b/src/editor/lsp/index.ts @@ -52,6 +52,7 @@ import { ChangeSignatureDialog, ExtractInterfaceDialog, HierarchyDialog, + PythonMoveDialog, JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand, } from "@/editor/refactor"; @@ -139,6 +140,7 @@ export function activate(): () => void { registerOverlay({ id: "editor-lsp.hierarchyDialog", component: HierarchyDialog }), registerOverlay({ id: "editor-lsp.changeSignatureDialog", component: ChangeSignatureDialog }), registerOverlay({ id: "editor-lsp.extractInterfaceDialog", component: ExtractInterfaceDialog }), + registerOverlay({ id: "editor-lsp.pythonMoveDialog", component: PythonMoveDialog }), registerOverlay({ id: "editor-lsp.memberChooser", component: MemberChooserDialog }), registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand), registerClientCommand(MOVE_TO_FILE_COMMAND, moveToFile), diff --git a/src/editor/refactor/PythonMoveDialog.tsx b/src/editor/refactor/PythonMoveDialog.tsx new file mode 100644 index 0000000000..75fe5503dc --- /dev/null +++ b/src/editor/refactor/PythonMoveDialog.tsx @@ -0,0 +1,135 @@ +/** PyCharm's Move dialog for the top-level elements of a Python module (`pythonMove.ts`). */ +import { useEffect, useRef, useState } from "react"; +import { Checkbox, Dialog, Icon, Input, Spinner, T } from "@/ui"; +import { useTx } from "@/platform/i18n"; +import { moveProblem, movePythonSymbols, usePythonMoveDialog, type PythonMoveRequest } from "./pythonMove"; +// The same layout as Extract Interface: fields above a checkbox table. +import styles from "./ExtractInterfaceDialog.module.css"; + +const ICONS = { function: "function", class: "class", variable: "variable" } as const; + +export function PythonMoveDialog() { + const request = usePythonMoveDialog((s) => s.request); + if (!request) return null; + return ; +} + +function PythonMoveDialogInner({ request }: { request: PythonMoveRequest }) { + const tx = useTx(); + const { symbols, file } = request; + const [destination, setDestination] = useState(file); + const [checked, setChecked] = useState>( + () => new Set(symbols.filter((s) => s.selected).map((s) => s.name)), + ); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const target = destination.trim(); + const problem = moveProblem(file, target, checked.size); + const ready = !busy && !problem; + const allChecked = checked.size === symbols.length; + + // Closing the dialog cancels a refactoring still being checked: it applies nothing. + const running = useRef(null); + useEffect(() => () => running.current?.abort(), []); + const close = () => { + running.current?.abort(); + usePythonMoveDialog.setState({ request: null }); + request.view.focus(); + }; + const toggle = (name: string, on: boolean) => + setChecked((all) => { + const next = new Set(all); + if (on) next.add(name); + else next.delete(name); + return next; + }); + const submit = async (preview: boolean) => { + if (!ready) return; + const run = (running.current = new AbortController()); + setBusy(true); + setError(null); + const names = symbols.map((s) => s.name).filter((name) => checked.has(name)); + const outcome = await movePythonSymbols(request, names, target, preview, run.signal); + if (usePythonMoveDialog.getState().request !== request) return; + setBusy(false); + if (outcome.status === "done") close(); + else if (outcome.error) setError(outcome.error); + }; + + return ( + void submit(true) }, + { label: "Refactor", role: "default", disabled: !ready, onClick: () => void submit(false) }, + { label: "Cancel", role: "cancel" }, + ]} + footerStart={ + busy ? ( + + + Checking for conflicts… + + ) : undefined + } + > +
+ + +
+ Elements to Move +
+
+
+
+ 0 && !allChecked} + onChange={(on) => setChecked(on ? new Set(symbols.map((s) => s.name)) : new Set())} + aria-label="Select All" + label={Name} + /> +
+
+ {symbols.map((s) => ( +
+
+ toggle(s.name, on)} + label={ + + + {s.name} + + } + /> +
+
+ ))} +
+ {(error ?? (target !== file && problem)) && ( + + {tx(error ?? problem!)} + + )} +
+
+ ); +} diff --git a/src/editor/refactor/index.ts b/src/editor/refactor/index.ts index ed025fa51b..2b8e26d623 100644 --- a/src/editor/refactor/index.ts +++ b/src/editor/refactor/index.ts @@ -6,3 +6,4 @@ export { ChangeSignatureDialog } from "./ChangeSignatureDialog"; export { JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand } from "./javaMove"; export { HierarchyDialog } from "./HierarchyDialog"; export { ExtractInterfaceDialog } from "./ExtractInterfaceDialog"; +export { PythonMoveDialog } from "./PythonMoveDialog"; diff --git a/src/editor/refactor/pythonMove.test.ts b/src/editor/refactor/pythonMove.test.ts new file mode 100644 index 0000000000..151dcdca35 --- /dev/null +++ b/src/editor/refactor/pythonMove.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from "vitest"; +import { moveProblem } from "./pythonMove"; + +describe("move Python symbols", () => { + it("tells what keeps the move from being submitted", () => { + expect(moveProblem("a.py", "b.py", 0)).toBe("Select the elements to move"); + expect(moveProblem("a.py", "pkg/b", 1)).toBe("The destination must be a .py file"); + expect(moveProblem("a.py", "a.py", 1)).toBe("The destination is the file itself"); + expect(moveProblem("a.py", "pkg/b.py", 2)).toBeNull(); + }); +}); diff --git a/src/editor/refactor/pythonMove.ts b/src/editor/refactor/pythonMove.ts new file mode 100644 index 0000000000..5f04958c7d --- /dev/null +++ b/src/editor/refactor/pythonMove.ts @@ -0,0 +1,142 @@ +/** + * Move… (F6) for the top-level functions, classes and variables of a Python module: the dialog + * (`PythonMoveDialog.tsx`) picks them and the destination file, the backend computes the edit. + */ +import type { Text } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { create } from "zustand"; +import type { ServerRefactored } from "@/bindings"; +import { whenSynced } from "@/editor/api"; +import { docOf, isUnavailable, lspRequest } from "@/editor/lsp/lsp"; +import { offsetToPos } from "@/editor/lsp/positions"; +import { showHint } from "@/editor/lsp/hint"; +import { openPopup } from "@/editor/lsp/popupStore"; +import { summarizeWorkspaceEdit } from "@/editor/lsp/workspaceEdit"; +import { executeAction } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import { IpcError, commands, isCancelled, unavailableText } from "@/platform/ipc"; +import { projectRelative } from "@/platform/projectRoots"; +import { cannotPerform } from "./catalog"; +import { applyEdit, cancellable, confirmProblems } from "./signature"; + +export interface MovableSymbol { + name: string; + kind: "function" | "class" | "variable"; + /** The caret is in it. */ + selected: boolean; +} + +export interface PythonMoveRequest { + seq: number; + view: EditorView; + doc: number; + /** The document the symbols were read from. */ + text: Text; + /** The source file, relative to the project. */ + file: string; + symbols: MovableSymbol[]; +} + +export const usePythonMoveDialog = create<{ request: PythonMoveRequest | null }>(() => ({ request: null })); +let seq = 0; +let running: AbortController | null = null; + +function errorText(e: unknown): string { + if (isUnavailable(e)) return unavailableText(e, "No language server available"); + return e instanceof Error ? e.message : String(e); +} + +/** Why the move can't be submitted yet, or null. */ +export function moveProblem(source: string, destination: string, count: number): string | null { + if (!count) return "Select the elements to move"; + if (!destination.endsWith(".py")) return "The destination must be a .py file"; + if (destination === source) return "The destination is the file itself"; + return null; +} + +/** Move…: reads the module's movable names, then opens the dialog. */ +export async function startPythonMove(view: EditorView): Promise { + const ctx = docOf(view); + if (!ctx) return; + running?.abort(); + const run = (running = new AbortController()); + await whenSynced(view); + const state = view.state; + const args = JSON.stringify({ line: offsetToPos(state.doc, state.selection.main.head).line }); + try { + const found = await cancellable(run.signal, (id, wanted) => + lspRequest(() => commands.lspJavaMoveDestinations(id, ctx.doc, "python", args), wanted), + ); + if (run.signal.aborted || view.state.doc !== state.doc) return; + usePythonMoveDialog.setState({ + request: { + seq: ++seq, + view, + doc: ctx.doc, + text: state.doc, + file: projectRelative(ctx.path) ?? ctx.path, + symbols: found.map((json) => JSON.parse(json) as MovableSymbol), + }, + }); + } catch (e) { + if (isCancelled(e) || run.signal.aborted) return; + if (e instanceof IpcError && e.data?.type === "tool" && e.data.missing) { + void executeAction("tools.promptInstall", { name: e.data.tool, refactoring: "Move" }); + } + showHint(view, cannotPerform(errorText(e))); + } finally { + if (running === run) running = null; + } +} + +export type MoveOutcome = { status: "done" } | { status: "stay"; error?: string }; + +/** Checks the move, confirms its problems and applies the edit, or previews it with `preview`. */ +export async function movePythonSymbols( + request: PythonMoveRequest, + names: readonly string[], + destination: string, + preview: boolean, + /** The dialog closed: nothing is confirmed, previewed or applied any more. */ + signal?: AbortSignal, +): Promise { + const { view } = request; + if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" }; + const args = JSON.stringify({ names, file: destination }); + let confirmation: string | null = null; + let moved: ServerRefactored; + try { + for (;;) { + // oxlint-disable-next-line no-await-in-loop -- sync before each confirmation round + await whenSynced(view); + const token: string | null = confirmation; + // oxlint-disable-next-line no-await-in-loop -- request carries the previous confirmation + moved = await cancellable(signal, (id, wanted) => + lspRequest(() => commands.lspJavaMove(id, request.doc, "python", args, token), wanted), + ); + if (signal?.aborted) return { status: "stay" }; + if (!moved.confirmation) break; + // oxlint-disable-next-line no-await-in-loop -- the confirmation gates the next request + if (!(await confirmProblems(moved.problems.map((p) => p.message))) || signal?.aborted) return { status: "stay" }; + confirmation = moved.confirmation; + } + } catch (e) { + if (isCancelled(e) || signal?.aborted) return { status: "stay" }; + return { status: "stay", error: errorText(e) }; + } + const edit = moved.edit; + const summary = edit && summarizeWorkspaceEdit(edit); + if (!edit || !summary?.files) return { status: "stay", error: "Nothing to change" }; + if (preview) { + openPopup({ + kind: "preview", + title: tx`Move`, + summary, + confirmLabel: "Do Refactor", + onConfirm: () => void applyEdit(view, edit), + }); + } else { + await applyEdit(view, edit, signal); + } + return { status: "done" }; +} diff --git a/src/editor/refactor/refactorThis.ts b/src/editor/refactor/refactorThis.ts index 1413e21d6f..cf6f994e51 100644 --- a/src/editor/refactor/refactorThis.ts +++ b/src/editor/refactor/refactorThis.ts @@ -22,6 +22,7 @@ import { foreground } from "@/editor/lsp/foreground"; import { caretAnchor, openPopup, type ListPopupItem } from "@/editor/lsp/popupStore"; import { applyCodeAction } from "@/editor/lsp/intentions"; import { planLocalRename } from "@/editor/lsp/syntaxFallback"; +import { startPythonMove } from "./pythonMove"; import { HIERARCHY_REFACTORINGS, REFACTORINGS, @@ -199,6 +200,10 @@ export async function runRefactoring(view: EditorView, id: RefactoringId): Promi await startChangeSignature(view); return; } + if (id === "move" && ctx.language === "python") { + await startPythonMove(view); + return; + } if (id === "extractInterface" && EXTRACT_INTERFACE_LANGUAGES.has(ctx.language)) { await startExtractInterface(view); return; diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index c89ba8a947..4481397e97 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -6221,6 +6221,12 @@ "Last turn": "Último turno", "Compact Conversation": "Compactar conversación", "Premium requests": "Solicitudes premium", + "From file:": "Desde el archivo:", + "To file:": "Al archivo:", + "Elements to Move": "Elementos para mover", + "Select the elements to move": "Seleccione los elementos que desea mover", + "The destination must be a .py file": "El destino debe ser un archivo .py", + "The destination is the file itself": "El destino es el propio archivo", "Build server config generated": "Configuración del servidor de compilación generada", "Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "La asistencia de código para {container} lee su última compilación: Ejecutar, o compilar en Xcode, la actualiza.", "Could not generate a build server config": "No se pudo generar la configuración del servidor de compilación", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index a3c3263542..a966b2d056 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -5912,6 +5912,12 @@ "Last turn": "Dernier tour", "Compact Conversation": "Compacter la conversation", "Premium requests": "Requêtes premium", + "From file:": "Depuis le fichier :", + "To file:": "Vers le fichier :", + "Elements to Move": "Éléments à déplacer", + "Select the elements to move": "Sélectionnez les éléments à déplacer", + "The destination must be a .py file": "La destination doit être un fichier .py", + "The destination is the file itself": "La destination est le fichier lui-même", "Build server config generated": "Configuration du serveur de build générée", "Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "L’assistance au code pour {container} lit sa dernière compilation : Exécuter, ou une compilation dans Xcode, la met à jour.", "Could not generate a build server config": "Impossible de générer la configuration du serveur de build", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 449d93596f..94a6446ded 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -6330,6 +6330,12 @@ "Last turn": "마지막 턴", "Compact Conversation": "대화 압축", "Premium requests": "프리미엄 요청", + "From file:": "원본 파일:", + "To file:": "대상 파일:", + "Elements to Move": "이동할 요소", + "Select the elements to move": "이동할 요소를 선택하세요", + "The destination must be a .py file": "대상은 .py 파일이어야 합니다", + "The destination is the file itself": "대상이 원본 파일과 같습니다", "Build server config generated": "빌드 서버 설정을 생성했습니다", "Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "{container}의 코드 인사이트는 마지막 빌드를 읽습니다. 실행하거나 Xcode에서 빌드하면 갱신됩니다.", "Could not generate a build server config": "빌드 서버 설정을 생성할 수 없습니다", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index b5667fbca3..854bc74741 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -6029,6 +6029,12 @@ "Last turn": "Ostatnia tura", "Compact Conversation": "Skompresuj rozmowę", "Premium requests": "Żądania premium", + "From file:": "Z pliku:", + "To file:": "Do pliku:", + "Elements to Move": "Elementy do przeniesienia", + "Select the elements to move": "Wybierz elementy do przeniesienia", + "The destination must be a .py file": "Celem musi być plik .py", + "The destination is the file itself": "Celem jest ten sam plik", "Build server config generated": "Wygenerowano konfigurację serwera budowania", "Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "Analiza kodu dla {container} korzysta z ostatniej kompilacji: uruchomienie lub kompilacja w Xcode ją odświeża.", "Could not generate a build server config": "Nie można wygenerować konfiguracji serwera budowania", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 5707192ba4..7da7f544cb 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -6044,6 +6044,12 @@ "Last turn": "Último turno", "Compact Conversation": "Compactar conversa", "Premium requests": "Solicitações premium", + "From file:": "Do arquivo:", + "To file:": "Para o arquivo:", + "Elements to Move": "Elementos a mover", + "Select the elements to move": "Selecione os elementos a mover", + "The destination must be a .py file": "O destino deve ser um arquivo .py", + "The destination is the file itself": "O destino é o próprio arquivo", "Build server config generated": "Configuração do servidor de build gerada", "Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "A inteligência de código para {container} lê a última compilação: Executar, ou compilar no Xcode, a atualiza.", "Could not generate a build server config": "Não foi possível gerar a configuração do servidor de build", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index 3591fbf75a..142488f749 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -10266,6 +10266,12 @@ "Last turn": "Последний ход", "Compact Conversation": "Сжать диалог", "Premium requests": "Премиум-запросы", + "From file:": "Из файла:", + "To file:": "В файл:", + "Elements to Move": "Перемещаемые элементы", + "Select the elements to move": "Выберите элементы для перемещения", + "The destination must be a .py file": "Целью должен быть файл .py", + "The destination is the file itself": "Цель совпадает с исходным файлом", "Build server config generated": "Конфигурация сервера сборки создана", "Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "Поддержка кода в {container} использует последнюю сборку: запуск или сборка в Xcode обновляют её.", "Could not generate a build server config": "Не удалось создать конфигурацию сервера сборки", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index eb3c6e0447..f531b5dfe6 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -8888,6 +8888,12 @@ "Last turn": "Son tur", "Compact Conversation": "Konuşmayı Sıkıştır", "Premium requests": "Premium istekler", + "From file:": "Kaynak dosya:", + "To file:": "Hedef dosya:", + "Elements to Move": "Taşınacak öğeler", + "Select the elements to move": "Taşınacak öğeleri seçin", + "The destination must be a .py file": "Hedef bir .py dosyası olmalıdır", + "The destination is the file itself": "Hedef, dosyanın kendisi", "Build server config generated": "Derleme sunucusu yapılandırması oluşturuldu", "Code insight for {container} reads its last build: Run, or a build in Xcode, refreshes it.": "{container} için kod zekâsı son derlemeyi okur: Çalıştırmak ya da Xcode'da derlemek onu yeniler.", "Could not generate a build server config": "Derleme sunucusu yapılandırması oluşturulamadı", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 1b7d8f7e2a..68e2faabd0 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9621,6 +9621,12 @@ "Last turn": "上一輪", "Compact Conversation": "壓縮對話", "Premium requests": "進階請求", + "From file:": "來源檔案:", + "To file:": "目標檔案:", + "Elements to Move": "要移動的元素", + "Select the elements to move": "請選取要移動的元素", + "The destination must be a .py file": "目標必須是 .py 檔案", + "The destination is the file itself": "目標就是檔案本身", "Find in Documentation": "在文件中查詢", "Previous Match": "上一個相符項目", "Next Match": "下一個相符項目", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 40c2d7a04a..ba8598a181 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -11345,6 +11345,12 @@ "Cannot list the manage.py commands": "无法列出 manage.py 命令", "Install django-types into this project's virtual environment to complete Django model fields and managers": "将 django-types 安装到此项目的虚拟环境,以补全 Django 模型字段和管理器", "No local changes in {path}": "{path} 中没有本地更改", + "From file:": "源文件:", + "To file:": "目标文件:", + "Elements to Move": "要移动的元素", + "Select the elements to move": "请选择要移动的元素", + "The destination must be a .py file": "目标必须是 .py 文件", + "The destination is the file itself": "目标就是文件本身", "Settings Sync": "设置同步", "The repository already holds settings. What should happen to the settings on this computer?": "仓库里已经有设置。这台电脑上的设置要怎么处理?", "Use the Repository's": "使用仓库的设置",