-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduties.py
More file actions
336 lines (268 loc) · 8.58 KB
/
duties.py
File metadata and controls
336 lines (268 loc) · 8.58 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
"""Duty tasks for the project."""
import os
import re
import shutil
import sys
import uuid
from datetime import datetime
from pathlib import Path
import pytz
from duty import duty, tools
from duty.context import Context
from pelican import main as pelican_main
from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer
from pelican.settings import DEFAULT_CONFIG, get_settings_from_file
CI = os.environ.get("CI", "0") in {"1", "true", "yes", ""}
DEBUG_MODE = os.environ.get("DEBUG_MODE", "0") in {"1", "true", "yes", ""}
OPEN_BROWSER_ON_SERVE = False
SETTINGS = {}
SETTINGS_FILE_BASE = "pelicanconf.py"
SETTINGS_FILE_PUBLISH = "publishconf.py"
SETTINGS.update(DEFAULT_CONFIG)
LOCAL_SETTINGS = get_settings_from_file(SETTINGS_FILE_BASE)
SETTINGS.update(LOCAL_SETTINGS)
PY_SRC_PATHS = (
Path(_)
for _ in ("src/", "tests/", "duties.py", "scripts/")
if Path(_).exists()
)
PY_SRC_LIST = tuple(str(_) for _ in PY_SRC_PATHS)
HOST = "localhost"
PORT = 8080
run_pelican = tools.lazy(pelican_main, name="pelican.main")
POST_PATH = Path(f"{SETTINGS['PATH']}/{SETTINGS['ARTICLE_PATHS'][0]}").resolve()
POST_TEMPLATE = """\
---
title: {title}
slug: {slug}
date: {timestamp}
modified: {timestamp}
summary:
tags:
-
---
"""
def strip_ansi(text: str) -> str:
"""Remove ANSI escape sequences from a string.
Args:
text (str): String to remove ANSI escape sequences from.
Returns:
str: String without ANSI escape sequences.
"""
ansi_chars = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]")
# Replace [ with \[ so rich doesn't interpret output as style tags
return ansi_chars.sub("", text).replace("[", r"\[")
def pyprefix(title: str) -> str:
"""Add a prefix to the title if CI is true.
Returns:
str: Title with prefix if CI is true.
"""
if CI:
prefix = f"(python{sys.version_info.major}.{sys.version_info.minor})"
return f"{prefix:14}{title}"
return title
def slugify(s):
s = s.lower().strip()
s = re.sub(r"[^\w\s-]", "", s)
s = re.sub(r"[\s_-]+", "-", s)
s = re.sub(r"^-+|-+$", "", s)
return s
@duty
def cache_bust(ctx: Context) -> None:
"""Cache bust links to CSS files within the HEAD by appending a unique ID to the URL."""
site_dir = Path(SETTINGS["OUTPUT_PATH"]).resolve()
unique_id = str(uuid.uuid4())[:8]
i = 0
for file in site_dir.glob("**/*.html"):
with open(file, "r") as f:
content = f.read()
if re.search(
r'<link href="?/static/css/[a-zA-Z0-9\.-_]+\.css', content
):
i += 1
content = re.sub(
r'(<link href="?/static/css/[a-zA-Z0-9\.-_]+\.css)',
rf"\1?v={unique_id}",
content,
)
with open(file, "w") as f:
f.write(content)
print(f"Cache busted CSS files in {i} files")
@duty(silent=True)
def clean(ctx: Context) -> None:
"""Clean the project."""
for path in (
".coverage*",
".mypy_cache",
".pytest_cache",
".reports",
".ruff_cache",
SETTINGS["OUTPUT_PATH"],
):
if Path(path).is_dir():
shutil.rmtree(path)
elif Path(path).is_file():
Path(path).unlink()
ctx.run("find . -type d -name __pycache__ | xargs rm -rf")
ctx.run("find . -name '.DS_Store' -delete")
os.makedirs(SETTINGS["OUTPUT_PATH"])
@duty(silent=True)
def clean_cache(ctx: Context) -> None:
"""Clean only the cache directory."""
cache_path = SETTINGS.get("CACHE_PATH", "cache")
if Path(cache_path).is_dir():
shutil.rmtree(cache_path)
# Also remove potential cache files in the output directory
for cache_file in Path(SETTINGS["OUTPUT_PATH"]).glob("**/*.cache"):
cache_file.unlink()
@duty(silent=True)
def clean_output(ctx: Context) -> None:
"""Clean only the output directory."""
output_path = SETTINGS["OUTPUT_PATH"]
if Path(output_path).is_dir():
shutil.rmtree(output_path)
os.makedirs(output_path)
@duty(post=[cache_bust])
def build(ctx: Context) -> None:
"""Build the project."""
pelican_args = ["-s", SETTINGS_FILE_BASE]
if DEBUG_MODE:
pelican_args.append("--debug")
ctx.run(run_pelican(pelican_args))
@duty(post=[cache_bust])
def rebuild(ctx: Context) -> None:
"""Rebuild the project."""
pelican_args = ["-d", "-s", SETTINGS_FILE_BASE]
if DEBUG_MODE:
pelican_args.append("--debug")
ctx.run(run_pelican(pelican_args))
@duty
def regenerate(ctx: Context) -> None:
"""Regenerate the project."""
pelican_args = ["-r", "-s", SETTINGS_FILE_BASE]
if DEBUG_MODE:
pelican_args.append("--debug")
ctx.run(run_pelican(pelican_args))
@duty
def serve(ctx: Context) -> None:
"""Serve the project."""
class AddressReuseTCPServer(RootedHTTPServer):
allow_reuse_address = True
server = AddressReuseTCPServer(
SETTINGS["OUTPUT_PATH"],
(HOST, PORT),
ComplexHTTPRequestHandler,
)
if OPEN_BROWSER_ON_SERVE:
# Open site in default browser
import webbrowser
webbrowser.open(f"http://{HOST}:{PORT}")
sys.stderr.write(f"Serving at {HOST}:{PORT} ...\n")
server.serve_forever()
@duty
def reserve(ctx: Context) -> None:
"""Re-serve the project."""
build(ctx)
serve(ctx)
@duty(post=[cache_bust])
def publish(ctx: Context) -> None:
"""Publish the project."""
ctx.run(run_pelican(["-s", SETTINGS_FILE_PUBLISH]))
@duty
def livereload(ctx: Context):
"""Automatically reload browser tab upon file modification."""
from livereload import Server
def cached_build():
# Clean cache and output directories before building to avoid EOFError
clean_cache(ctx)
clean_output(ctx)
pelican_args = [
"-s",
SETTINGS_FILE_BASE,
"--debug", # Always use debug mode to get more detailed error info
]
ctx.run(run_pelican(pelican_args))
theme_path = SETTINGS["THEME"]
watched_globs = [
SETTINGS_FILE_BASE,
f"{theme_path}/templates/**/*.html",
]
cached_build()
server = Server()
content_file_extensions = [".md", ".rst"]
for extension in content_file_extensions:
content_glob = f"{SETTINGS['PATH']}/**/*{extension}"
watched_globs.append(content_glob)
static_file_extensions = [".css", ".js"]
for extension in static_file_extensions:
static_file_glob = f"{theme_path}/static/**/*{extension}"
watched_globs.append(static_file_glob)
for glob in watched_globs:
server.watch(glob, cached_build)
if OPEN_BROWSER_ON_SERVE:
# Open site in default browser
import webbrowser
webbrowser.open(f"http://{HOST}:{PORT}")
server.serve(host=HOST, port=PORT, root=SETTINGS["OUTPUT_PATH"])
@duty
def new(ctx: Context, title: str) -> None:
"""Create a new post."""
newYorkTz = pytz.timezone("Europe/Istanbul")
now = datetime.now(newYorkTz)
new_post_path = POST_PATH.joinpath(
f"{now.strftime('%Y-%m-%d')}-{slugify(title)}.md"
)
new_post_path.touch()
with open(new_post_path, "w") as f:
f.write(
POST_TEMPLATE.format(
title=title,
slug=slugify(title),
timestamp=now.strftime("%Y-%m-%d %H:%M"),
)
)
print(f"Created new post at {new_post_path.relative_to(Path.cwd())}")
@duty(capture=CI)
def update(ctx: Context) -> None:
"""Update the project."""
ctx.run(
["uv", "lock", "--upgrade"],
title="update uv lock",
command="uv lock --upgrade",
)
ctx.run(
["pre-commit", "autoupdate"],
title="pre-commit autoupdate",
command="pre-commit autoupdate",
)
ctx.run(
[
"uv",
"-q",
"pip",
"compile",
"pyproject.toml",
"-o",
"requirements.txt",
],
title="update requirements.txt",
command="uv -q pip compile pyproject.toml -o requirements.txt",
)
@duty(capture=CI)
def lint(ctx: Context) -> None:
"""Run all linting duties."""
ctx.run(
["typos", "--config", ".typos.toml"],
title=pyprefix("typos check"),
command="typos --config .typos.toml",
)
ctx.run(
"djlint --configuration pyproject.toml theme",
title=pyprefix("djlint check"),
command="djlint --configuration pyproject.toml theme",
)
ctx.run(
"SKIP=typos,djlint pre-commit run --all-files",
title=pyprefix("pre-commit hooks"),
command="SKIP=typos,djlint pre-commit run --all-files",
)