Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compare parsed HTML #364

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions src/mdformat/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from collections.abc import Iterable, Mapping
from contextlib import nullcontext
import filecmp
from html.parser import HTMLParser
import os
from pathlib import Path
import re
Expand Down Expand Up @@ -107,6 +108,77 @@ def is_md_equal(
return html_texts["md1"] == html_texts["md2"]


# TODO: remove empty p tags, remove formatted code
def normalize_html_ast(ast: list[dict]) -> list[dict]:
pass


class HTML2AST(HTMLParser):
"""Parse HTML to a list/dict structure that can be used in comparisons.

HTML2AST.parse() is the only method considered public.
"""

def __init__(self):
super().__init__(convert_charrefs=True)
self.tree: list[dict] = []
self.current: dict | None = None

def parse(self, text: str, strip_classes: Iterable[str] = ()) -> list[dict]:
self.feed(text)
self.close()
self.strip_classes(self.tree, set(strip_classes))
return self.tree

# TODO: remove?
def strip_classes(self, tree: list[dict], classes: set[str]) -> list[dict]:
"""Strip content from tags with certain classes."""
items = []
for item in tree:
if set(item["attrs"].get("class", "").split()).intersection(classes):
items.append({"tag": item["tag"], "attrs": item["attrs"]})
continue
items.append(item)
item["children"] = self.strip_classes(item.get("children", []), classes)
if not item["children"]:
item.pop("children")

return items

def handle_starttag(self, tag: str, attrs: list[tuple[str, str]]) -> None:
tag_item = {"tag": tag, "attrs": dict(attrs), "parent": self.current}
if self.current is None:
self.tree.append(tag_item)
else:
children = self.current.setdefault("children", [])
children.append(tag_item)
self.current = tag_item

def handle_endtag(self, tag: str) -> None:
# walk up the tree to the tag's parent
while self.current is not None:
if self.current["tag"] == tag:
self.current = self.current.pop("parent")
break
self.current = self.current.pop("parent")

def handle_data(self, data: str) -> None:
# ignore data outside tags
if self.current is None:
return
assert (
"data" not in self.current
), "Oh no, the tag had data in more than one place."

if self.current["tag"] == "p":
# Strip insignificant paragraph leading/trailing whitespace
data = data.strip()
# Reduce all collapsable whitespace to a single space
data = re.sub(r"[\n\t ]+", " ", data)

self.current["data"] = data


def atomic_write(path: Path, text: str, newline: str) -> None:
"""A function for atomic writes to a file.

Expand Down
99 changes: 99 additions & 0 deletions tests/test_html2ast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
from mdformat._util import HTML2AST


def test_html2ast():
data = HTML2AST().parse('<div><p class="x">a<s>j</s></p></div><a>b</a>')
assert data == [
{
"tag": "div",
"attrs": {},
"children": [
{
"tag": "p",
"attrs": {"class": "x"},
"data": ["a"],
"children": [{"tag": "s", "attrs": {}, "data": ["j"]}],
}
],
},
{"tag": "a", "attrs": {}, "data": ["b"]},
]


def test_html2ast_multiline():
data = HTML2AST().parse("<div>a\nb \nc \n\n</div>")
assert data == [{"tag": "div", "attrs": {}, "data": ["a", "b", "c"]}]


def test_html2ast_nested():
data = HTML2AST().parse("<a d=1>b<a d=2>c<a d=3>e</a></a></a>")
assert data == [
{
"tag": "a",
"attrs": {"d": "1"},
"data": ["b"],
"children": [
{
"tag": "a",
"attrs": {"d": "2"},
"data": ["c"],
"children": [{"tag": "a", "attrs": {"d": "3"}, "data": ["e"]}],
}
],
}
]


def test_html2ast_strip():
data = HTML2AST().parse('<div><p class="x y">a<s>j</s></p></div><a>b</a>', {"x"})
assert data == [
{
"tag": "div",
"attrs": {},
"children": [{"tag": "p", "attrs": {"class": "x y"}}],
},
{"tag": "a", "attrs": {}, "data": ["b"]},
]


def test_html2ast_multiple_content():
data = HTML2AST().parse(
"""'
<div>
hello

<p class="x y">a</p>
<p class="a b"></p>

another hello in the same div
this one is multiline
</div>
""",
)
assert data == [
{
"tag": "div",
"attrs": {},
"children": [{"tag": "p", "attrs": {"class": "x y"}}],
},
{"tag": "a", "attrs": {}, "data": ["b"]},
]


def test_html2ast_multiple_contentssss():
data = HTML2AST().parse(
"""'
<p></p>
<p>a</p>
<p>
</p>
""",
)
assert data == [
{
"tag": "div",
"attrs": {},
"children": [{"tag": "p", "attrs": {"class": "x y"}}],
},
{"tag": "a", "attrs": {}, "data": ["b"]},
]