💾 Archived View for republic.circumlunar.space › ~luminar › scripts › atomgen.py captured on 2023-01-29 at 18:57:47.

View Raw

More Information

⬅️ Previous capture (2020-10-31)

-=-=-=-=-=-=-

#! scripts/venv/bin/python

from dataclasses import dataclass
from datetime import datetime
from operator import attrgetter
from pathlib import Path

import pytz
from feedgen.feed import FeedGenerator
from xmlformatter import Formatter

BASE_URL = "gemini://republic.circumlunar.space/~luminar"


@dataclass
class Post:

    title: str
    date: datetime
    summary: str
    file_name: str


def main(file_name: Path, post_dir: Path):

    posts = []
    for post_file in post_dir.glob("*.gmi"):

        with open(post_file) as f:
            title = next(f).strip("# \n")
            date = pytz.timezone("Europe/Prague").localize(
                datetime.strptime(next(f).strip(), "%Y-%m-%d")
            )
            date = date.replace(hour=12, minute=0, second=0, microsecond=0)

            # Get the next non-empty line
            while True:
                summary = next(f).strip()
                if summary:
                    break

            # If there are multiple level one headings, append them to the title
            for line in f:
                if line.startswith("# "):
                    title += "; " + line.strip("# ")

            posts.append(Post(title, date, summary, post_file.name))

    by_date = sorted(posts, key=attrgetter("date"))

    generator = FeedGenerator()
    generator.title("luminar's capsule")
    generator.id(BASE_URL)
    generator.link(href=BASE_URL)
    generator.author(name="luminar")
    generator.language("en")
    generator.updated(by_date[-1].date)

    for post in by_date:
        entry = generator.add_entry()
        entry.id(post.file_name)
        entry.title(post.title)
        entry.summary(post.summary)

        entry.link(href=f"{BASE_URL}/text/{post.file_name}")
        entry.updated(post.date)

    feed = generator.atom_str()
    formatted = Formatter().format_string(feed)

    file_name.write_bytes(formatted)


if __name__ == "__main__":
    main(Path("atom_feed.xml"), Path("text"))