3 import lxml.html as html
7 def __init__(self, name: str):
12 def append(self, line: str):
13 self._buffer.append(line)
16 def buffer(self) -> str:
18 buf = "\n".join(self._buffer)
19 self._html = markdown.markdown(buf)
24 def name(self) -> str:
33 def property(self) -> dict:
36 def __getitem__(self, key: str) -> dict:
37 return self._items[key]
39 def __setitem__(self, key: str, value: str):
40 self._items[key] = value
42 def __str__(self) -> str:
43 d = dict({'property': self._props}, **self._items)
47 def __init__(self, clazz, rules = {}):
48 self._item_class = clazz
49 self._doc = Document()
52 re.compile(v): getattr(self, k) for k, v in rules.items()
55 def parse(self, lines):
57 self._parse_line(line)
64 self._doc[self._item.name] = self._item.buffer
66 def on_property(self, buf: tuple):
68 self._doc.property[key] = value
70 def on_section_title(self, value: tuple):
73 self._item = self._item_class(title)
75 def on_content(self, value: tuple):
78 self._item.append(content)
80 def _parse_line(self, line: str):
81 def apply(k: str, v: str):
83 return v(m.groups()) if m else None
85 for k, v in self.rules.items():
89 'on_section_title': r'%\s*(.+?)\s*%*\n?',
90 'on_property': r'=\((.+?)\)\s*(.+?)\s*=*\n?',
91 'on_content': r'([^%=].*)\n?',
94 def convert_sections(lines: list):
95 p = Parser(Section).parse(lines)
100 ps = argparse.ArgumentParser()
101 ps.add_argument("source")
102 ps.add_argument("-o", dest="out_path", default="out.html")
103 ps.add_argument("-t", dest="template_path", default="template.html")
105 return ps.parse_args()
107 if __name__ == "__main__":
111 print(args.template_path)
113 with open(args.source) as f:
114 lines = f.readlines()
115 doc = Parser(Section, rules).parse(lines)
119 temp = html.parse(args.template_path)
120 temp.getroot().attrib['lang'] = doc.property['lang']
121 temp.xpath('//title')[0].text = doc.property['title']
122 img = temp.xpath('//div[contains(@class, "logo")]/img')[0]
123 img.attrib['src'] = f"/img/logo-{doc.property['lang']}"
124 img.attrib['alt'] = doc.property['title']
126 for sec in temp.xpath('//section'):
127 id = sec.attrib['id']
128 fg = html.fromstring(doc[id])
131 with open(args.out_path, 'w') as f:
132 f.write(html.tostring(temp, encoding='utf-8').decode())