summaryrefslogtreecommitdiff
path: root/blog/post.py
blob: 8a7c8808957ebe648591966d2822b48a5c9a6cbc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import os
import shutil
import datetime
import functools
from typing import Dict

from jinja2 import Template

import render


class Metadata(object):
    __slots__ = ("title", "author", "date", "status")
    title: str
    author: str
    date: str
    status: str

    def __init__(self, title: str, author: str,
                 date: str, status: str) -> None:
        self.title = title
        self.author = author
        self.date = date
        self.status = status


class Post(object):
    template: Template
    directory: str
    name: str

    def __init__(self, template: Template, directory: str) -> None:
        self.template = template
        self.directory = directory
        self.name = os.path.basename(directory)

    @staticmethod
    def _load_raw_metadata(filename: str) -> Dict[str, str]:
        data = {}

        with open(filename) as f:
            for line in f:
                k, v = line.strip().split(": ")
                data[k] = v

        return data

    @functools.cached_property
    def metadata(self) -> Metadata:
        raw = Post._load_raw_metadata(os.path.join(self.directory,
                                                   "metadata.txt"))

        title = raw["Title"]
        author = raw["Author"]
        date = raw.get("Date", datetime.date.today().strftime("%Y-%m-%d"))
        status = raw.get("Status", "draft")

        return Metadata(title, author, date, status)

    def generate(self, basedir: str) -> None:
        postdir = os.path.basename(self.directory)
        workdir = os.path.join(basedir, postdir)
        os.makedirs(workdir)

        md = None
        for filename in os.listdir(self.directory):
            source = os.path.join(self.directory, filename)
            destination = os.path.join(workdir, filename)

            shutil.copy(source, destination)

            if filename.endswith(".md"):
                md = source

        assert md, f"There is no markdown file in `{self.directory}`"

        content = render.to_html(md)
        rendered = self.template.render(title=self.metadata.title,
                                        author=self.metadata.author,
                                        date=self.metadata.date,
                                        status=self.metadata.status,
                                        content=content)
        render.write_file_content(os.path.join(workdir, "index.html"),
                                  rendered)