aides-spec/aides_spec/replacers/base.py

41 lines
1.5 KiB
Python
Raw Normal View History

2024-12-01 18:49:14 +00:00
class BaseReplacer:
def __init__(self, content, tree):
self.content = content
self.tree = tree
self.replaces = []
def _node_text(self, node):
"""Helper function to get the text of a node."""
2024-12-01 19:24:12 +00:00
return self.content[node.start_byte : node.end_byte].decode("utf-8")
2024-12-01 18:49:14 +00:00
def _apply_replacements(self):
"""Apply the replacements to the content and edit the tree."""
new_content = bytearray(self.content)
for replace_info in sorted(
self.replaces,
key=lambda x: (x["node"].start_byte, x["node"].end_byte),
reverse=True,
):
start, end = (
replace_info["node"].start_byte,
replace_info["node"].end_byte,
)
replacement = replace_info["content"].encode("utf-8")
new_content[start:end] = replacement
self.tree.edit(
start_byte=start,
old_end_byte=end,
new_end_byte=start + len(replacement),
start_point=replace_info["node"].start_point,
old_end_point=replace_info["node"].end_point,
new_end_point=(
replace_info["node"].start_point[0],
replace_info["node"].start_point[1] + len(replacement),
),
)
return new_content
def process(self):
raise NotImplementedError("Subclasses should implement this method.")