Skip to content

Commit

Permalink
Run "hatch fmt"
Browse files Browse the repository at this point in the history
  • Loading branch information
jackrosenthal committed Sep 29, 2024
1 parent e402a41 commit 297d953
Show file tree
Hide file tree
Showing 10 changed files with 75 additions and 79 deletions.
2 changes: 1 addition & 1 deletion kajiki/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def _kv_pair(pair):
key, sep, value = pair.partition("=")
if not sep:
raise argparse.ArgumentTypeError(
"Expected a KEY=VALUE pair, got {}".format(pair)
f"Expected a KEY=VALUE pair, got {pair}"
)
return key, value

Expand Down
5 changes: 2 additions & 3 deletions kajiki/doctype.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re


class DocumentTypeDeclaration(object):
class DocumentTypeDeclaration:
"""Represents a http://en.wikipedia.org/wiki/Document_Type_Declaration
This is used to lookup DTDs details by its string, DTDs can
Expand Down Expand Up @@ -84,8 +84,7 @@ def matching(cls, dtd_string):
for dtd in cls.by_uri.values():
if dtd.regex.match(dtd_string):
return dtd
else:
return None
return None

REGEX = re.compile(r"<!DOCTYPE[^>]+>") # This matches any DTD.

Expand Down
4 changes: 2 additions & 2 deletions kajiki/ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def generate_python(ir):
yield line.indent(cur_indent)


class Node(object):
class Node:
def __init__(self):
self.filename = "<string>"
self.lineno = 0
Expand Down Expand Up @@ -453,7 +453,7 @@ def optimize(iter_node):
yield last_node


class PyLine(object):
class PyLine:
def __init__(self, filename, lineno, text, indent=0):
self._filename = filename
self._lineno = lineno
Expand Down
1 change: 0 additions & 1 deletion kajiki/loader.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import functools
import importlib.resources
import os
from pathlib import Path
Expand Down
6 changes: 3 additions & 3 deletions kajiki/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@
from .util import flattener, literal


class _obj(object):
class _obj:
def __init__(self, **kw):
for k, v in kw.items():
setattr(self, k, v)


class _Template(object):
class _Template:
"""Base Class for all compiled Kajiki Templates.
All kajiki templates created from a :class:`kajiki.ir.TemplateNode` will
Expand Down Expand Up @@ -339,7 +339,7 @@ def from_ir(ir_node, base_globals=None):
return tpl


