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 6.2KB

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