Repository navigation
Expand file tree
/
Copy pathtasks.py
More file actions
557 lines (450 loc) · 14.3 KB
/
Copy pathtasks.py
File metadata and controls
557 lines (450 loc) · 14.3 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
"""
Invoke - Tasks
==============
"""
from __future__ import annotations
import contextlib
import fnmatch
import inspect
import os
import re
import shutil
import sys
import tarfile
import tomllib
import typing
import uuid
from pathlib import Path
from shlex import quote
from tempfile import TemporaryDirectory
import biblib.bib
from colour.utilities import message_box
import colour_datasets
if not hasattr(inspect, "getargspec"):
inspect.getargspec = inspect.getfullargspec # pyright: ignore
if typing.TYPE_CHECKING:
from invoke.context import Context
from invoke.tasks import task
__author__ = "Colour Developers"
__copyright__ = "Copyright 2019 Colour Developers"
__license__ = "BSD-3-Clause - https://opensource.org/licenses/BSD-3-Clause"
__maintainer__ = "Colour Developers"
__email__ = "colour-developers@colour-science.org"
__status__ = "Production"
__all__ = [
"APPLICATION_NAME",
"APPLICATION_VERSION",
"PYTHON_PACKAGE_NAME",
"PYPI_PACKAGE_NAME",
"PYPI_ARCHIVE_NAME",
"BIBLIOGRAPHY_NAME",
"clean",
"formatting",
"quality",
"prek",
"tests",
"examples",
"preflight",
"docs",
"todo",
"requirements",
"build",
"virtualise",
"tag",
"pre_release",
"release",
"sha256",
]
APPLICATION_NAME: str = colour_datasets.__application_name__
APPLICATION_VERSION: str = colour_datasets.__version__
PYTHON_PACKAGE_NAME: str = colour_datasets.__name__
PYPI_PACKAGE_NAME: str = "colour-datasets"
PYPI_ARCHIVE_NAME: str = PYPI_PACKAGE_NAME.replace("-", "_")
BIBLIOGRAPHY_NAME: str = "BIBLIOGRAPHY.bib"
@task
def clean(
ctx: Context,
docs: bool = True,
bytecode: bool = False,
pytest: bool = True,
) -> None:
"""
Clean the project.
Parameters
----------
ctx
Context.
docs
Whether to clean the *docs* directory.
bytecode
Whether to clean the bytecode files, e.g., *.pyc* files.
pytest
Whether to clean the *Pytest* cache directory.
"""
message_box("Cleaning project...")
patterns = ["build", "*.egg-info", "dist"]
if docs:
patterns.append("docs/_build")
patterns.append("docs/generated")
if bytecode:
patterns.append("**/__pycache__")
patterns.append("**/*.pyc")
if pytest:
patterns.append(".pytest_cache")
for pattern in patterns:
ctx.run(f"rm -rf {pattern}")
@task
def formatting(
ctx: Context,
asciify: bool = True,
bibtex: bool = True,
) -> None:
"""
Convert unicode characters to ASCII and cleanup the *BibTeX* file.
Parameters
----------
ctx
Context.
asciify
Whether to convert unicode characters to ASCII.
bibtex
Whether to cleanup the *BibTeX* file.
"""
if asciify:
message_box("Converting unicode characters to ASCII...")
with ctx.cd("utilities"):
ctx.run("./unicode_to_ascii.py")
if bibtex:
message_box('Cleaning up "BibTeX" file...')
bibtex_path = BIBLIOGRAPHY_NAME
with open(bibtex_path) as bibtex_file:
entries = biblib.bib.Parser().parse(bibtex_file.read()).get_entries()
for entry in sorted(entries.values(), key=lambda x: x.key):
with contextlib.suppress(KeyError):
del entry["file"]
for key, value in entry.items():
entry[key] = re.sub("(?<!\\\\)\\&", "\\&", value)
with open(bibtex_path, "w") as bibtex_file:
for entry in sorted(entries.values(), key=lambda x: x.key):
bibtex_file.write(entry.to_bib())
bibtex_file.write("\n")
@task
def quality(
ctx: Context,
pyright: bool = True,
rstlint: bool = True,
) -> None:
"""
Check the codebase with *Pyright* and lints various *restructuredText*
files with *rst-lint*.
Parameters
----------
ctx
Context.
pyright
Whether to check the codebase with *Pyright*.
rstlint
Whether to lint various *restructuredText* files with *rst-lint*.
"""
if pyright:
message_box('Checking codebase with "Pyright"...')
ctx.run("pyright --threads --skipunannotated --level warning")
if rstlint:
message_box('Linting "README.rst" file...')
ctx.run("rst-lint README.rst")
@task
def prek(ctx: Context) -> None:
"""
Run the "prek" hooks on the codebase.
Parameters
----------
ctx
Context.
"""
message_box('Running "prek" hooks on the codebase...')
ctx.run("prek run --all-files")
@task
def tests(ctx: Context) -> None:
"""
Run the unit tests with *Pytest*.
Parameters
----------
ctx
Context.
"""
message_box('Running "Pytest"...')
ctx.run(
"pytest "
"--doctest-modules "
f"--ignore={PYTHON_PACKAGE_NAME}/examples "
f"--cov={PYTHON_PACKAGE_NAME} "
f"{PYTHON_PACKAGE_NAME}"
)
@task
def examples(ctx: Context) -> None:
"""
Run the examples.
Parameters
----------
ctx
Context.
"""
message_box("Running examples...")
with TemporaryDirectory(prefix="colour-datasets-examples-") as repository:
for root, _dirnames, filenames in os.walk(
os.path.join(PYTHON_PACKAGE_NAME, "examples")
):
for filename in fnmatch.filter(filenames, "*.py"):
ctx.run(
f"python {os.path.join(root, filename)}",
env={"COLOUR_SCIENCE__COLOUR_DATASETS__REPOSITORY": repository},
)
@task(formatting, quality, prek, tests, examples)
def preflight(ctx: Context) -> None: # noqa: ARG001
"""
Perform the preflight tasks.
Parameters
----------
ctx
Context.
"""
message_box('Finishing "Preflight"...')
@task
def docs(ctx: Context, html: bool = True, pdf: bool = True) -> None:
"""
Build the documentation.
Parameters
----------
ctx
Context.
html
Whether to build the *HTML* documentation.
pdf
Whether to build the *PDF* documentation.
"""
with ctx.prefix("export COLOUR_SCIENCE__DOCUMENTATION_BUILD=True"), ctx.cd("docs"):
if html:
message_box('Building "HTML" documentation...')
ctx.run("make html SPHINXOPTS='-W --keep-going'")
if pdf:
message_box('Building "PDF" documentation...')
ctx.run("make latexpdf SPHINXOPTS='-W --keep-going'")
@task
def todo(ctx: Context) -> None:
"""
Export the TODO items.
Parameters
----------
ctx
Context.
"""
message_box('Exporting "TODO" items...')
with ctx.cd("utilities"):
ctx.run("./export_todo.py")
@task
def requirements(ctx: Context) -> None:
"""
Export the *requirements.txt* file.
Parameters
----------
ctx
Context.
"""
message_box('Exporting "requirements.txt" file...')
ctx.run(
"uv export --no-hashes --all-extras --no-emit-project "
"--output-file requirements.txt"
)
message_box('Exporting "docs/requirements.txt" file...')
ctx.run(
"uv export --no-hashes --all-extras --no-dev --no-emit-project "
"--output-file docs/requirements.txt"
)
@task(clean, preflight, docs, todo, requirements)
def build(ctx: Context) -> None:
"""
Build the project and runs dependency tasks.
Parameters
----------
ctx
Context.
"""
message_box("Building...")
status = ctx.run("git status --porcelain -- README.rst", hide="both")
if status is not None and status.stdout.strip():
error = 'Please commit your changes to the "README.rst" file!'
raise RuntimeError(error)
readme_path = Path("README.rst")
original_readme = readme_path.read_bytes()
readme_content = original_readme.decode("utf-8")
readme_content = re.sub(
r"(\.\. begin-trim-long-description.*?\.\. end-trim-long-description)",
"",
readme_content,
flags=re.DOTALL,
)
try:
readme_path.write_text(readme_content, encoding="utf-8", newline="")
ctx.run("uv build")
finally:
readme_path.write_bytes(original_readme)
ctx.run("twine check dist/*.whl dist/*.tar.gz")
@task
def virtualise(ctx: Context, tests: bool = True) -> None:
"""
Build a wheel from the source distribution and validate its installation.
The wheel is installed in a fresh environment. Tests run outside the source
tree with isolated Python imports, so an editable checkout cannot mask
missing files or dependencies in the release artifacts.
Parameters
----------
ctx
Context.
tests
Whether to run tests on the virtual environment.
"""
archive = Path(
"dist", f"{PYPI_ARCHIVE_NAME}-{APPLICATION_VERSION}.tar.gz"
).resolve()
directory = archive.parent / f"{PYPI_PACKAGE_NAME}-{uuid.uuid4()}"
directory.mkdir()
with tarfile.open(archive) as distribution:
distribution.extractall(directory, filter="data")
project = directory / f"{PYPI_ARCHIVE_NAME}-{APPLICATION_VERSION}"
wheels = directory / "wheels"
ctx.run(f"uv build --wheel --out-dir {quote(str(wheels))} {quote(str(project))}")
wheel = next(wheels.glob("*.whl"))
environment = directory / ".venv"
ctx.run(f"uv venv --python {quote(sys.executable)} {quote(str(environment))}")
python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
interpreter = quote(str(python))
configuration = tomllib.loads((project / "pyproject.toml").read_text())
extras = ",".join(configuration["project"].get("optional-dependencies", {}))
package = f"{wheel}[{extras}]" if extras else str(wheel)
group = (
f" --group {quote(str(project / 'pyproject.toml') + ':dev')}" if tests else ""
)
ctx.run(f"uv pip install --python {interpreter} {quote(package)}{group}")
ctx.run(f"uv pip check --python {interpreter}")
checks = directory / "checks"
checks.mkdir()
shutil.copyfile(project / "pyproject.toml", checks / "pyproject.toml")
if (project / "conftest.py").exists():
shutil.copyfile(project / "conftest.py", checks / "conftest.py")
with ctx.cd(str(checks)):
code = (
f"import importlib.metadata; import {PYTHON_PACKAGE_NAME}; "
f"assert importlib.metadata.version('{PYPI_PACKAGE_NAME}') "
f"== '{APPLICATION_VERSION}'; print({PYTHON_PACKAGE_NAME}.__file__)"
)
result = ctx.run(f"{interpreter} -I -OO -c {quote(code)}", hide="both")
if result is None:
msg = "Could not locate the installed distribution."
raise RuntimeError(msg)
installed = Path(result.stdout.strip()).parent
if not installed.is_relative_to(environment):
msg = f"Package imported outside the validation environment: {installed}"
raise RuntimeError(msg)
ctx.run(
f"{interpreter} -I -c "
+ quote("import imageio; imageio.plugins.freeimage.download()")
)
if tests:
ctx.run(
f"{interpreter} -I -m pytest --import-mode=append "
f"--doctest-modules --ignore={quote(str(installed / 'examples'))} "
f"--pyargs {PYTHON_PACKAGE_NAME}",
env={"MPLBACKEND": "AGG", "OMP_NUM_THREADS": "1"},
)
@task
def tag(ctx: Context, remote_name: str = "upstream") -> None:
"""
Tag the repository according to defined version using *git-flow*.
Parameters
----------
ctx
Context.
remote_name
Name of the remote repository.
"""
message_box("Tagging...")
result = ctx.run("git rev-parse --abbrev-ref HEAD", hide="both")
if result is None or result.stdout.strip() != "develop":
error = "Are you still on a feature or master branch?"
raise RuntimeError(error)
with open(os.path.join(PYTHON_PACKAGE_NAME, "__init__.py")) as file_handle:
file_content = file_handle.read()
major_version = re.search(
'__major_version__\\s+=\\s+"(.*)"', file_content
).group( # pyright: ignore
1
)
minor_version = re.search(
'__minor_version__\\s+=\\s+"(.*)"', file_content
).group( # pyright: ignore
1
)
change_version = re.search(
'__change_version__\\s+=\\s+"(.*)"', file_content
).group( # pyright: ignore
1
)
version = f"{major_version}.{minor_version}.{change_version}"
result = ctx.run(
f"git ls-remote --tags --refs {quote(remote_name)}", hide="both"
)
if result is None:
error = "Failed to list remote tags."
raise RuntimeError(error)
tags = {
ref.removeprefix("refs/tags/").removesuffix("^{}")
for line in result.stdout.splitlines()
if (ref := line.partition("\t")[2]).startswith("refs/tags/")
}
if f"v{version}" in tags:
error = (
f'A "{PYTHON_PACKAGE_NAME}" "v{version}" tag already exists in '
f"remote repository!"
)
raise RuntimeError(error)
ctx.run(f"git flow release start v{version}")
ctx.run(f"git flow release finish v{version}")
@task(build)
def release(ctx: Context) -> None:
"""
Release the project to *Pypi* with *Twine*.
Parameters
----------
ctx
Context.
"""
message_box("Releasing...")
with ctx.cd("dist"):
ctx.run("twine upload *.tar.gz")
ctx.run("twine upload *.whl")
@task
def sha256(ctx: Context) -> None:
"""
Compute the project *Pypi* package *sha256* with *OpenSSL*.
Parameters
----------
ctx
Context.
"""
message_box('Computing "sha256"...')
with ctx.cd("dist"):
ctx.run(
f"openssl sha256 {PYPI_ARCHIVE_NAME}-*.tar.gz {PYPI_ARCHIVE_NAME}-*.whl"
)
@task(build, virtualise, sha256)
def pre_release(ctx: Context) -> None: # noqa: ARG001
"""
Validate the complete pre-release workflow without tagging or publishing.
Run ``uv sync --all-extras`` followed by ``uv run invoke pre-release``.
A current TeX installation is required for the HTML and PDF documentation.
Parameters
----------
ctx
Context.
"""
message_box("Pre-release validation complete.")