Debian Codegraph @

duties.py

raw
1 """Development tasks."""
2
3 from __future__ import annotations
4
5 import os
6 import re
7 import sys
8 from pathlib import Path
9 from typing import TYPE_CHECKING
10
11 from duty import duty, tools
12
13 if TYPE_CHECKING:
14 from duty.context import Context
15
16
17 PY_SRC_PATHS = (Path(_) for _ in ("src", "tests", "duties.py", "scripts"))
18 PY_SRC_LIST = tuple(str(_) for _ in PY_SRC_PATHS)
19 PY_SRC = " ".join(PY_SRC_LIST)
20 CI = os.environ.get("CI", "0") in {"1", "true", "yes", ""}
21 WINDOWS = os.name == "nt"
22 PTY = not WINDOWS and not CI
23 MULTIRUN = os.environ.get("MULTIRUN", "0") == "1"
24 PY_VERSION = f"{sys.version_info.major}{sys.version_info.minor}"
25 PY_DEV = "315"
26
27
28 def pyprefix(title: str) -> str:
29 if MULTIRUN:
30 prefix = f"(python{sys.version_info.major}.{sys.version_info.minor})"
31 return f"{prefix:14}{title}"
32 return title
33
34
35 def _get_changelog_version() -> str:
36 changelog_version_re = re.compile(r"^## \[(\d+\.\d+\.\d+)\].*$")
37 with Path(__file__).parent.joinpath("CHANGELOG.md").open("r", encoding="utf8") as file:
38 return next(filter(bool, map(changelog_version_re.match, file))).group(1) # ty: ignore[unresolved-attribute]
39
40
41 @duty
42 def changelog(ctx: Context, bump: str = "") -> None:
43 """Update the changelog in-place with latest commits.
44
45 Parameters:
46 bump: Bump option passed to git-changelog.
47 """
48 ctx.run(tools.git_changelog(bump=bump or None), title="Updating changelog")
49 ctx.run(tools.yore.check(bump=bump or _get_changelog_version()), title="Checking legacy code")
50
51
52 @duty(pre=["check-quality", "check-types", "check-docs", "check-api"])
53 def check(ctx: Context) -> None:
54 """Check it all!"""
55
56
57 @duty(nofail=PY_VERSION == PY_DEV)
58 def check_quality(ctx: Context) -> None:
59 """Check the code quality."""
60 ctx.run(
61 tools.ruff.check(*PY_SRC_LIST, config="config/ruff.toml", color=True),
62 title=pyprefix("Checking code quality"),
63 )
64
65
66 @duty(nofail=PY_VERSION == PY_DEV)
67 def check_docs(ctx: Context) -> None:
68 """Check if the documentation builds correctly."""
69 ctx.run(
70 tools.zensical.build(strict=True),
71 title=pyprefix("Building documentation"),
72 )
73
74
75 @duty(nofail=PY_VERSION == PY_DEV)
76 def check_types(ctx: Context) -> None:
77 """Check that the code is correctly typed."""
78 py = f"{sys.version_info.major}.{sys.version_info.minor}"
79 ctx.run(
80 tools.ty.check(
81 *PY_SRC_LIST,
82 config_file="config/ty.toml",
83 color=True,
84 error_on_warning=True,
85 python_version=py,
86 ),
87 title=pyprefix("Type-checking"),
88 )
89
90
91 @duty(nofail=PY_VERSION == PY_DEV)
92 def check_api(ctx: Context, *cli_args: str) -> None:
93 """Check for API breaking changes."""
94 ctx.run(
95 tools.griffe.check("mkdocstrings", search=["src"], color=True).add_args(*cli_args),
96 title="Checking for API breaking changes",
97 nofail=True,
98 )
99
100
101 @duty
102 def docs(ctx: Context, *cli_args: str, host: str = "127.0.0.1", port: int = 8000) -> None:
103 """Serve the documentation (localhost:8000).
104
105 Parameters:
106 host: The host to serve the docs from.
107 port: The port to serve the docs on.
108 """
109 ctx.run(
110 tools.zensical.serve(dev_addr=f"{host}:{port}").add_args(*cli_args),
111 title="Serving documentation",
112 capture=False,
113 )
114
115
116 @duty
117 def docs_deploy(ctx: Context) -> None:
118 """Deploy the documentation to GitHub pages."""
119 from ghp_import import ghp_import # noqa: PLC0415
120
121 ctx.run(tools.zensical.build(), title="Building documentation site")
122 ctx.run(
123 ghp_import,
124 kwargs={
125 "srcdir": "site",
126 "mesg": "chore: Update documentation",
127 "push": True,
128 "force": True,
129 "remote": "org-pages",
130 },
131 title="Deploying site to GitHub Pages",
132 command="ghp-import site -r org-pages -fpm 'chore: Update documentation'",
133 pty=PTY,
134 )
135
136
137 @duty
138 def format(ctx: Context) -> None:
139 """Run formatting tools on the code."""
140 ctx.run(
141 tools.ruff.check(*PY_SRC_LIST, config="config/ruff.toml", fix_only=True, exit_zero=True),
142 title="Auto-fixing code",
143 )
144 ctx.run(tools.ruff.format(*PY_SRC_LIST, config="config/ruff.toml"), title="Formatting code")
145
146
147 @duty
148 def build(ctx: Context) -> None:
149 """Build source and wheel distributions."""
150 ctx.run(
151 ["uv", "build"],
152 title="Building distributions",
153 pty=PTY,
154 )
155
156
157 @duty
158 def publish(ctx: Context) -> None:
159 """Publish source and wheel distributions to PyPI."""
160 if not Path("dist").exists():
161 ctx.run("false", title="No distribution files found")
162 dists = [str(dist) for dist in Path("dist").iterdir() if dist.suffix in (".gz", ".whl")]
163 ctx.run(
164 tools.twine.upload(*dists, skip_existing=True),
165 title="Publishing distributions to PyPI",
166 pty=PTY,
167 )
168
169
170 @duty(post=["build", "publish", "docs-deploy"])
171 def release(ctx: Context, version: str = "") -> None:
172 """Release a new Python package.
173
174 Parameters:
175 version: The new version number to use.
176 """
177 if not (version := (version or input("> Version to release: ")).strip()):
178 ctx.run("false", title="A version must be provided")
179 ctx.run("git add pyproject.toml CHANGELOG.md", title="Staging files", pty=PTY)
180 ctx.run(["git", "commit", "-m", f"chore: Prepare release {version}"], title="Committing changes", pty=PTY)
181 ctx.run(f"git tag -m '' -a {version}", title="Tagging commit", pty=PTY)
182 ctx.run("git push", title="Pushing commits", pty=False)
183 ctx.run("git push --tags", title="Pushing tags", pty=False)
184
185
186 @duty(silent=True, aliases=["cov"])
187 def coverage(ctx: Context) -> None:
188 """Report coverage as text and HTML."""
189 ctx.run(tools.coverage.combine(), nofail=True)
190 ctx.run(tools.coverage.report(rcfile="config/coverage.ini"), capture=False)
191 ctx.run(tools.coverage.html(rcfile="config/coverage.ini"))
192
193
194 @duty(nofail=PY_VERSION == PY_DEV)
195 def test(ctx: Context, *cli_args: str) -> None:
196 """Run the test suite."""
197 os.environ["COVERAGE_FILE"] = f".coverage.{PY_VERSION}"
198 os.environ["PYTHONWARNDEFAULTENCODING"] = "1"
199 ctx.run(
200 tools.pytest(
201 "tests",
202 config_file="config/pytest.ini",
203 color="yes",
204 ).add_args("-n", "auto", *cli_args),
205 title=pyprefix("Running tests"),
206 )