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, []
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)
located_lines = _find_import_lines(text, old_module, moved)
rewrites = _build_caller_rewrites(
located_lines, symbols, collector.matched_names, new_module
)
return final_tree.code, rewrites
|