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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 = date.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 self.date > TODAY
  102. @cli
  103. def fragment(title: str):
  104. """Create a new fragment and open it in iA Writer."""
  105. fragment_path = DAVID / "2020" / "fragments" / f"{title}.md"
  106. open(fragment_path, "w+").write(f"## {title}")
  107. os.popen(f'open -a "iA Writer" "{fragment_path}"')
  108. @cli
  109. def pages():
  110. """Build the agregations from fragments."""
  111. root_path = DAVID / "2020"
  112. for previous, page, next_ in neighborhood(
  113. reversed(Page.all(source=root_path, only_published=False)),
  114. first={
  115. "url": "/david/stream/",
  116. "title": "Streams 2009-2019",
  117. "is_draft": False,
  118. },
  119. ):
  120. template = environment.get_template("article_2020.html")
  121. content = template.render(page=page, prev=previous, next=next_,)
  122. target_path = Path(page.url[1:])
  123. target_path.mkdir(parents=True, exist_ok=True)
  124. open(target_path / "index.html", "w").write(content)
  125. if page.is_draft:
  126. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  127. template = environment.get_template("archives_2020.html")
  128. content = template.render(page_list=Page.all(source=root_path))
  129. open(root_path / "index.html", "w").write(content)
  130. @cli
  131. def home():
  132. """Build the home page with last published items."""
  133. template = environment.get_template("profil.html")
  134. content = template.render(page_list=Page.all(source=DAVID / "2020"),)
  135. open(DAVID / "index.html", "w").write(content)
  136. @cli
  137. def feed():
  138. """Generate a feed from last published items."""
  139. template = environment.get_template("feed.xml")
  140. content = template.render(
  141. page_list=Page.all(source=DAVID / "2020"),
  142. current_dt=datetime.now().strftime(NORMALIZED_STRFTIME),
  143. BASE_URL=f"{DOMAIN}/david/",
  144. )
  145. open(DAVID / "log" / "index.xml", "w").write(content)
  146. @wrap
  147. def perf_wrapper():
  148. start = perf_counter()
  149. yield
  150. elapsed = perf_counter() - start
  151. print(f"Done in {elapsed:.5f} seconds.")
  152. if __name__ == "__main__":
  153. run()