Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

site.py 5.7KB

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