Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. _ = 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">#</a>'
  87. f"</h2>"
  88. )
  89. else:
  90. return super().heading(text, level)
  91. # We want a custom renderer to create a hash/link for each H2 headings.
  92. markdown_with_h2_anchors = mistune.Markdown(
  93. renderer=H2AnchorsRenderer(escape=False),
  94. inline=MarkParser(H2AnchorsRenderer(escape=False)),
  95. plugins=[DirectiveInclude()],
  96. )
  97. # The second markdown is pertinent to generate articles for the feed,
  98. # we do not need anchors in that case.
  99. markdown_with_img_sizes = mistune.Markdown(
  100. renderer=ImgsWithSizesRenderer(escape=False),
  101. inline=MarkParser(ImgsWithSizesRenderer(escape=False)),
  102. plugins=[DirectiveInclude()],
  103. )
  104. # This is the jinja2 configuration to locate templates.
  105. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  106. def neighborhood(iterable, first=None, last=None):
  107. """
  108. Yield the (previous, current, next) items given an iterable.
  109. You can specify a `first` and/or `last` item for bounds.
  110. """
  111. iterator = iter(iterable)
  112. previous = first
  113. current = next(iterator) # Throws StopIteration if empty.
  114. for next_ in iterator:
  115. yield (previous, current, next_)
  116. previous = current
  117. current = next_
  118. yield (previous, current, last)
  119. def each_markdown_from(source_dir, file_name="*.md"):
  120. """Walk across the `source_dir` and return the md file paths."""
  121. for filename in fnmatch.filter(os.listdir(source_dir), file_name):
  122. yield os.path.join(source_dir, filename)
  123. @dataclass
  124. class Page:
  125. title: str
  126. content: str
  127. file_path: str
  128. lang: str = "fr"
  129. def __post_init__(self):
  130. suffix = len(".md")
  131. prefix = len("YYYY/MM-DD") + suffix
  132. date_str = self.file_path[-prefix:-suffix].replace("-", "/")
  133. self.url = f"/david/{date_str}/"
  134. self.date = datetime.strptime(date_str, "%Y/%m/%d").date()
  135. self.full_url = f"{DOMAIN}{self.url}"
  136. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  137. self.escaped_title = escape(self.title)
  138. self.escaped_content = escape(
  139. self.content.replace('href="/', f'href="{DOMAIN}/')
  140. .replace('src="/', f'src="{DOMAIN}/')
  141. .replace('href="#', f'href="{self.full_url}#')
  142. + '<hr/><p><a href="mailto:david@larlet.fr">Réagir ?</a></p>'
  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(
  200. page=page,
  201. prev=previous,
  202. next=next_,
  203. )
  204. target_path = Path(page.url[1:])
  205. target_path.mkdir(parents=True, exist_ok=True)
  206. open(target_path / "index.html", "w").write(content)
  207. if page.is_draft:
  208. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  209. template = environment.get_template("archives_2020.html")
  210. content = template.render(page_list=reversed(Page.all(source=root_path)))
  211. open(root_path / "index.html", "w").write(content)
  212. @cli
  213. def home():
  214. """Build the home page with last published items."""
  215. template = environment.get_template("profil.html")
  216. content = template.render(
  217. page_list=reversed(Page.all(source=DAVID / "2020")),
  218. )
  219. open(DAVID / "index.html", "w").write(content)
  220. @cli
  221. def feed():
  222. """Generate a feed from last published items."""
  223. template = environment.get_template("feed.xml")
  224. content = template.render(
  225. page_list=Page.all(source=DAVID / "2020", with_h2_anchors=False),
  226. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  227. BASE_URL=f"{DOMAIN}/david/",
  228. )
  229. open(DAVID / "log" / "index.xml", "w").write(content)
  230. @wrap
  231. def perf_wrapper():
  232. start = perf_counter()
  233. yield
  234. elapsed = perf_counter() - start
  235. print(f"Done in {elapsed:.5f} seconds.")
  236. if __name__ == "__main__":
  237. run()