Skip to content

Commit

Permalink
mypy lint
Browse files Browse the repository at this point in the history
  • Loading branch information
OleJoik committed Jun 12, 2024
1 parent a5f799e commit 241e7ca
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 34 deletions.
28 changes: 14 additions & 14 deletions htpy/html2htpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __init__(
self.parent = parent
self.children: list[Self | str] = []

def serialize(self, shorthand_id_class: bool = False):
def serialize(self, shorthand_id_class: bool = False) -> str:
_type = self.type
if "-" in _type:
_type = _type.replace("-", "_")
Expand Down Expand Up @@ -131,12 +131,12 @@ def format(self, s: str) -> str:


class HTPYParser(HTMLParser):
def __init__(self):
def __init__(self) -> None:
self._collected: list[Tag | str] = []
self._current: Tag | None = None
super().__init__()

def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]):
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
t = Tag(tag, attrs, parent=self._current)

if not self._current:
Expand All @@ -146,15 +146,15 @@ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]):

self._current = t

def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]):
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
t = Tag(tag, attrs, parent=self._current)

if not self._current:
self._collected.append(t)
else:
self._current.children.append(t)

def handle_endtag(self, tag: str):
def handle_endtag(self, tag: str) -> None:
if not self._current:
raise Exception(f"Error parsing html: Closing tag {tag} when not inside any other tag")

Expand All @@ -166,7 +166,7 @@ def handle_endtag(self, tag: str):

self._current = self._current.parent

def handle_data(self, data: str):
def handle_data(self, data: str) -> None:
if not data.isspace():
stringified_data = _convert_data_to_string(data)

Expand All @@ -177,7 +177,7 @@ def handle_data(self, data: str):

def serialize_python(
self, shorthand_id_class: bool = False, formatter: Formatter | None = None
):
) -> str:
o = ""

if len(self._collected) == 1:
Expand All @@ -199,14 +199,14 @@ def html2htpy(
html: str,
shorthand_id_class: bool = True,
formatter: Formatter | None = None,
):
) -> str:
parser = HTPYParser()
parser.feed(html)

return parser.serialize_python(shorthand_id_class, formatter)


def _convert_data_to_string(data: str):
def _convert_data_to_string(data: str) -> str:
_data = str(data)

is_multiline = "\n" in _data
Expand All @@ -228,7 +228,7 @@ def _convert_data_to_string(data: str):
r"(\{\{\s*[\w\.]+\s*\}\}|(?<![\{]){(?![\{])|(?<![\}])}(?![\}]))"
)

def replacer(match: re.Match[str]):
def replacer(match: re.Match[str]) -> str:
captured = match.group(1)

if captured.startswith("{{"):
Expand All @@ -253,7 +253,7 @@ def replacer(match: re.Match[str]):
return _data


def _serialize(el: Tag | str, shorthand_id_class: bool):
def _serialize(el: Tag | str, shorthand_id_class: bool) -> str:
if isinstance(el, Tag):
return el.serialize(shorthand_id_class=shorthand_id_class)
else:
Expand Down Expand Up @@ -292,11 +292,11 @@ def _get_formatter(format: Literal["auto", "ruff", "black", "none"]) -> Formatte
return None


def _is_command_available(command: str):
def _is_command_available(command: str) -> bool:
return shutil.which(command) is not None


def main():
def main() -> None:
parser = argparse.ArgumentParser(prog="html2htpy")

parser.add_argument(
Expand Down Expand Up @@ -347,5 +347,5 @@ def main():
print(html2htpy(input, shorthand, formatter))


def _printerr(value: str):
def _printerr(value: str) -> None:
print(value, file=sys.stderr)
40 changes: 20 additions & 20 deletions tests/test_html2htpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from htpy.html2htpy import BlackFormatter, RuffFormatter, html2htpy


def test_convert_default_shorthand_id_and_class():
def test_convert_default_shorthand_id_and_class() -> None:
input = """
<div id="div-id" class="some-class other-class">
<p>This is a paragraph.</p>
Expand All @@ -18,7 +18,7 @@ def test_convert_default_shorthand_id_and_class():
assert actual == expected


def test_convert_explicit_id_class_syntas():
def test_convert_explicit_id_class_syntas() -> None:
input = """
<div id="div-id" class="some-class other-class">
<p>This is a paragraph.</p>
Expand All @@ -39,7 +39,7 @@ def test_convert_explicit_id_class_syntas():
"""


def test_convert_nested_element_without_formatting():
def test_convert_nested_element_without_formatting() -> None:
actual = html2htpy(nested_html, formatter=None)

expected = (
Expand All @@ -52,7 +52,7 @@ def test_convert_nested_element_without_formatting():
assert actual == expected


def test_convert_nested_element_ruff_formatting():
def test_convert_nested_element_ruff_formatting() -> None:
actual = html2htpy(nested_html, formatter=RuffFormatter())
assert actual == textwrap.dedent(
"""\
Expand All @@ -64,7 +64,7 @@ def test_convert_nested_element_ruff_formatting():
)