class TplFunc(object):
class TplFunc:
"""A template function attached to a _Template.
By default template functions (ie: __main__) depends
Expand Down
8 changes: 4 additions & 4 deletions kajiki/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def TextTemplate(source=None, filename=None, autoescape=False, encoding="utf-8")
filename = "<string>"
assert isinstance(
source, str
), "*source* must be a unicode string, not a {}".format(type(source))
), f"*source* must be a unicode string, not a {type(source)}"
scanner = _Scanner(filename, source)
tree = _Parser(scanner, autoescape).parse()
tree.filename = filename
Expand All @@ -68,7 +68,7 @@ def _diff_pos(last_pos, new_pos):
return new_pos[1]


class _Scanner(object):
class _Scanner:
def __init__(self, filename, source):
self.filename = filename
self.source = source
Expand Down Expand Up @@ -179,7 +179,7 @@ def _get_braced_expr(self):
return self.expr(text)


class _Parser(object):
class _Parser:
def __init__(self, tokenizer, autoescape=False):
self.tokenizer = tokenizer
self.functions = collections.defaultdict(list)
Expand Down Expand Up @@ -327,7 +327,7 @@ def _parse_block(self, token):
return ir.ExprNode(decl)


class _Token(object):
class _Token:
def __init__(self, filename, lineno, text):
self.filename = filename
self.lineno = lineno
Expand Down
6 changes: 3 additions & 3 deletions kajiki/util.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import os.path
from collections import deque
from random import randint
from threading import local
import os.path


def expose(func):
func.exposed = True
return func


class flattener(object):
class flattener:
def __init__(self, iterator):
while type(iterator) == flattener:
iterator = iterator.iterator
Expand Down Expand Up @@ -55,7 +55,7 @@ def literal(text):
return flattener(iter([text]))


class NameGen(object):
class NameGen:
lcl = local()

def __init__(self):
Expand Down
88 changes: 43 additions & 45 deletions kajiki/xml_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def inner(self, node, *args, **kwargs):
return inner


class _Compiler(object):
class _Compiler:
"""Compiles a DOM tree into IR :class:`kajiki.ir.TemplateNode`.
Intermediate Representation is a tree of nodes that represent
Expand Down Expand Up @@ -265,50 +265,48 @@ def _compile_xml(self, node):
yield ir.TextNode(">", guard)
yield ir.ExprNode(content)
yield ir.TextNode("</%s>" % node.tagName, guard)
else:
if node.childNodes:
elif node.childNodes:
yield ir.TextNode(">", guard)
if self.cdata_scripts and node.tagName in HTML_CDATA_TAGS:
# Special behaviour for <script>, <style> tags:
if self.mode == "xml": # Start escaping
yield ir.TextNode("/*<![CDATA[*/")
# Need to unescape the contents of these tags
for child in node.childNodes:
# CDATA for scripts and styles are automatically managed.
if getattr(child, "_cdata", False):
continue
assert isinstance(child, dom.Text)
for x in self._compile_text(child):
if (
child.escaped
): # If user declared CDATA no escaping happened.
x.text = html.unescape(x.text)
yield x
if self.mode == "xml": # Finish escaping
yield ir.TextNode("/*]]>*/")
else:
for cn in node.childNodes:
# Keep CDATA sections around if declared by user
if getattr(cn, "_cdata", False):
yield ir.TextNode(cn.data)
continue
for x in self._compile_node(cn):
yield x
if not (
self.mode.startswith("html")
and node.tagName in HTML_OPTIONAL_END_TAGS
):
yield ir.TextNode("</%s>" % node.tagName, guard)
elif node.tagName in HTML_REQUIRED_END_TAGS:
yield ir.TextNode("></%s>" % node.tagName, guard)
elif self.mode.startswith("html"):
if node.tagName in HTML_OPTIONAL_END_TAGS:
yield ir.TextNode(">", guard)
if self.cdata_scripts and node.tagName in HTML_CDATA_TAGS:
# Special behaviour for <script>, <style> tags:
if self.mode == "xml": # Start escaping
yield ir.TextNode("/*<![CDATA[*/")
# Need to unescape the contents of these tags
for child in node.childNodes:
# CDATA for scripts and styles are automatically managed.
if getattr(child, "_cdata", False):
continue
assert isinstance(child, dom.Text)
for x in self._compile_text(child):
if (
child.escaped
): # If user declared CDATA no escaping happened.
x.text = html.unescape(x.text)
yield x
if self.mode == "xml": # Finish escaping
yield ir.TextNode("/*]]>*/")
else:
for cn in node.childNodes:
# Keep CDATA sections around if declared by user
if getattr(cn, "_cdata", False):
yield ir.TextNode(cn.data)
continue
for x in self._compile_node(cn):
yield x
if not (
self.mode.startswith("html")
and node.tagName in HTML_OPTIONAL_END_TAGS
):
yield ir.TextNode("</%s>" % node.tagName, guard)
elif node.tagName in HTML_REQUIRED_END_TAGS:
yield ir.TextNode("></%s>" % node.tagName, guard)
else:
if self.mode.startswith("html"):
if node.tagName in HTML_OPTIONAL_END_TAGS:
yield ir.TextNode(">", guard)
else:
yield ir.TextNode("></%s>" % node.tagName, guard)
else:
yield ir.TextNode("/>", guard)
yield ir.TextNode("></%s>" % node.tagName, guard)
else:
yield ir.TextNode("/>", guard)

@annotate
def _compile_replace(self, node):
Expand Down Expand Up @@ -498,7 +496,7 @@ def make_text_node(text, guard=None):
return ir.TextNode(text, guard)


class _TextCompiler(object):
class _TextCompiler:
"""Separates expressions such as ${some_var} from the ordinary text
around them in the template source and generates :class:`.ir.ExprNode`
instances and :class:`.ir.TextNode` instances accordingly.
Expand Down Expand Up @@ -783,7 +781,7 @@ def endDTD(self):
pass


class _DomTransformer(object):
class _DomTransformer:
"""Applies standard Kajiki transformations to a parsed document.
Given a document generated by :class:`.Parser` it applies some
Expand Down
8 changes: 4 additions & 4 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import unittest.mock as mock
from unittest import mock

