refactor
refactor copied to clipboard
Remove Node/Remove Line Actions
trafficstars
Recently in a refactor I ended up creating actions to remove a matching node and the entire line it was on, which I think might be useful to others.
Would you accept these in a PR?
from refactor import Action
class RemoveNodeAction(Action):
"""A action that removes matched segments"""
def apply(self, context: Context, source: str) -> str:
"""Refactor a source segment in the given string."""
lines = split_lines(source)
view = slice(self.node.lineno - 1, self.node.end_lineno)
target_lines = lines[view]
lines[view] = [
target_lines[0][: self.node.col_offset] + target_lines[-1][self.node.end_col_offset :]
]
return lines.join()
class RemoveLineAction(Action):
"""A action that removes matched segments"""
def apply(self, context: Context, source: str) -> str:
"""Refactor a source segment in the given string."""
lines = split_lines(source)
view = slice(self.node.lineno - 1, self.node.end_lineno)
del lines[view]
return lines.join()
I was actually thinking about this a while, but never needed it. It definitely fits as a use case, and would love to see it on the core! Shoot the PR 🚀