Skip to content

Commit

Permalink
TagNode.merge_text_nodes: Also drops empty text nodes
Browse files Browse the repository at this point in the history
Optimizations are applied as well.
  • Loading branch information
funkyfuture committed Jul 26, 2024
1 parent 1cdda90 commit 0f13e80
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
15 changes: 13 additions & 2 deletions _delb/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2258,9 +2258,20 @@ def location_path(self) -> str:
def merge_text_nodes(self):
"""
Merges all consecutive text nodes in the subtree into one.
Text nodes without content are dropped.
"""
for node in self.iterate_descendants(is_text_node):
node._merge_appended_text_nodes()
with _wrapper_cache:
empty_nodes: list[TextNode] = []

for node in self.iterate_descendants():
if not isinstance(node, TextNode):
continue
node._merge_appended_text_nodes()
if not node.content:
empty_nodes.append(node)

for node in empty_nodes:
node.detach()

@property
def namespace(self) -> Optional[str]:
Expand Down
10 changes: 10 additions & 0 deletions tests/test_tag_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,16 @@ def test_make_node_in_context_with_namespace():
assert node._etree_obj.tag == "{https://name.space}foo"


@pytest.mark.parametrize(
("child_nodes", "expected_count"),
(([""], 0), ([" "], 1), ([" ", " "], 1), (["", "", tag("child"), "", ""], 1)),
)
def test_merge_text_nodes(child_nodes, expected_count):
node = new_tag_node("node", children=child_nodes)
node.merge_text_nodes()
assert len(node) == expected_count


def test_names(sample_document):
root = sample_document.root

Expand Down

0 comments on commit 0f13e80

Please sign in to comment.