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.

пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 ImgsWithSizesRenderer(mistune.HTMLRenderer):
  29. def paragraph(self, text):
  30. # In case of a figure, we do not want the (non-standard) paragraph.
  31. if text.strip().startswith("<figure>"):
  32. return text
  33. return f"<p>{text}</p>\n"
  34. def image(self, src, alt="", title=None):
  35. full_path = STATIC / Path(src[1:])
  36. image = Image.open(full_path)
  37. width, height = image.size
  38. return dedent(
  39. f"""\
  40. <figure>
  41. <img src="{src}"
  42. alt="{alt}"
  43. loading="lazy" width="{width}" height="{height}" />
  44. <figcaption>{title}</figcaption>
  45. </figure>
  46. """
  47. )
  48. class H2AnchorsRenderer(ImgsWithSizesRenderer):
  49. def heading(self, text, level):
  50. # Set an anchor to h2 headings.
  51. if level == 2:
  52. slug = slugify(text)
  53. return (
  54. f'<h2 id="{slug}">'
  55. f"{text} "
  56. f'<a href="#{slug}" title="Ancre vers cette partie" '
  57. f'aria-hidden="true">#</a>'
  58. f"</h2>"
  59. )
  60. else:
  61. return super().heading(text, level)
  62. # We want a custom renderer to create a hash/link for each H2 headings.
  63. markdown_with_h2_anchors = mistune.create_markdown(
  64. renderer=H2AnchorsRenderer(escape=False), plugins=[DirectiveInclude()]
  65. )
  66. # The second markdown is pertinent to generate articles for the feed,
  67. # we do not need anchors in that case.
  68. markdown_with_img_sizes = mistune.create_markdown(
  69. renderer=ImgsWithSizesRenderer(escape=False), plugins=[DirectiveInclude()]
  70. )
  71. # This is the jinja2 configuration to locate templates.
  72. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  73. def neighborhood(iterable, first=None, last=None):
  74. """
  75. Yield the (previous, current, next) items given an iterable.
  76. You can specify a `first` and/or `last` item for bounds.
  77. """
  78. iterator = iter(iterable)
  79. previous = first
  80. current = next(iterator) # Throws StopIteration if empty.
  81. for next_ in iterator:
  82. yield (previous, current, next_)
  83. previous = current
  84. current = next_
  85. yield (previous, current, last)
  86. def each_markdown_from(source_dir, file_name="*.md"):
  87. """Walk across the `source_dir` and return the md file paths."""
  88. for filename in fnmatch.filter(os.listdir(source_dir), file_name):
  89. yield os.path.join(source_dir, filename)
  90. @dataclass
  91. class Page:
  92. title: str
  93. content: str
  94. file_path: str
  95. lang: str = "fr"
  96. def __post_init__(self):
  97. suffix = len(".md")
  98. prefix = len("YYYY/MM-DD") + suffix
  99. date_str = self.file_path[-prefix:-suffix].replace("-", "/")
  100. self.url = f"/david/{date_str}/"
  101. self.date = datetime.strptime(date_str, "%Y/%m/%d").date()
  102. self.full_url = f"{DOMAIN}{self.url}"
  103. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  104. self.escaped_title = escape(self.title)
  105. self.escaped_content = escape(
  106. self.content.replace('href="/', f'href="{DOMAIN}/')
  107. .replace('src="/', f'src="{DOMAIN}/')
  108. .replace('href="#', f'href="{self.full_url}#')
  109. )
  110. # Extract first paragraph.
  111. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  112. def __lt__(self, other: "Page"):
  113. if not isinstance(other, Page):
  114. return NotImplemented
  115. return self.date < other.date
  116. @staticmethod
  117. def all(source: Path, only_published=True, with_h2_anchors=True):
  118. """Retrieve all pages sorted by desc."""
  119. page_list = []
  120. md = markdown_with_h2_anchors if with_h2_anchors else markdown_with_img_sizes
  121. for file_path in each_markdown_from(source):
  122. result = md.read(file_path)
  123. # Extract (and remove) the title from the generated page.
  124. title, content = result.split("</h1>", 1)
  125. h1_opening_size = len("<h1>")
  126. title = title[h1_opening_size:]
  127. page = Page(title, content, file_path)
  128. if only_published and page.is_draft:
  129. continue
  130. page_list.append(page)
  131. return sorted(page_list, reverse=True)
  132. @property
  133. def is_draft(self):
  134. return (
  135. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  136. > TODAY
  137. )
  138. @cli
  139. def orphans():
  140. """Print out fragments not linked to any page."""
  141. linked_fragments = []
  142. for file_path in each_markdown_from(DAVID / "2020"):
  143. for line in open(file_path).readlines():
  144. if line.startswith(".. include:: fragments/"):
  145. linked_fragments.append(line[len(".. include:: fragments/") : -1])
  146. all_fragments = []
  147. for file_path in each_markdown_from(DAVID / "2020" / "fragments"):
  148. all_fragments.append(file_path[len("david/2020/fragments/") :])
  149. for fragment_filename in set(all_fragments) - set(linked_fragments):
  150. # Prepending path for easy command+click from fish.
  151. print(f"Orphan: {DAVID / '2020' / 'fragments' / fragment_filename}")
  152. @cli
  153. def pages():
  154. """Build the agregations from fragments."""
  155. root_path = DAVID / "2020"
  156. for previous, page, next_ in neighborhood(
  157. reversed(Page.all(source=root_path, only_published=False)),
  158. first={
  159. "url": "/david/stream/",
  160. "title": "Streams 2009-2019",
  161. "is_draft": False,
  162. },
  163. ):
  164. template = environment.get_template("article_2020.html")
  165. content = template.render(page=page, prev=previous, next=next_,)
  166. target_path = Path(page.url[1:])
  167. target_path.mkdir(parents=True, exist_ok=True)
  168. open(target_path / "index.html", "w").write(content)
  169. if page.is_draft:
  170. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  171. template = environment.get_template("archives_2020.html")
  172. content = template.render(page_list=Page.all(source=root_path))
  173. open(root_path / "index.html", "w").write(content)
  174. @cli
  175. def home():
  176. """Build the home page with last published items."""
  177. template = environment.get_template("profil.html")
  178. content = template.render(page_list=Page.all(source=DAVID / "2020"),)
  179. open(DAVID / "index.html", "w").write(content)
  180. @cli
  181. def feed():
  182. """Generate a feed from last published items."""
  183. template = environment.get_template("feed.xml")
  184. content = template.render(
  185. page_list=Page.all(source=DAVID / "2020", with_h2_anchors=False),
  186. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  187. BASE_URL=f"{DOMAIN}/david/",
  188. )
  189. open(DAVID / "log" / "index.xml", "w").write(content)
  190. @wrap
  191. def perf_wrapper():
  192. start = perf_counter()
  193. yield
  194. elapsed = perf_counter() - start
  195. print(f"Done in {elapsed:.5f} seconds.")
  196. if __name__ == "__main__":
  197. run()