Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

site.py 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #!/usr/bin/env python3
  2. import fnmatch
  3. import locale
  4. import os
  5. from dataclasses import dataclass
  6. from datetime import datetime, timedelta
  7. from html import escape
  8. from pathlib import Path
  9. from textwrap import dedent
  10. from time import perf_counter
  11. import mistune
  12. from jinja2 import Environment as Env
  13. from jinja2 import FileSystemLoader
  14. from minicli import cli, run, wrap
  15. from mistune.directives import DirectiveInclude
  16. from PIL import Image
  17. from slugify import slugify
  18. # Useful for dates rendering within Jinja2.
  19. locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
  20. HERE = Path(".")
  21. DAVID = HERE / "david"
  22. STATIC = HERE / ".." / "larlet-fr-static"
  23. DOMAIN = "https://larlet.fr"
  24. LOCAL_DOMAIN = "http://larlet.test:3579"
  25. # Hardcoding publication at 12 in Paris timezone.
  26. NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
  27. TODAY = datetime.today() + timedelta(hours=6)
  28. class MarkParser(mistune.InlineParser):
  29. """Parses `==foo==` as `<mark>foo</mark>`."""
  30. MARK = (
  31. r"(\={2})(?=[^\s*])("
  32. r"(?:\\[\\*]|[^*])*"
  33. r"(?:" + mistune.InlineParser.ESCAPE + r"|[^\s*]))\1"
  34. )
  35. RULE_NAMES = mistune.InlineParser.RULE_NAMES + ("mark",)
  36. def parse_mark(self, m, state):
  37. marker = m.group(1)
  38. text = m.group(2)
  39. return "mark", self.render(text, state)
  40. class MarkRenderer(mistune.HTMLRenderer):
  41. """To use in conjunction with `MarkParser`."""
  42. def mark(self, text):
  43. return "<mark>" + text + "</mark>"
  44. class BlockquoteLanguageRenderer(MarkRenderer):
  45. """Sets the English language attribute for blockquotes with `[en]` prefix."""
  46. def _get_language(self, text):
  47. if text.startswith("<p>[en] "):
  48. return "en", text.replace("<p>[en] ", "<p>")
  49. else:
  50. return None, text
  51. def block_quote(self, text):
  52. language, text = self._get_language(text)
  53. if language:
  54. return f'\n<blockquote lang="{language}">\n{text}</blockquote>\n'
  55. else:
  56. return f"\n<blockquote>\n{text}</blockquote>\n"
  57. class ImgsWithSizesRenderer(BlockquoteLanguageRenderer):
  58. """Renders images as <figure>s and add sizes (useful for lazy loading)."""
  59. def paragraph(self, text):
  60. # In case of a figure, we do not want the (non-standard) paragraph.
  61. if text.strip().startswith("<figure>"):
  62. return text
  63. return f"<p>{text}</p>\n"
  64. def image(self, src, alt="", title=None):
  65. full_path = STATIC / Path(src[1:])
  66. image = Image.open(full_path)
  67. width, height = image.size
  68. return dedent(
  69. f"""\
  70. <figure>
  71. <img src="{src}"
  72. alt="{alt}"
  73. loading="lazy" width="{width}" height="{height}" />
  74. <figcaption>{title}</figcaption>
  75. </figure>
  76. """
  77. )
  78. class H2AnchorsRenderer(ImgsWithSizesRenderer):
  79. """Custom renderer for H2 titles with anchors."""
  80. def heading(self, text, level):
  81. if level == 2:
  82. slug = slugify(text)
  83. return (
  84. f'<h2 id="{slug}">'
  85. f"{text} "
  86. f'<a href="#{slug}" title="Ancre vers cette partie" '
  87. f'aria-hidden="true">#</a>'
  88. f"</h2>"
  89. )
  90. else:
  91. return super().heading(text, level)
  92. # We want a custom renderer to create a hash/link for each H2 headings.
  93. markdown_with_h2_anchors = mistune.Markdown(
  94. renderer=H2AnchorsRenderer(escape=False),
  95. inline=MarkParser(H2AnchorsRenderer(escape=False)),
  96. plugins=[DirectiveInclude()],
  97. )
  98. # The second markdown is pertinent to generate articles for the feed,
  99. # we do not need anchors in that case.
  100. markdown_with_img_sizes = mistune.Markdown(
  101. renderer=ImgsWithSizesRenderer(escape=False),
  102. inline=MarkParser(ImgsWithSizesRenderer(escape=False)),
  103. plugins=[DirectiveInclude()],
  104. )
  105. # This is the jinja2 configuration to locate templates.
  106. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  107. def neighborhood(iterable, first=None, last=None):
  108. """
  109. Yield the (previous, current, next) items given an iterable.
  110. You can specify a `first` and/or `last` item for bounds.
  111. """
  112. iterator = iter(iterable)
  113. previous = first
  114. current = next(iterator) # Throws StopIteration if empty.
  115. for next_ in iterator:
  116. yield (previous, current, next_)
  117. previous = current
  118. current = next_
  119. yield (previous, current, last)
  120. def each_markdown_from(source_dir, file_name="*.md"):
  121. """Walk across the `source_dir` and return the md file paths."""
  122. for filename in fnmatch.filter(os.listdir(source_dir), file_name):
  123. yield os.path.join(source_dir, filename)
  124. @dataclass
  125. class Page:
  126. title: str
  127. content: str
  128. file_path: str
  129. lang: str = "fr"
  130. def __post_init__(self):
  131. suffix = len(".md")
  132. prefix = len("YYYY/MM-DD") + suffix
  133. date_str = self.file_path[-prefix:-suffix].replace("-", "/")
  134. self.url = f"/david/{date_str}/"
  135. self.date = datetime.strptime(date_str, "%Y/%m/%d").date()
  136. self.full_url = f"{DOMAIN}{self.url}"
  137. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  138. self.escaped_title = escape(self.title)
  139. self.escaped_content = escape(
  140. self.content.replace('href="/', f'href="{DOMAIN}/')
  141. .replace('src="/', f'src="{DOMAIN}/')
  142. .replace('href="#', f'href="{self.full_url}#')
  143. )
  144. # Extract first paragraph.
  145. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  146. def __lt__(self, other: "Page"):
  147. if not isinstance(other, Page):
  148. return NotImplemented
  149. return self.date < other.date
  150. @staticmethod
  151. def all(source: Path, only_published=True, with_h2_anchors=True):
  152. """Retrieve all pages sorted by desc."""
  153. page_list = []
  154. md = markdown_with_h2_anchors if with_h2_anchors else markdown_with_img_sizes
  155. for file_path in each_markdown_from(source):
  156. result = md.read(file_path)
  157. # Extract (and remove) the title from the generated page.
  158. title, content = result.split("</h1>", 1)
  159. h1_opening_size = len("<h1>")
  160. title = title[h1_opening_size:]
  161. page = Page(title, content, file_path)
  162. if only_published and page.is_draft:
  163. continue
  164. page_list.append(page)
  165. return sorted(page_list, reverse=True)
  166. @property
  167. def is_draft(self):
  168. return (
  169. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  170. > TODAY
  171. )
  172. @cli
  173. def orphans():
  174. """Print out fragments not linked to any page."""
  175. linked_fragments = []
  176. for file_path in each_markdown_from(DAVID / "2020"):
  177. for line in open(file_path).readlines():
  178. if line.startswith(".. include:: fragments/"):
  179. linked_fragments.append(line[len(".. include:: fragments/") : -1])
  180. all_fragments = []
  181. for file_path in each_markdown_from(DAVID / "2020" / "fragments"):
  182. all_fragments.append(file_path[len("david/2020/fragments/") :])
  183. for fragment_filename in set(all_fragments) - set(linked_fragments):
  184. # Prepending path for easy command+click from fish.
  185. print(f"Orphan: {DAVID / '2020' / 'fragments' / fragment_filename}")
  186. @cli
  187. def pages():
  188. """Build the agregations from fragments."""
  189. root_path = DAVID / "2020"
  190. for previous, page, next_ in neighborhood(
  191. reversed(Page.all(source=root_path, only_published=False)),
  192. first={
  193. "url": "/david/stream/",
  194. "title": "Streams 2009-2019",
  195. "is_draft": False,
  196. },
  197. ):
  198. template = environment.get_template("article_2020.html")
  199. content = template.render(page=page, prev=previous, next=next_,)
  200. target_path = Path(page.url[1:])
  201. target_path.mkdir(parents=True, exist_ok=True)
  202. open(target_path / "index.html", "w").write(content)
  203. if page.is_draft:
  204. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  205. template = environment.get_template("archives_2020.html")
  206. content = template.render(page_list=Page.all(source=root_path))
  207. open(root_path / "index.html", "w").write(content)
  208. @cli
  209. def home():
  210. """Build the home page with last published items."""
  211. template = environment.get_template("profil.html")
  212. content = template.render(page_list=Page.all(source=DAVID / "2020"),)
  213. open(DAVID / "index.html", "w").write(content)
  214. @cli
  215. def feed():
  216. """Generate a feed from last published items."""
  217. template = environment.get_template("feed.xml")
  218. content = template.render(
  219. page_list=Page.all(source=DAVID / "2020", with_h2_anchors=False),
  220. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  221. BASE_URL=f"{DOMAIN}/david/",
  222. )
  223. open(DAVID / "log" / "index.xml", "w").write(content)
  224. @wrap
  225. def perf_wrapper():
  226. start = perf_counter()
  227. yield
  228. elapsed = perf_counter() - start
  229. print(f"Done in {elapsed:.5f} seconds.")
  230. if __name__ == "__main__":
  231. run()