Rewrite from old_module import <symbols> to new_module.
Returns (new_text, rewrites). When no matching import exists the
original text and an empty list are returned unchanged.
Source code in packages/axm-anvil/src/axm_anvil/core/callers.py
| Python |
|---|
| def rewrite_caller_text(
text: str,
old_module: str,
new_module: str,
symbols: Sequence[str],
) -> tuple[str, list[CallerRewrite]]:
"""Rewrite ``from old_module import <symbols>`` to ``new_module``.
Returns ``(new_text, rewrites)``. When no matching import exists the
original text and an empty list are returned unchanged.
"""
moved = set(symbols)
tree = cst.parse_module(text)
collector = _CollectOldImport(old_module, moved)
tree.visit(collector)
if not collector.matched_names:
return text, []
located = _find_import_line(text, old_module)
line_no = located[0] if located else 1
old_line = located[1].strip() if located else ""
new_tree = tree.visit(_RewriteOldImport(old_module, moved))
context = _add_new_imports(symbols, collector.matched_names, new_module)
final_tree = AddImportsVisitor(context).transform_module(new_tree)
new_stmt = _format_new_import_stmt(symbols, collector.matched_names, new_module)
rewrite = CallerRewrite(file="", line=line_no, old=old_line, new=new_stmt)
return final_tree.code, [rewrite]
|