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.""" return self.content[node.start_byte : node.end_byte].decode("utf-8") 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.")