aboutsummaryrefslogtreecommitdiff
path: root/build.py
blob: 7f46759cea2eb644824a9d8bf932355f63b47859 (plain)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/env python3
import datetime
import os
import pathlib
import shutil
import textwrap


class Post:
    def __init__(self, slug, content):
        self.content = content
        self.slug = slug

    @property
    def title(self):
        return self.content.splitlines()[0][2:]

    @property
    def posted(self):
        return datetime.datetime.strptime(self.content.splitlines()[1], "%Y-%m-%d").date()

    @property
    def uri(self):
        yyyy = self.posted.strftime("%Y")
        mm = self.posted.strftime("%m")
        return f"{yyyy}/{mm}/{self.slug}"


    def __repr__(self):
        return f"Post(slug={self.slug},title={self.title},posted={self.posted}"


def load_posts():
    posts = []

    for directory, _, files in os.walk("content"):
        for file in files:
            if file.endswith("gmi"):
                with open(f"{directory}/{file}") as old_file:
                    posts.append(Post(file[:-4], old_file.read()))
            else:
                # FIXME
                pass

    return posts


def create_index(posts):
    with open("build/gmi/index.gmi", "w") as index:
        index.write(textwrap.dedent("""
            # El blog es mío

            ## Hay otros como él, pero este es el mío
        """).lstrip())

        index.write("_" * 40)
        index.write("\n")

        for post in posts[0:10]:
            index.write(textwrap.dedent(f"""
                => {post.uri} {post.posted} {post.title}

                ### {post.title}
            """))

            post_lines = post.content.splitlines()

            index.write("\n".join(post_lines[2:]))
            index.write("\n\n")
            index.write("_" * 40)
            index.write("\n")

        index.write(textwrap.dedent("""
            # Sobre mí

            => https://alex.corcoles.net/feed/ Feed RSS de este blog
            => https://github.com/alexpdp7/ GitHub
            => https://es.linkedin.com/in/alexcorcoles LinkedIn
            => https://projecteuler.net/profile/koalillo.png Project Euler
            => https://stackexchange.com/users/13361/alex Stack Exchange
            => https://farside.link/nitter/koalillo Twitter

            Podéis escribirme cogiendo el dominio de esta web y cambiando el primer punto por una arroba.

            # El resto...
        """))



        for post in posts[10:]:
            index.write(textwrap.dedent(f"""
                => {post.uri} {post.posted} {post.title}
            """)[:-1])

def create_individual_posts(posts):
    for post in posts:
        os.makedirs(f"build/gmi/{post.uri}", exist_ok=True)
        with open(f"build/gmi/{post.uri}/index.gmi", "w") as post_file:
            post_file.write(textwrap.dedent("""
                => / El blog es mío

            """))
            post_file.write(post.content)
            post_file.write(textwrap.dedent(f"""

                => https://github.com/alexpdp7/gemini_blog/edit/master/content/{post.uri}.gmi Editar este post

                Podéis escribirme cogiendo el dominio de esta web y cambiando el primer punto por una arroba.

                # Volver al inicio

                => / El blog es mío
            """))


def build():
    shutil.rmtree("build", ignore_errors=True)
    os.makedirs("build/gmi")

    posts = load_posts()
    create_index(sorted(posts, key=lambda p: p.posted, reverse=True))
    create_individual_posts(posts)
    for directory, _, files in os.walk("static/gmi"):
        new_dir = directory.replace("static/gmi", "build/gmi")
        for file in files:
            pathlib.Path(new_dir).mkdir(parents=True, exist_ok=True)
            shutil.copy(f"{directory}/{file}", f"{new_dir}/{file}")

if __name__ == "__main__":
    build()