-
Notifications
You must be signed in to change notification settings - Fork 0
/
build_static_files.py
158 lines (129 loc) Β· 5.53 KB
/
build_static_files.py
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
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
158
import shutil
import time
from django.conf import settings
from django.core import management
from django.core.management.base import BaseCommand
from django.core.paginator import Paginator
from django.test import Client as DjangoClient, override_settings
from django.urls import reverse
from ... import assets_generation, models
from ...models import enable_building_static_assets_mode, get_post_url
class Command(BaseCommand):
help = "Build the blog as static files for deployment"
def handle(self, *args, **options):
shutil.rmtree(settings.DIST_DIR, ignore_errors=True)
settings.DIST_DIR.mkdir(exist_ok=True)
self._trigger_remote_assets_generation()
self._handle_static_assets()
self._handle_current_pages()
# These 2 are specific to the migration from Material for MkDocs:
self._handle_material_for_mkdocs_posts_redirect_pages()
self._handle_files_to_copy()
@staticmethod
def _trigger_remote_assets_generation() -> None:
assets_generation.download_assets_if_needed()
def _handle_static_assets(self) -> None:
settings.STATIC_ROOT.mkdir(exist_ok=True)
self.stdout.write("Collecting static files...")
management.call_command(
"collectstatic", verbosity=0, interactive=False, clear=True
)
self.stdout.write("")
def _handle_current_pages(self) -> None:
enable_building_static_assets_mode()
url_paths_to_build = [
"/",
"/about/",
"/rss.xml",
*self._get_blog_post_url_paths(),
*self._get_blog_tags_url_paths(),
*self._get_blog_posts_pagination_url_paths(),
]
static_pages_generation_start_time = time.monotonic()
with override_settings(DEBUG=False):
client = DjangoClient()
for url_path in url_paths_to_build:
self._write_static_html_file_for_url_path(url_path, client=client)
self.stdout.write(
self.style.SUCCESS(
f"Successfully built {len(url_paths_to_build)} pages "
f"in {time.monotonic() - static_pages_generation_start_time:.2f}s."
)
)
def _handle_material_for_mkdocs_posts_redirect_pages(self) -> None:
url_paths_to_build = self._get_material_for_mkdocs_blog_posts_url_paths()
static_pages_generation_start_time = time.monotonic()
with override_settings(DEBUG=False):
client = DjangoClient()
for url_path in url_paths_to_build:
self._write_static_html_file_for_url_path(
url_path,
client=client,
)
self.stdout.write(
self.style.SUCCESS(
f"Successfully managed {len(url_paths_to_build)} former 'MKDocs' page redirects "
f"in {time.monotonic() - static_pages_generation_start_time:.2f}s."
)
)
def _handle_files_to_copy(self) -> None:
dist_dir = settings.DIST_DIR
files_to_copy = {
# With Material FOr MKDocs the RSS feed was living at "/feed_rss_created.xml":
dist_dir / "rss.xml": dist_dir / "feed_rss_created.xml"
}
files_copy_start_time = time.monotonic()
for source, target in files_to_copy.items():
self.stdout.write(
f"Copying '{source.relative_to(dist_dir)}' to '{target.relative_to(dist_dir)}'..."
)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(source.read_bytes())
self.stdout.write(
self.style.SUCCESS(
f"Successfully managed {len(files_to_copy)} file copies "
f"in {time.monotonic() - files_copy_start_time:.2f}s."
)
)
@staticmethod
def _get_blog_post_url_paths() -> list[str]:
return [get_post_url(post) for post in models.get_posts()]
@staticmethod
def _get_blog_tags_url_paths() -> list[str]:
return [
reverse("tag_page", kwargs={"tag": tag}) for tag in models.get_posts_tags()
]
@staticmethod
def _get_blog_posts_pagination_url_paths() -> list[str]:
posts_paginator = Paginator(
models.get_posts(), per_page=settings.POSTS_PER_PAGE
)
return [
reverse("posts_page", kwargs={"page": page})
for page in posts_paginator.page_range
]
@staticmethod
def _get_material_for_mkdocs_blog_posts_url_paths() -> list[str]:
return [
get_post_url(post).removeprefix("/posts")
for post in models.get_posts()
if post.created_at <= models.MATERIAL_FOR_MKDOCS_LAST_POST_DATE
]
def _write_static_html_file_for_url_path(
self, url_path: str, *, client: DjangoClient, target_url_path: str | None = None
) -> None:
self.stdout.write(f"Building '{self.style.SUCCESS(url_path)}' file...")
response = client.get(url_path)
assert response.status_code == 200
target_url_path = target_url_path or url_path
target_file_path = (
settings.DIST_DIR / f"{target_url_path.removeprefix('/')}index.html"
if target_url_path.endswith("/")
else settings.DIST_DIR / target_url_path.removeprefix("/")
)
self.stdout.write(
f"Writing file '{target_file_path.relative_to(settings.DIST_DIR)}'..."
)
target_file_path.parent.mkdir(parents=True, exist_ok=True)
target_file_path.write_bytes(response.content)
self.stdout.write("")