utils.py 4.73 KB
Newer Older
1
2
3
import os
import shutil

4
import boop.boopsy as boopsy
5
from boop.article import Article
6
from boop.page import Page
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


def init_output_folder(output_path):
    """Create the output directory, empty it if it contains files.
    """
    if os.path.isdir(output_path):
        # it should be a directory...
        shutil.rmtree(output_path)
    elif os.path.exists(output_path):
        # ... but it also can be a simple file if user created it manually!
        os.remove(output_path)
    os.mkdir(output_path)


def add_articles_to_feed(feed, articles):
    """Add article as standard entries to the feed.
    """
    for article in articles:
        entry = {
            "title": article.title(),
            "id": f"urn:uuid:{article.uuid()}",
            "article_link": article.url(),
            "published": article.date(),
            "content": article.content(),
        }

        article_author = article.author()
        if article_author:
            entry["author"] = article_author
        article_update = article.update()
        if article_update:
            entry["updated"] = article_update

        feed.add_entry(entry)


def build_article_from_filepath(filepath, configuration, serie=None):
    """Read a file and initialize an Article from it.
    """
    filepath_no_ext, _ = os.path.splitext(filepath)
    slug = os.path.basename(filepath_no_ext)
    with open(filepath, "r") as article_file:
        return Article(
            slug, article_file.read(), configuration=configuration, serie=serie
        )


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def build_page_from_filepath(filepath, configuration, basename=None, slug=None):
    """Read a file and initialize a Page from it.
    """
    filepath_no_ext, _ = os.path.splitext(filepath)
    if slug:
        final_slug = slug
    elif basename and filepath_no_ext.startswith(basename):
        index_basename = len(basename) + 1
        final_slug = filepath_no_ext[index_basename:]
    else:
        final_slug = os.path.basename(filepath_no_ext)

    with open(filepath, "r") as page_file:
        return Page(final_slug, page_file.read(), configuration=configuration)


berumuron's avatar
berumuron committed
70
71
72
73
74
75
76
def build_blog_page(articles, configuration):
    blog_page = Page("blog", "", configuration=configuration)
    blog_page.meta["PAGE_TEMPLATE"] = "blog"
    blog_page.meta["ARTICLES"] = articles
    return blog_page


berumuron's avatar
berumuron committed
77
78
79
templates_cache = {}


80
81
82
83
84
85
86
87
88
def write_content(content, output_path):
    """Write content (Article or Page) under output_path.
    """
    output_filepath = os.path.join(output_path, f"{content.slug()}.html")
    template_filepath = os.path.join(
        os.curdir, "templates", f"{content.template()}.html"
    )

    # Initialize the template defined within content
berumuron's avatar
berumuron committed
89
90
91
92
    if template_filepath in templates_cache:
        template = templates_cache[template_filepath]
        rendered_content = template.render(content.meta)
    elif os.path.exists(template_filepath):
93
        template = boopsy.Template(template_filepath)
berumuron's avatar
berumuron committed
94
        templates_cache[template_filepath] = template
95
96
97
98
99
100
101
102
103
        rendered_content = template.render(content.meta)
    else:
        rendered_content = content.content()

    mkdirs_for_file(output_filepath)
    with open(output_filepath, "w") as output_file:
        output_file.write(rendered_content)


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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def list_dirs(path):
    """List all the directories within a path.
    """
    for filename in os.listdir(path):
        full_path = os.path.join(path, filename)
        if os.path.isdir(full_path):
            yield filename


def match_extensions(filename, extensions):
    """Return True if filename extension is part of extensions array.
    """
    if len(extensions) > 0:
        _, ext = os.path.splitext(filename)
        if ext[1:] not in extensions:
            return False
    return True


def list_files(path, only=[]):
    """List all the files within a path.
    """
    for filename in os.listdir(path):
        full_path = os.path.join(path, filename)

        # We don't want to yield directories
        if not os.path.isfile(full_path):
            continue

        # If file extension is not part of "only" array, we don't yield it. If
        # only is empty, it means we accept all extensions.
        if not match_extensions(full_path, only):
            continue

        yield filename


def dir_tree(path, only=[]):
    """List all the tree directory under the given path.
    """
    for filename in os.listdir(path):
        full_path = os.path.join(path, filename)
        if os.path.isdir(full_path):
            for sub_filename in dir_tree(full_path, only=only):
                yield os.path.join(filename, sub_filename)
        elif match_extensions(filename, only):
            yield filename


def mkdirs_for_file(filepath):
    """Create parent directories for a given file.
    """
    path = os.path.dirname(filepath)
    os.makedirs(path, exist_ok=True)