commit - 4e5d15550233b0836ae2162309030b4ebf00df51
commit + 8ad6b2ac5161889bd6d94a694a32eea11eaa9df6
blob - e8d2d5e05e993e5bacbb12ebe022ecb0ffc2bf5c
blob + 59556928be2a11c98d3de2d177d9c8e5bb1c9a4f
--- yah2g.py
+++ yah2g.py
class _Elem:
def __init__(self, file):
self.elem = None
- self._file = file
+ self.file = file
@contextmanager
def __call__(self):
yield self
self.flush()
+ def flush_bytes(self):
+ if self.elem is None:
+ return b""
+
+ rv = ET.tostring(self.elem) + b"\r\n"
+ self.elem = None
+ return rv
+
def flush(self):
- if self.elem is not None:
- self._file.write(ET.tostring(self.elem) + b"\r\n")
- self.elem = None
+ self.file.write(self.flush_bytes())
-class _AutoFlush:
+class _FlushBeforeWrite:
def __init__(self, elem):
self._elem = elem
+ self._file = elem.file
def cancel(self):
self._elem = None
+
+ def commit(self):
+ if self._elem is not None:
+ self._elem.flush()
+ self._elem = None
+ return self._file
@contextmanager
def __call__(self):
yield self
- if self._elem is not None:
- self._elem.flush()
+ self.commit()
class _RequestHandler(BaseHTTPRequestHandler):
with _Elem(self.wfile)() as pre:
with _Elem(self.wfile)() as ul:
for line in body.splitlines():
- with _AutoFlush(ul)() as auto_flush_ul:
+ with _FlushBeforeWrite(ul)() as flush_before:
if line.startswith("```"):
if pre.elem is None:
pre.elem = ET.Element("pre")
pre.elem.text = ""
else:
- pre.flush()
+ flush_before.commit().write(pre.flush_bytes())
elif pre.elem is not None:
if pre.elem.text:
pre.elem.text += "\r\n"
else:
a.attrib.update(target="_blank", href=target)
a.text = splitted[1] if len(splitted) > 1 else target
- self.wfile.write(ET.tostring(p) + b"\r\n")
+ flush_before.commit().write(ET.tostring(p) + b"\r\n")
elif line.startswith("#") and len(line.split()) > 1:
splitted = line.split(maxsplit=1)
h = ET.Element("h" + str(len(splitted[0])))
h.text = splitted[1]
- self.wfile.write(ET.tostring(h) + b"\r\n")
+ flush_before.commit().write(ET.tostring(h) + b"\r\n")
elif line.startswith("* ") and line[2:].strip():
if ul.elem is None:
ul.elem = ET.Element("ul")
ET.SubElement(ul.elem, "li").text = line[2:].strip()
- auto_flush_ul.cancel()
+ flush_before.cancel()
elif line.startswith("> ") and line[2:].strip():
blockquote = ET.Element("blockquote")
ET.SubElement(blockquote, "p").text = line[2:].strip()
- self.wfile.write(ET.tostring(blockquote) + b"\r\n")
+ flush_before.commit().write(ET.tostring(blockquote) + b"\r\n")
else:
if line:
p = ET.Element("p")
p.text = line
- self.wfile.write(ET.tostring(p) + b"\r\n")
+ flush_before.commit().write(ET.tostring(p) + b"\r\n")
self.wfile.write(self.server.footer_file_bytes)