Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #!/usr/bin/env python3
  2. import codecs
  3. import fnmatch
  4. import locale
  5. import os
  6. from collections import namedtuple
  7. from dataclasses import dataclass
  8. from datetime import date, datetime
  9. from html import escape
  10. from operator import attrgetter
  11. from pathlib import Path
  12. from time import perf_counter
  13. import markdown
  14. from jinja2 import Environment as Env
  15. from jinja2 import FileSystemLoader
  16. from minicli import cli, run, wrap
  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. # Hardcoding publication at 12 in Paris timezone.
  23. NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
  24. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  25. def neighborhood(iterable, first=None, last=None):
  26. """
  27. Yield the (previous, current, next) items given an iterable.
  28. You can specify a `first` and/or `last` item for bounds.
  29. """
  30. iterator = iter(iterable)
  31. previous = first
  32. current = next(iterator) # Throws StopIteration if empty.
  33. for next_ in iterator:
  34. yield (previous, current, next_)
  35. previous = current
  36. current = next_
  37. yield (previous, current, last)
  38. def parse_markdown(file_path):
  39. """Extract title, (HTML) content and metadata from a markdown file."""
  40. parser = markdown.Markdown(extensions=["meta"])
  41. with codecs.open(file_path, "r") as source:
  42. content = parser.convert(source.read())
  43. metadata = parser.Meta if hasattr(parser, "Meta") else None
  44. title = metadata["title"][0] if metadata is not None else ""
  45. return title, content, metadata
  46. def each_markdown_from(source_dir, file_name="index.md"):
  47. """Walk across the `source_dir` and return the md file paths."""
  48. for root, dirnames, filenames in os.walk(source_dir):
  49. for filename in fnmatch.filter(filenames, file_name):
  50. yield os.path.join(root, filename)
  51. @dataclass
  52. class Item:
  53. title: str
  54. content: str
  55. file_path: str
  56. def __post_init__(self):
  57. self.full_url = f"{DOMAIN}{self.url}"
  58. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  59. self.escaped_title = escape(self.title)
  60. self.escaped_content = escape(
  61. self.content.replace('href="/', f'href="{DOMAIN}/').replace(
  62. 'src="/', f'src="{DOMAIN}/'
  63. )
  64. )
  65. @property
  66. def is_draft(self):
  67. return self.date > date.today()
  68. @dataclass
  69. class Note(Item):
  70. def __post_init__(self):
  71. suffix = len("/index.md")
  72. prefix = len("YYYY/MM/DD") + suffix
  73. date_str = self.file_path[-prefix:-suffix]
  74. self.url = f"/david/stream/{date_str}/"
  75. self.date = datetime.strptime(date_str, "%Y/%m/%d").date()
  76. super().__post_init__()
  77. self.extract = self.content.split("</p>", 1)[0] + "</p>"
  78. @staticmethod
  79. def all(source, only_published=True):
  80. """Retrieve all (published) notes sorted by date desc."""
  81. note_list = []
  82. for file_path in each_markdown_from(source):
  83. title, content, _ = parse_markdown(file_path)
  84. note = Note(title, content, file_path)
  85. if only_published and note.is_draft:
  86. continue
  87. note_list.append(note)
  88. return sorted(note_list, key=attrgetter("date"), reverse=True)
  89. @dataclass
  90. class Post(Item):
  91. date: str
  92. slug: str
  93. chapo: str
  94. lang: str
  95. def __post_init__(self):
  96. self.url = f"/david/blog/{self.date.year}/{self.slug}/"
  97. super().__post_init__()
  98. self.url_image = f"/static/david/blog/{self.date.year}/{self.slug}.jpg"
  99. self.url_image_thumbnail = (
  100. f"/static/david/blog/{self.date.year}/thumbnails/{self.slug}.jpg"
  101. )
  102. self.full_img_url = f"{DOMAIN}{self.url_image}"
  103. self.full_img_url_thumbnail = f"{DOMAIN}{self.url_image_thumbnail}"
  104. self.escaped_content = self.escaped_content + escape(
  105. f'<img src="{self.full_img_url_thumbnail}" width="500px" height="500px" />'
  106. )
  107. self.escaped_chapo = escape(self.chapo)
  108. @staticmethod
  109. def all(source, only_published=True):
  110. """Retrieve all (published) posts sorted by date desc."""
  111. post_list = []
  112. for file_path in each_markdown_from(source):
  113. title, content, metadata = parse_markdown(file_path)
  114. date = datetime.strptime(metadata["date"][0], "%Y-%m-%d").date()
  115. slug = metadata["slug"][0]
  116. chapo = metadata["chapo"][0]
  117. lang = metadata.get("lang", ["fr"])[0]
  118. post = Post(title, content, file_path, date, slug, chapo, lang)
  119. if only_published and post.is_draft:
  120. continue
  121. post_list.append(post)
  122. return sorted(post_list, key=attrgetter("date"), reverse=True)
  123. @cli
  124. def note(when=None):
  125. """Create a new note and open it in iA Writer.
  126. :when: Optional date in ISO format (YYYY-MM-DD)
  127. """
  128. when = datetime.strptime(when, "%Y-%m-%d") if when else date.today()
  129. note_path = DAVID / "stream" / str(when.year) / str(when.month) / str(when.day)
  130. os.makedirs(note_path)
  131. filename = note_path / "index.md"
  132. open(filename, "w+").write("title: ")
  133. os.popen(f'open -a "iA Writer" "{filename}"')
  134. @cli
  135. def stream():
  136. """Generate articles and archives for the stream."""
  137. template_article = environment.get_template("stream_2019_article.html")
  138. template_archives = environment.get_template("stream_2019_archives.html")
  139. # Default when you reach the last item.
  140. FakeNote = namedtuple("FakeNote", ["url", "title"])
  141. notes_2018 = FakeNote(url="/david/stream/2018/", title="Anciennes notes (2018)")
  142. note_base = DAVID / "stream" / "2019"
  143. unpublished = Note.all(source=note_base, only_published=False)
  144. published = [note for note in unpublished if not note.is_draft]
  145. for previous, note, next_ in neighborhood(unpublished, last=notes_2018):
  146. if note.is_draft:
  147. print(f"Soon: http://larlet.test:8001{note.url} ({note.title})")
  148. # Detect if there is code for syntax highlighting + monospaced font.
  149. has_code = "<code>" in note.content
  150. # Do not link to unpublished notes.
  151. previous = previous and not previous.is_draft and previous or None
  152. page_article = template_article.render(
  153. note=note,
  154. next=previous,
  155. prev=next_,
  156. has_code=has_code,
  157. note_list=published,
  158. )
  159. open(
  160. note_base / f"{note.date.month:02}" / f"{note.date.day:02}" / "index.html",
  161. "w",
  162. ).write(page_article)
  163. page_archive = template_archives.render(note_list=published)
  164. open(note_base / "index.html", "w").write(page_archive)
  165. print(f"Done: http://larlet.test:8001/{note_base}/")
  166. @cli
  167. def blog():
  168. """Generate articles and archives for the blog."""
  169. template_article = environment.get_template("blog_article.html")
  170. template_archives = environment.get_template("blog_archives.html")
  171. # Default when you reach the last item.
  172. FakePost = namedtuple("FakePost", ["url", "title"])
  173. posts_2012 = FakePost(
  174. url="/david/thoughts/", title="Pensées précédentes (en anglais)"
  175. )
  176. post_base = DAVID / "blog"
  177. unpublished = Post.all(source=post_base, only_published=False)
  178. published = [post for post in unpublished if not post.is_draft]
  179. published_en = [post for post in published if post.lang == "en"]
  180. note_list = Note.all(source=DAVID / "stream" / "2019")
  181. for previous, post, next_ in neighborhood(unpublished, last=posts_2012):
  182. if post.is_draft:
  183. print(f"Soon: http://larlet.test:8001{post.url} ({post.title})")
  184. # Detect if there is code for syntax highlighting + monospaced font.
  185. has_code = "<code>" in post.content
  186. # Do not link to unpublished posts.
  187. previous = previous and not previous.is_draft and previous or None
  188. page_article = template_article.render(
  189. post=post,
  190. next=previous,
  191. prev=next_,
  192. has_code=has_code,
  193. post_list=published,
  194. published_posts_en=published_en,
  195. note_list=note_list,
  196. )
  197. open(post_base / str(post.date.year) / post.slug / "index.html", "w",).write(
  198. page_article
  199. )
  200. page_archive = template_archives.render(posts=published)
  201. open(post_base / "index.html", "w").write(page_archive)
  202. print(f"Done: http://larlet.test:8001/{post_base}/")
  203. @cli
  204. def home():
  205. """Build the home page with last published items."""
  206. template = environment.get_template("profil.html")
  207. content = template.render(note_list=Note.all(source=DAVID / "stream" / "2019"),)
  208. open(DAVID / "index.html", "w").write(content)
  209. @cli
  210. def feed():
  211. """Generate a feed from last published items."""
  212. template = environment.get_template("feed.xml")
  213. content = template.render(
  214. note_list=Note.all(source=DAVID / "stream" / "2019")[:15],
  215. post_list=Post.all(source=DAVID / "blog")[:5],
  216. current_dt=datetime.now().strftime(NORMALIZED_STRFTIME),
  217. BASE_URL=f"{DOMAIN}/david/",
  218. )
  219. open(DAVID / "log" / "index.xml", "w").write(content)
  220. @wrap
  221. def perf_wrapper():
  222. start = perf_counter()
  223. yield
  224. elapsed = perf_counter() - start
  225. print(f"Done in {elapsed:.5f} seconds.")
  226. if __name__ == "__main__":
  227. run()