Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

site.py 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #!/usr/bin/env python3
  2. import fnmatch
  3. import json
  4. import locale
  5. import os
  6. from dataclasses import dataclass
  7. from datetime import date, datetime, timedelta
  8. from html import escape
  9. from pathlib import Path
  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 slugify import slugify
  17. # Useful for dates rendering within Jinja2.
  18. locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
  19. HERE = Path(".")
  20. DAVID = HERE / "david"
  21. DOMAIN = "https://larlet.fr"
  22. LOCAL_DOMAIN = "http://larlet.test:3579"
  23. # Hardcoding publication at 12 in Paris timezone.
  24. NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
  25. TODAY = datetime.today() + timedelta(hours=6)
  26. class CustomHTMLRenderer(mistune.HTMLRenderer):
  27. def heading(self, text, level):
  28. # Set an anchor to h2 headings.
  29. if level == 2:
  30. slug = slugify(text)
  31. return (
  32. f'<h2 id="{slug}">'
  33. f"{text} "
  34. f'<a href="#{slug}" title="Ancre vers cette partie" '
  35. f'aria-hidden="true">#</a>'
  36. f"</h2>"
  37. )
  38. else:
  39. return super().heading(text, level)
  40. markdown = mistune.create_markdown(
  41. renderer=CustomHTMLRenderer(escape=False), plugins=[DirectiveInclude()]
  42. )
  43. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  44. def neighborhood(iterable, first=None, last=None):
  45. """
  46. Yield the (previous, current, next) items given an iterable.
  47. You can specify a `first` and/or `last` item for bounds.
  48. """
  49. iterator = iter(iterable)
  50. previous = first
  51. current = next(iterator) # Throws StopIteration if empty.
  52. for next_ in iterator:
  53. yield (previous, current, next_)
  54. previous = current
  55. current = next_
  56. yield (previous, current, last)
  57. def each_markdown_from(source_dir, file_name="*.md"):
  58. """Walk across the `source_dir` and return the md file paths."""
  59. for filename in fnmatch.filter(os.listdir(source_dir), file_name):
  60. yield os.path.join(source_dir, filename)
  61. @dataclass
  62. class Page:
  63. title: str
  64. content: str
  65. file_path: str
  66. lang: str = "fr"
  67. def __post_init__(self):
  68. suffix = len(".md")
  69. prefix = len("YYYY/MM-DD") + suffix
  70. date_str = self.file_path[-prefix:-suffix].replace("-", "/")
  71. self.url = f"/david/{date_str}/"
  72. self.date = datetime.strptime(date_str, "%Y/%m/%d").date()
  73. self.full_url = f"{DOMAIN}{self.url}"
  74. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  75. self.escaped_title = escape(self.title)
  76. self.escaped_content = escape(
  77. self.content.replace('href="/', f'href="{DOMAIN}/')
  78. .replace('src="/', f'src="{DOMAIN}/')
  79. .replace('href="#', f'href="{self.full_url}#')
  80. )
  81. # Extract first paragraph.
  82. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  83. def __lt__(self, other: "Page"):
  84. if not isinstance(other, Page):
  85. return NotImplemented
  86. return self.date < other.date
  87. @staticmethod
  88. def all(source: Path, only_published=True):
  89. """Retrieve all pages sorted by desc."""
  90. page_list = []
  91. for file_path in each_markdown_from(source):
  92. result = markdown.read(file_path)
  93. title, content = result.split("</h1>", 1)
  94. h1_opening_size = len("<h1>")
  95. title = title[h1_opening_size:]
  96. page = Page(title, content, file_path)
  97. if only_published and page.is_draft:
  98. continue
  99. page_list.append(page)
  100. return sorted(page_list, reverse=True)
  101. @property
  102. def is_draft(self):
  103. return (
  104. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  105. > TODAY
  106. )
  107. @cli
  108. def orphans():
  109. """Print out fragments not linked to any page."""
  110. linked_fragments = []
  111. for file_path in each_markdown_from(DAVID / "2020"):
  112. for line in open(file_path).readlines():
  113. if line.startswith(".. include:: fragments/"):
  114. linked_fragments.append(line[len(".. include:: fragments/") : -1])
  115. all_fragments = []
  116. for file_path in each_markdown_from(DAVID / "2020" / "fragments"):
  117. all_fragments.append(file_path[len("david/2020/fragments/") :])
  118. for fragment_filename in set(all_fragments) - set(linked_fragments):
  119. # Prepending path for easy command+click from fish.
  120. print(f"Orphan: {DAVID / '2020' / 'fragments' / fragment_filename}")
  121. @cli
  122. def pages():
  123. """Build the agregations from fragments."""
  124. root_path = DAVID / "2020"
  125. for previous, page, next_ in neighborhood(
  126. reversed(Page.all(source=root_path, only_published=False)),
  127. first={
  128. "url": "/david/stream/",
  129. "title": "Streams 2009-2019",
  130. "is_draft": False,
  131. },
  132. ):
  133. template = environment.get_template("article_2020.html")
  134. content = template.render(page=page, prev=previous, next=next_,)
  135. target_path = Path(page.url[1:])
  136. target_path.mkdir(parents=True, exist_ok=True)
  137. open(target_path / "index.html", "w").write(content)
  138. if page.is_draft:
  139. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  140. template = environment.get_template("archives_2020.html")
  141. content = template.render(page_list=Page.all(source=root_path))
  142. open(root_path / "index.html", "w").write(content)
  143. @cli
  144. def home():
  145. """Build the home page with last published items."""
  146. template = environment.get_template("profil.html")
  147. content = template.render(page_list=Page.all(source=DAVID / "2020"),)
  148. open(DAVID / "index.html", "w").write(content)
  149. @cli
  150. def feed():
  151. """Generate a feed from last published items."""
  152. template = environment.get_template("feed.xml")
  153. content = template.render(
  154. page_list=Page.all(source=DAVID / "2020"),
  155. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  156. BASE_URL=f"{DOMAIN}/david/",
  157. )
  158. open(DAVID / "log" / "index.xml", "w").write(content)
  159. @cli
  160. def mastodon():
  161. """Generate an activity feed from last published items."""
  162. page_list = Page.all(source=DAVID / "2020")
  163. current_dt = TODAY.strftime(NORMALIZED_STRFTIME)
  164. BASE_URL = f"{DOMAIN}/david/"
  165. content = {}
  166. open(DAVID / "mastodon" / "outbox_content.json", "w").write(json.dumps(content))
  167. @wrap
  168. def perf_wrapper():
  169. start = perf_counter()
  170. yield
  171. elapsed = perf_counter() - start
  172. print(f"Done in {elapsed:.5f} seconds.")
  173. if __name__ == "__main__":
  174. run()