def test_convert_nested_element_black_formatting():
def test_convert_nested_element_black_formatting() -> None:
actual = html2htpy(nested_html, formatter=BlackFormatter())
assert actual == textwrap.dedent(
"""\
Expand All @@ -76,7 +76,7 @@ def test_convert_nested_element_black_formatting():
)


def test_convert_self_closing_tags():
def test_convert_self_closing_tags() -> None:
input = """
<img src="image.jpg" alt="An image" />
<br />
Expand All @@ -88,13 +88,13 @@ def test_convert_self_closing_tags():
assert actual == '[img(src="image.jpg",alt="An image"),br,input(type="text")]'


def test_convert_attribute_with_special_characters():
def test_convert_attribute_with_special_characters() -> None:
input = """<img src="path/to/image.jpg" alt="A <test> & 'image'" />"""
actual = html2htpy(input)
assert actual == """img(src="path/to/image.jpg",alt="A <test> & 'image'")"""


def test_convert_ignores_comments():
def test_convert_ignores_comments() -> None:
input = """
<!-- This is a comment -->
<div>Content <!-- Another comment --> inside</div>
Expand All @@ -103,7 +103,7 @@ def test_convert_ignores_comments():
assert actual == 'div["Content "," inside"]'


def test_convert_special_characters():
def test_convert_special_characters() -> None:
input = """
<p>Special characters: &amp; &lt; &gt; &quot; &apos; &copy;</p>
"""
Expand All @@ -112,7 +112,7 @@ def test_convert_special_characters():
assert actual == 'p["Special characters: & < > \\" \' ©"]'


def test_convert_f_string_escaping():
def test_convert_f_string_escaping() -> None:
input = """
<p>{{ variable }} is "a" { paragraph }.</p>
"""
Expand All @@ -123,7 +123,7 @@ def test_convert_f_string_escaping():
assert actual == expected


def test_convert_f_string_escaping_complex():
def test_convert_f_string_escaping_complex() -> None:
input = """
<body>
<h1>{{ heading }}</h1>
Expand Down Expand Up @@ -162,7 +162,7 @@ def test_convert_f_string_escaping_complex():
assert actual == expected


def test_convert_script_tag():
def test_convert_script_tag() -> None:
input = """
<script type="text/javascript">alert('This is a script');</script>
"""
Expand All @@ -171,15 +171,15 @@ def test_convert_script_tag():
assert actual == """script(type="text/javascript")["alert('This is a script');"]"""


def test_convert_style_tag():
def test_convert_style_tag() -> None:
input = """
<style>body { background-color: #fff; }</style>
"""
actual = html2htpy(input)
assert actual == """style["body { background-color: #fff; }"]"""


def test_convert_html_doctype():
def test_convert_html_doctype() -> None:
input = """
<!DOCTYPE html>
<html>
Expand All @@ -199,7 +199,7 @@ def test_convert_html_doctype():
assert actual == expected


def test_convert_empty_elements():
def test_convert_empty_elements() -> None:
input = """
<div></div>
<p></p>
Expand All @@ -210,7 +210,7 @@ def test_convert_empty_elements():
assert actual == "[div,p,span]"


def test_convert_custom_tag():
def test_convert_custom_tag() -> None:
input = """
<custom-element attribute="value">Custom content</custom-element>
"""
Expand All @@ -219,7 +219,7 @@ def test_convert_custom_tag():
assert actual == """custom_element(attribute="value")["Custom content"]"""


def test_convert_malformed_html():
def test_convert_malformed_html() -> None:
input = """
<div>
<p>Paragraph without closing tag
Expand All @@ -233,7 +233,7 @@ def test_convert_malformed_html():
assert "Closing tag p does not match the currently open tag (div)" in str(e.value)


def test_convert_attributes_without_values():
def test_convert_attributes_without_values() -> None:
input = """
<input type="checkbox" checked />
<option selected>Option</option>
Expand All @@ -242,7 +242,7 @@ def test_convert_attributes_without_values():
assert actual == """[input(type="checkbox",checked=True),option(selected=True)["Option"]]"""


def test_convert_complex_section():
def test_convert_complex_section() -> None:
input = """
<section class="hero is-fullheight is-link">
<div class="hero-body">
Expand Down Expand Up @@ -271,7 +271,7 @@ def test_convert_complex_section():
assert actual == expected


def test_convert_complex_svg():
def test_convert_complex_svg() -> None:
path_d: str = (
"m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2"
".652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1"
Expand Down

0 comments on commit 241e7ca

Please sign in to comment.