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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. + '<hr/><p><a href="mailto:david@larlet.fr">Réagir ?</a></p>'
  144. )
  145. # Extract first paragraph.
  146. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  147. def __lt__(self, other: "Page"):
  148. if not isinstance(other, Page):
  149. return NotImplemented
  150. return self.date < other.date
  151. @staticmethod
  152. def all(source: Path, only_published=True, with_h2_anchors=True):
  153. """Retrieve all pages sorted by desc."""
  154. page_list = []
  155. md = markdown_with_h2_anchors if with_h2_anchors else markdown_with_img_sizes
  156. for file_path in each_markdown_from(source):
  157. result = md.read(file_path)
  158. # Extract (and remove) the title from the generated page.
  159. title, content = result.split("</h1>", 1)
  160. h1_opening_size = len("<h1>")
  161. title = title[h1_opening_size:]
  162. page = Page(title, content, file_path)
  163. if only_published and page.is_draft:
  164. continue
  165. page_list.append(page)
  166. return sorted(page_list, reverse=True)
  167. @property
  168. def is_draft(self):
  169. return (
  170. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  171. > TODAY
  172. )
  173. @cli
  174. def orphans():
  175. """Print out fragments not linked to any page."""
  176. linked_fragments = []
  177. for file_path in each_markdown_from(DAVID / "2020"):
  178. for line in open(file_path).readlines():
  179. if line.startswith(".. include:: fragments/"):
  180. linked_fragments.append(line[len(".. include:: fragments/") : -1])
  181. all_fragments = []
  182. for file_path in each_markdown_from(DAVID / "2020" / "fragments"):
  183. all_fragments.append(file_path[len("david/2020/fragments/") :])
  184. for fragment_filename in set(all_fragments) - set(linked_fragments):
  185. # Prepending path for easy command+click from fish.
  186. print(f"Orphan: {DAVID / '2020' / 'fragments' / fragment_filename}")
  187. @cli
  188. def pages():
  189. """Build the agregations from fragments."""
  190. root_path = DAVID / "2020"
  191. for previous, page, next_ in neighborhood(
  192. reversed(Page.all(source=root_path, only_published=False)),
  193. first={
  194. "url": "/david/stream/",
  195. "title": "Streams 2009-2019",
  196. "is_draft": False,
  197. },
  198. ):
  199. template = environment.get_template("article_2020.html")
  200. content = template.render(page=page, prev=previous, next=next_,)
  201. target_path = Path(page.url[1:])
  202. target_path.mkdir(parents=True, exist_ok=True)
  203. open(target_path / "index.html", "w").write(content)
  204. if page.is_draft:
  205. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  206. template = environment.get_template("archives_2020.html")
  207. content = template.render(page_list=Page.all(source=root_path))
  208. open(root_path / "index.html", "w").write(content)
  209. @cli
  210. def home():
  211. """Build the home page with last published items."""
  212. template = environment.get_template("profil.html")
  213. content = template.render(page_list=Page.all(source=DAVID / "2020"),)
  214. open(DAVID / "index.html", "w").write(content)
  215. @cli
  216. def feed():
  217. """Generate a feed from last published items."""
  218. template = environment.get_template("feed.xml")
  219. content = template.render(
  220. page_list=Page.all(source=DAVID / "2020", with_h2_anchors=False),
  221. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  222. BASE_URL=f"{DOMAIN}/david/",
  223. )
  224. open(DAVID / "log" / "index.xml", "w").write(content)
  225. @wrap
  226. def perf_wrapper():
  227. start = perf_counter()
  228. yield
  229. elapsed = perf_counter() - start
  230. print(f"Done in {elapsed:.5f} seconds.")
  231. if __name__ == "__main__":
  232. run()