import pytest

Expand All @@ -11,7 +11,7 @@ def __init__(self, monkeypatch):
mocked_render = mock.Mock(return_value="render result")
self.render = mocked_render

class MockedTemplate(object):
class MockedTemplate:
def render(self, *args, **kwargs):
return mocked_render(*args, **kwargs)

Expand All @@ -20,7 +20,7 @@ def render(self, *args, **kwargs):
mocked_import = mock.Mock(return_value=self.template_type)
self.import_ = mocked_import

class MockedLoader(object):
class MockedLoader:
def import_(self, *args, **kwargs):
return mocked_import(*args, **kwargs)

Expand Down Expand Up @@ -108,7 +108,7 @@ def test_output_to_file(tmpdir, main_mocks):
main_mocks.template_type.assert_called_once_with({})
main_mocks.render.assert_called_once_with()

with open(outfile, "r") as f:
with open(outfile) as f:
assert f.read() == "render result"


Expand Down
26 changes: 13 additions & 13 deletions tests/test_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,21 +120,21 @@ def test_script_escaping(self):
must be explicitly be made so.
"""
script = 'if (1 < 2) { doc.write("<p>Offen&nbsp;bach</p>"); }\n'
src = "<script><![CDATA[\n{0}]]></script>".format(script)
src = f"<script><![CDATA[\n{script}]]></script>"
perform(
src, mode="html", expected_output="<script>\n{0}</script>".format(script)
src, mode="html", expected_output=f"<script>\n{script}</script>"
)
perform(
src, "<script>/*<![CDATA[*/\n{0}/*]]>*/</script>".format(script), mode="xml"
src, f"<script>/*<![CDATA[*/\n{script}/*]]>*/</script>", mode="xml"
)

def test_style_escaping(self):
style = "html > body { display: none; }\n"
src = "<style><![CDATA[\n{0}]]></style>".format(style)
src = f"<style><![CDATA[\n{style}]]></style>"
perform(
src, "<style>/*<![CDATA[*/\n{0}/*]]>*/</style>".format(style), mode="xml"
src, f"<style>/*<![CDATA[*/\n{style}/*]]>*/</style>", mode="xml"
)
perform(src, "<style>\n{0}</style>".format(style), mode="html")
perform(src, f"<style>\n{style}</style>", mode="html")

def test_script_variable(self):
"""Interpolate variables inside <script> tags"""
Expand Down Expand Up @@ -171,15 +171,15 @@ def test_CDATA_escaping_mixed(self):

def test_script_commented_CDATA(self):
script = 'if (1 < 2) { doc.write("<p>Offen&nbsp;bach</p>"); }\n'
src = "<script>/*<![CDATA[*/\n{0}/*]]>*/</script>".format(script)
src = f"<script>/*<![CDATA[*/\n{script}/*]]>*/</script>"
perform(
src,
mode="html",
expected_output="<script>/**/\n{0}/**/</script>".format(script),
expected_output=f"<script>/**/\n{script}/**/</script>",
)
perform(
src,
"<script>/*<![CDATA[*//**/\n{0}/**//*]]>*/</script>".format(script),
f"<script>/*<![CDATA[*//**/\n{script}/**//*]]>*/</script>",
mode="xml",
)

Expand Down Expand Up @@ -580,9 +580,9 @@ def test_include(self):
tpl = loader.import_("tpl.html")
rsp = tpl(dict(name="Rick")).render()
assert (
"<html><body><p>This is the body</p>\n"
rsp == "<html><body><p>This is the body</p>\n"
"<p>The included template must also access Kajiki globals and "
"the template context: Rick</p></body></html>" == rsp
"the template context: Rick</p></body></html>"
)

def test_include_html5(self):
Expand Down Expand Up @@ -617,9 +617,9 @@ def _load(self, name, encoding="utf-8", *args, **kwargs):
tpl = loader.import_("tpl.html")
rsp = tpl(dict(name="Rick")).render()
assert (
"<!DOCTYPE html>\n<html><body><p>This is the body</p>\n"
rsp == "<!DOCTYPE html>\n<html><body><p>This is the body</p>\n"
"<p>The included template must also access Kajiki globals and "
"the template context: Rick</p></body></html>" == rsp
"the template context: Rick</p></body></html>"
), rsp


Expand Down

0 comments on commit 297d953

Please sign in to comment.