Repository navigation
Expand file tree
/
Copy pathnoxfile.py
More file actions
765 lines (652 loc) · 24.9 KB
/
Copy pathnoxfile.py
File metadata and controls
765 lines (652 loc) · 24.9 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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# /// script
# dependencies = ["nox>=2025.02.09", "packaging"]
# ///
from __future__ import annotations
import argparse
import contextlib
import datetime
import difflib
import glob
import importlib.metadata
import io
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import textwrap
import time
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import IO, TYPE_CHECKING
import nox
import packaging.version # will always be present with nox
if TYPE_CHECKING:
from collections.abc import Generator
nox.needs_version = ">=2025.02.09"
nox.options.reuse_existing_virtualenvs = True
nox.options.default_venv_backend = "uv|virtualenv"
# Parallel mode added in modern nox
NOX_VERSION = packaging.version.Version(importlib.metadata.version("nox"))
if packaging.version.Version("2026.08.10") <= NOX_VERSION:
nox.options.allow_parallel = True
PYPROJECT = nox.project.load_toml("pyproject.toml")
PYTHON_VERSIONS = nox.project.python_versions(PYPROJECT)
# hypothesis 6.156+ ships as a maturin/pyo3 project without wheels for PyPy or
# free-threaded CPython, so building from the sdist fails there. Restrict it to
# binaries so uv/pip picks the newest version with a compatible wheel instead.
HYPOTHESIS_BINARY_ONLY = ("--only-binary", "hypothesis")
# Interpreters that run the tests without coverage, because tracing is too slow
# there: PyPy, and free-threaded 3.13, which has no fast C tracer.
NO_COVERAGE = {"pypy", "3.13t"}
@nox.session(
python=[
*PYTHON_VERSIONS,
"3.13t",
"3.14t",
"3.15t",
"pypy3.10",
"pypy3.11",
],
default=False,
)
def tests(session: nox.Session) -> None:
"""
Run the tests, with coverage.
"""
assert session.python is not None
assert not isinstance(session.python, bool)
parser = argparse.ArgumentParser(prog="nox -s tests --")
parser.add_argument(
"--coverage",
action=argparse.BooleanOptionalAction,
default=not any(x in session.python for x in NO_COVERAGE),
help="Run the tests under coverage.",
)
args, posargs = parser.parse_known_args(session.posargs)
coverage = ["python", "-m", "coverage"]
session.install(
*HYPOTHESIS_BINARY_ONLY, *nox.project.dependency_groups(PYPROJECT, "test")
)
session.install("-e.")
# Give each session its own data file so parallel sessions don't fight over
# the default ".coverage".
env = {"COVERAGE_FILE": str(Path.cwd() / f".coverage.{session.python}")}
if session.python == "3.14":
env["COVERAGE_CORE"] = "sysmon"
# Property tests are marked with @pytest.mark.property and are excluded by default
# via pyproject.toml. Run the regular test suite normally; property tests can be
# run explicitly with `pytest -m property` or the `property_tests` nox session.
if args.coverage:
session.run(
*coverage,
"run",
"-m",
"pytest",
*posargs,
env=env,
)
session.run(*coverage, "report", env=env)
else:
session.run(
"python",
"-m",
"pytest",
"--capture=no",
*posargs,
)
@nox.session(default=False)
def property_tests(session: nox.Session) -> None:
"""
Run property-based tests (no coverage).
"""
session.install(
*HYPOTHESIS_BINARY_ONLY, *nox.project.dependency_groups(PYPROJECT, "test")
)
session.install("-e.")
session.run(
"python",
"-m",
"pytest",
"-m",
"property",
*session.posargs,
)
# A few of the pinned releases break under pytest 9.1.0 (released 2026-06-13)
PYTEST_910_CUTOFF = "2026-06-12 00:00:00Z"
@dataclass(frozen=True)
class Project:
url: str
install: tuple[str, ...] = ("-e.", "--group=test")
install_env: dict[str, str] | None = None
swap: tuple[str, ...] = ()
pytest_args: tuple[str, ...] = ()
extra_env: dict[str, str | None] | None = None
date_limit: bool = False
PROJECTS = {
"packaging_legacy": Project(
"https://github.com/di/packaging_legacy/archive/refs/tags/23.0.post0.tar.gz",
install=("-r", "tests/requirements.txt", "-e."),
date_limit=True,
),
"build": Project(
"https://github.com/pypa/build/archive/refs/tags/1.5.0.tar.gz",
date_limit=True,
),
"setuptools": Project(
"https://github.com/pypa/setuptools/archive/refs/tags/v82.0.0.tar.gz",
install=("-e.[test,cover]",),
swap=("setuptools/_vendor/packaging",),
pytest_args=(
"-k",
"not test_editable_install and not test_editable_with_pyproject",
),
date_limit=True,
),
"pyproject_metadata": Project(
"https://github.com/pypa/pyproject-metadata/archive/refs/tags/0.11.0.tar.gz",
date_limit=True,
),
"pip": Project(
"https://github.com/pypa/pip/archive/refs/tags/26.0.1.tar.gz",
swap=("src/pip/_vendor/packaging",),
pytest_args=(
"tests/unit",
"--numprocesses=auto",
"-k",
"not test_ensure_svn_available",
),
date_limit=True,
),
"dependency_groups": Project(
"https://github.com/pypa/dependency-groups/archive/refs/tags/1.3.1.tar.gz",
),
"dep_logic": Project(
"https://github.com/pdm-project/dep-logic/archive/refs/tags/0.6.0.tar.gz",
install=("-e.", "pytest"),
install_env={"PDM_BUILD_SCM_VERSION": "0.6.0"},
),
"twine": Project(
"https://github.com/pypa/twine/archive/refs/tags/7.0.0.tar.gz",
# twine keeps its test deps in tox.ini rather than a [test] extra.
install=("-e.", "pretend", "pytest", "pytest-socket", "coverage"),
install_env={"SETUPTOOLS_SCM_PRETEND_VERSION": "7.0.0"},
# test_fails_rst_no_content expects an RST document with only a title
# to render as empty, which readme_renderer 46 changed; unrelated to
# packaging.
pytest_args=("-k", "not test_fails_rst_no_content"),
),
"cibuildwheel": Project(
"https://github.com/pypa/cibuildwheel/archive/refs/tags/v4.1.0.tar.gz",
# unit_test/ is the fast suite; test/ holds slow Docker integration tests.
pytest_args=("unit_test",),
),
"hatchling": Project(
"https://github.com/pypa/hatch/archive/refs/tags/hatchling-v1.31.0.tar.gz",
# hatchling lives in the hatch monorepo; its backend tests rely on the
# full hatch package and its fixtures.
install=(
"-e./backend",
"-e.",
"pytest",
"pytest-mock",
"filelock",
"editables",
),
install_env={"SETUPTOOLS_SCM_PRETEND_VERSION": "1.31.0"},
# test_binary downloads a PyApp binary over the network.
# See https://github.com/pypa/hatch/issues/2319.
# hatchling ships no pytest config, so from nox's tmp dir inside this
# checkout pytest makes packaging's own directory the rootdir. Node IDs
# then carry a .nox/... prefix, which silently breaks --deselect.
pytest_args=(
"tests/backend",
"--rootdir=.",
"--ignore=tests/backend/builders/test_binary.py",
),
),
"tox": Project(
"https://github.com/tox-dev/tox/archive/refs/tags/4.67.9.tar.gz",
# argcomplete is an optional dep that several tests import at collection.
install=("-e.", "--group=test", "argcomplete"),
install_env={"SETUPTOOLS_SCM_PRETEND_VERSION": "4.67.9"},
# packaging rejects the test's newline URL before tox's validation runs.
pytest_args=(
"-m",
"not integration",
"--deselect=tests/tox_env/python/pip/test_req_file.py::"
"test_provision_requirement_entry_cannot_change_lines[line-break]",
),
# In CI, tox appends a pip-freeze line to command output, which several
# output-asserting tests do not expect. Unset every variable its is_ci()
# (tox/util/ci.py) checks that GitHub Actions sets.
extra_env={"CI": None, "GITHUB_ACTIONS": None},
),
"virtualenv": Project(
"https://github.com/pypa/virtualenv/archive/refs/tags/21.15.5.tar.gz",
install_env={"SETUPTOOLS_SCM_PRETEND_VERSION": "21.15.5"},
),
"pdm": Project(
"https://github.com/pdm-project/pdm/archive/refs/tags/2.29.7.tar.gz",
install_env={"PDM_BUILD_SCM_VERSION": "2.29.7"},
pytest_args=("-m", "not network and not integration"),
),
"poetry_core": Project(
"https://github.com/python-poetry/poetry-core/archive/refs/tags/2.4.1.tar.gz",
# poetry-core uses poetry-native dependency groups, so its test deps are
# not pip-installable as an extra; install them explicitly. setuptools is
# needed to build its C-extension test fixtures.
install=(
"-e.",
"pytest",
"pytest-mock",
"build",
"setuptools",
"tomli-w",
"virtualenv",
"trove-classifiers",
),
# poetry-core vendors packaging under _vendor and injects it onto sys.path.
swap=("src/poetry/core/_vendor/packaging",),
pytest_args=("tests",),
),
"pipenv": Project(
"https://github.com/pypa/pipenv/archive/refs/tags/v2026.6.2.tar.gz",
install=("-e.[tests]",),
# pipenv vendors packaging twice: its own vendor tree and the patched pip.
swap=("pipenv/vendor/packaging", "pipenv/patched/pip/_vendor/packaging"),
# test_vendor.py asserts vendoring integrity (and needs pytz), so it is
# expected to fail after the swap. pipenv's addopts enable --no-cov, which
# errors without pytest-cov; replace them.
pytest_args=(
"tests/unit",
"--ignore=tests/unit/test_vendor.py",
"-o",
"addopts=-ra",
),
),
}
@nox.parametrize("project", list(PROJECTS))
@nox.session(default=False)
def downstream(session: nox.Session, project: str) -> None:
"""
Run downstream projects with this packaging.
"""
cfg = PROJECTS[project]
pkg_dir = Path.cwd() / "src/packaging"
# virtualenv's relocation tests copy the files listed in packaging's RECORD.
session.install(".")
tmp_dir = Path(session.create_tmp())
session.chdir(tmp_dir)
shutil.rmtree(project, ignore_errors=True)
with urllib.request.urlopen(cfg.url) as resp:
data = resp.read()
with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as tf:
tf.extractall(project)
project_path = Path(project)
(inner_dir,) = project_path.iterdir()
# Make sure pytest doesn't keep searching upwards for config
project_path.joinpath("pytest.ini").touch()
session.chdir(inner_dir)
pip_cmd = ["uv", "pip"] if session.venv_backend == "uv" else ["pip"]
if cfg.date_limit:
# See PYTEST_910_CUTOFF: cap resolution so these projects pull a pytest
# they support, on both backends.
session.env["UV_EXCLUDE_NEWER"] = PYTEST_910_CUTOFF
session.env["PIP_UPLOADED_PRIOR_TO"] = PYTEST_910_CUTOFF
# nox points TMPDIR inside this git checkout, so downstream tools that walk up
# the tree (hatchling's VCS sdist builder, tox/pdm config discovery) find
# packaging's own repo metadata and misbehave. Keep the test temp dir outside.
test_env: dict[str, str | None] = {
"FORCE_COLOR": None,
"TMPDIR": tempfile.mkdtemp(prefix="downstream-"),
}
if cfg.extra_env:
test_env |= cfg.extra_env
session.install(*cfg.install, env=cfg.install_env)
if project == "pip":
# pip needs its common test wheels built before its vendored copy of
# packaging is swapped out.
session.run(
"pip",
"wheel",
"-w",
"tests/data/common_wheels",
"--group",
"test-common-wheels",
)
for repl_dir in cfg.swap:
# Replace the vendored packaging with the current source. Its relative
# imports keep it self-contained under any vendor namespace.
shutil.rmtree(repl_dir)
shutil.copytree(pkg_dir, repl_dir)
session.run(*pip_cmd, "list")
session.run("pytest", *cfg.pytest_args, *session.posargs, env=test_env)
@nox.session(python="3.10")
def lint(session: nox.Session) -> None:
"""
Run the linters.
"""
session.install("prek", "build", "twine")
# Run the linters (via prek, a Rust pre-commit runner)
session.run("prek", "run", "--all-files", *session.posargs)
# Check the distribution. Build into the session temp dir, so this does not
# collide with the "dist/" the release sessions manage.
out_dir = Path(session.create_tmp()) / "dist"
session.run("pyproject-build", "--outdir", str(out_dir))
session.run("twine", "check", *glob.glob(f"{out_dir}/*"))
@nox.session(default=False)
def docs(session: nox.Session) -> None:
"""
Build the docs.
"""
shutil.rmtree("docs/_build", ignore_errors=True)
session.install(*nox.project.dependency_groups(PYPROJECT, "docs"))
session.install("-e.")
variants = [
# (builder, dest)
("html", "html"),
("latex", "latex"),
("doctest", "html"),
]
for builder, dest in variants:
session.run(
"sphinx-build",
"-W",
"-n",
"-b",
builder,
"-d",
"docs/_build/doctrees/" + dest,
"docs", # source directory
"docs/_build/" + dest, # output directory
)
session.log(
"Finished! If you want to view at http://localhost:8000, try:\n"
" python3 -m http.server -d docs/_build/html/"
)
@nox.session(default=False)
def release(session: nox.Session) -> None:
"""
Give a version number to use as tag.
"""
package_name = "packaging"
version_file = Path(f"src/{package_name}/__init__.py")
changelog_file = Path("CHANGELOG.rst")
try:
release_version = _get_version_from_arguments(session.posargs)
except ValueError as e:
session.error(f"Invalid arguments: {e}")
return
# Check state of working directory and git.
_check_working_directory_state(session)
_check_git_state(session, release_version)
# Prepare for release.
_changelog_update_unreleased_title(release_version, file=changelog_file)
session.run("git", "add", str(changelog_file), external=True)
_bump(session, version=release_version, file=version_file, kind="release")
# Check the built distribution.
_build_and_check(session, release_version, remove=True)
# Tag the release commit.
# fmt: off
session.run(
"git", "tag",
"-s", release_version,
"-m", f"Release {release_version}",
external=True,
)
# fmt: on
# Prepare for development.
_changelog_add_unreleased_title(file=changelog_file)
session.run("git", "add", str(changelog_file), external=True)
rel_ver = packaging.version.Version(release_version)
next_version = f"{rel_ver.major}.{rel_ver.minor + 1}.dev0"
_bump(session, version=next_version, file=version_file, kind="development")
# Push the commits and tag.
# NOTE: The following fails if pushing to the branch is not allowed. This can
# happen on GitHub, if the main branch is protected, there are required
# CI checks and "Include administrators" is enabled on the protection.
session.log("Run the following to push changes and tag (assuming 'upstream')")
print()
print(f" git push upstream main {release_version}")
print()
@nox.session(default=False)
def release_build(session: nox.Session) -> None:
"""
Build version from command-line arguments otherwise current Git tag.
"""
release_version: str | None
try:
release_version = _get_version_from_arguments(session.posargs)
except ValueError as e:
if session.posargs:
session.error(f"Invalid arguments: {e}")
release_version = session.run(
"git", "describe", "--exact-match", silent=True, external=True
)
release_version = "" if release_version is None else release_version.strip()
session.debug(f"version: {release_version}")
checkout = False
else:
checkout = True
# Check state of working directory.
_check_working_directory_state(session)
# Ensure there are no uncommitted changes.
result = subprocess.run(
["git", "status", "--porcelain"],
check=False,
capture_output=True,
encoding="utf-8",
)
if result.stdout:
print(result.stdout, end="", file=sys.stderr)
session.error("The working tree has uncommitted changes")
# Check out the Git tag, if provided.
if checkout:
session.run("git", "switch", "--detach", "-q", release_version, external=True)
# Build the distribution.
_build_and_check(session, release_version)
# Get back out into main, if we checked out before.
if checkout:
session.run("git", "switch", "-q", "main", external=True)
@nox.session(default=False)
def update_licenses(session: nox.Session) -> None:
"""
Update licenses.
"""
session.install("httpx")
session.run("python", "tasks/licenses.py")
@nox.session(default=False)
@nox.parametrize("version", ["21.0", "24.0", "25.0", "26.0", "26.1", "26.2", "26.3"])
def test_pickle(session: nox.Session, version: str) -> None:
"""
Make sure pickles written by an older packaging release can be read
by the current code.
"""
tmp_dir = Path(session.create_tmp())
pickle_file = tmp_dir / f"packaging_{version}_pickles.pkl"
# Step 1: install the old release so the generator pickles objects in
# the format that version serialises.
session.install(f"packaging=={version}")
session.run(
"python",
"tasks/pickle_compat.py",
"write",
version,
str(tmp_dir),
)
# Step 2: install the current (in-tree) packaging so we can verify
# backward compatibility of the load path.
session.install("-e.")
session.run(
"python",
"tasks/pickle_compat.py",
"verify",
"--version",
version,
str(pickle_file),
)
# -----------------------------------------------------------------------------
# Helpers
# -----------------------------------------------------------------------------
def _build_and_check(
session: nox.Session,
release_version: str,
remove: bool = False,
) -> None:
package_name = "packaging"
session.install("build", "twine")
# Determine if we're in install-only mode. This works as `python --version`
# should always succeed when running `nox`, but in install-only mode
# `session.run(..., silent=True)` always immediately returns `None` instead
# of invoking the command and returning the command's output. See the
# documentation at:
# https://nox.thea.codes/en/stable/usage.html#skipping-everything-but-install-commands
install_only = session.run("python", "--version", silent=True) is None
# Build the distribution.
session.run("python", "-m", "build")
# Check what files are in dist/ for upload.
files = sorted(glob.glob("dist/*"))
expected = [
f"dist/{package_name}-{release_version}-py3-none-any.whl",
f"dist/{package_name}-{release_version}.tar.gz",
]
if files != expected and not install_only:
diff_generator = difflib.context_diff(
expected, files, fromfile="expected", tofile="got", lineterm=""
)
diff = "\n".join(diff_generator)
session.error(f"Got the wrong files:\n{diff}")
# Check distribution files.
session.run("twine", "check", "--strict", *files)
# Remove distribution files, if requested.
if remove and not install_only:
shutil.rmtree("dist", ignore_errors=True)
def _get_version_from_arguments(arguments: list[str]) -> str:
"""Checks the arguments passed to `nox -s release`.
Only 1 argument that looks like a version? Return the argument.
Otherwise, raise a ValueError describing what's wrong.
"""
if len(arguments) != 1:
raise ValueError("Expected exactly 1 argument")
version = arguments[0]
parts = version.split(".")
if len(parts) != 2:
# Not of the form: YY.N
raise ValueError("not of the form: YY.N")
norm_version = str(packaging.version.Version(version))
if norm_version != version:
raise ValueError(f"Must be normalized version {norm_version!r}")
# All is good.
return version
def _check_working_directory_state(session: nox.Session) -> None:
"""Check state of the working directory, prior to making the release."""
should_not_exist = ["build/", "dist/"]
bad_existing_paths = list(filter(os.path.exists, should_not_exist))
if bad_existing_paths:
session.error(f"Remove {', '.join(bad_existing_paths)} and try again")
def _check_git_state(session: nox.Session, version_tag: str) -> None:
"""Check state of the git repository, prior to making the release."""
# Ensure the upstream remote pushes to the correct URL.
allowed_upstreams = [
"git@github.com:pypa/packaging.git",
"https://github.com/pypa/packaging.git",
]
result = subprocess.run(
["git", "remote", "get-url", "--push", "upstream"],
check=False,
capture_output=True,
encoding="utf-8",
)
if result.stdout.rstrip() not in allowed_upstreams:
session.error(f"git remote `upstream` is not one of {allowed_upstreams}")
# Ensure we're on main branch for cutting a release.
result = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
check=False,
capture_output=True,
encoding="utf-8",
)
if result.stdout != "main\n":
session.error(f"Not on main branch: {result.stdout!r}")
# Ensure there are no uncommitted changes.
result = subprocess.run(
["git", "status", "--porcelain"],
check=False,
capture_output=True,
encoding="utf-8",
)
if result.stdout:
print(result.stdout, end="", file=sys.stderr)
session.error("The working tree has uncommitted changes")
# Ensure this tag doesn't exist already.
result = subprocess.run(
["git", "rev-parse", version_tag],
check=False,
capture_output=True,
encoding="utf-8",
)
if not result.returncode:
session.error(f"Tag already exists! {version_tag} -- {result.stdout!r}")
# Back up the current git reference, in a tag that's easy to clean up.
_release_backup_tag = "auto/release-start-" + str(int(time.time()))
session.run("git", "tag", _release_backup_tag, external=True)
def _bump(session: nox.Session, *, version: str, file: Path, kind: str) -> None:
session.log(f"Bump version to {version!r}")
contents = file.read_text()
new_contents = re.sub(
'__version__ = "(.+)"', f'__version__ = "{version}"', contents
)
file.write_text(new_contents)
session.log("git commit")
subprocess.run(["git", "add", str(file)], check=False)
subprocess.run(["git", "commit", "-m", f"Bump for {kind}"], check=False)
@contextlib.contextmanager
def _replace_file(
original_path: Path,
) -> Generator[tuple[IO[str], IO[str]]]:
# Create a temporary file.
fh, replacement_path = tempfile.mkstemp()
with os.fdopen(fh, "w") as replacement, open(original_path) as original:
yield original, replacement
shutil.copymode(original_path, replacement_path)
os.remove(original_path)
shutil.move(replacement_path, original_path)
def _changelog_update_unreleased_title(version: str, *, file: Path) -> None:
"""Update an "*unreleased*" heading to "{version} - {date}" """
yyyy_mm_dd = datetime.datetime.now(tz=datetime.timezone.utc).strftime("%Y-%m-%d")
title = f"{version} - {yyyy_mm_dd}"
with _replace_file(file) as (original, replacement):
for line in original:
if line == "*unreleased*\n":
replacement.write(f"{title}\n")
replacement.write(len(title) * "~" + "\n")
# Skip processing the next line (the heading underline for *unreleased*)
# since we already wrote the heading underline.
next(original)
else:
replacement.write(line)
def _changelog_add_unreleased_title(*, file: Path) -> None:
with _replace_file(file) as (original, replacement):
# Duplicate first 3 lines from the original file.
for _ in range(3):
line = next(original)
replacement.write(line)
# Write the heading.
replacement.write(
textwrap.dedent(
"""\
*unreleased*
~~~~~~~~~~~~
No unreleased changes.
"""
)
)
# Duplicate all the remaining lines.
for line in original:
replacement.write(line)
if __name__ == "__main__":
nox.main()