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 = "314"
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) # type: ignore[union-attr]
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"),
62 title=pyprefix("Checking code quality"),
63 )
64
65
66 @duty(
67 nofail=PY_VERSION == PY_DEV,
68 skip_if=sys.version_info < (3, 13),
69 skip_reason=pyprefix("Skipped: docs require modern generics syntax"),
70 )
71 def check_docs(ctx: Context) -> None:
72 """Check if the documentation builds correctly."""
73 Path("htmlcov").mkdir(parents=True, exist_ok=True)
74 Path("htmlcov/index.html").touch(exist_ok=True)
75 ctx.run(
76 tools.mkdocs.build(strict=True, verbose=True),
77 title=pyprefix("Building documentation"),
78 )
79
80
81 @duty(nofail=True)
82 def check_types(ctx: Context) -> None:
83 """Check that the code is correctly typed."""
84 os.environ["MYPYPATH"] = "src"
85 os.environ["FORCE_COLOR"] = "1"
86 ctx.run(
87 tools.mypy(*PY_SRC_LIST, config_file="config/mypy.ini"),
88 title=pyprefix("Type-checking"),
89 )
90
91
92 @duty(nofail=PY_VERSION == PY_DEV)
93 def check_api(ctx: Context, *cli_args: str) -> None:
94 """Check for API breaking changes."""
95 ctx.run(
96 tools.griffe.check("mkdocstrings_handlers.python", search=["src"], color=True).add_args(*cli_args),
97 title="Checking for API breaking changes",
98 nofail=True,
99 )
100
101
102 @duty(skip_if=sys.version_info < (3, 13), skip_reason=pyprefix("Skipped: docs require modern generics syntax"))
103 def docs(ctx: Context, *cli_args: str, host: str = "127.0.0.1", port: int = 8000) -> None:
104 """Serve the documentation (localhost:8000).
105
106 Parameters:
107 host: The host to serve the docs from.
108 port: The port to serve the docs on.
109 """
110 ctx.run(
111 tools.mkdocs.serve(dev_addr=f"{host}:{port}").add_args(*cli_args),
112 title="Serving documentation",
113 capture=False,
114 )
115
116
117 @duty(skip_if=sys.version_info < (3, 13), skip_reason=pyprefix("Skipped: docs require modern generics syntax"))
118 def docs_deploy(ctx: Context) -> None:
119 """Deploy the documentation to GitHub pages."""
120 os.environ["DEPLOY"] = "true"
121 ctx.run(tools.mkdocs.gh_deploy(force=True), title="Deploying documentation")
122
123
124 @duty
125 def format(ctx: Context) -> None:
126 """Run formatting tools on the code."""
127 ctx.run(
128 tools.ruff.check(*PY_SRC_LIST, config="config/ruff.toml", fix_only=True, exit_zero=True),
129 title="Auto-fixing code",
130 )
131 ctx.run(tools.ruff.format(*PY_SRC_LIST, config="config/ruff.toml"), title="Formatting code")
132
133
134 @duty
135 def build(ctx: Context) -> None:
136 """Build source and wheel distributions."""
137 ctx.run(
138 tools.build(),
139 title="Building source and wheel distributions",
140 pty=PTY,
141 )
142
143
144 @duty
145 def publish(ctx: Context) -> None:
146 """Publish source and wheel distributions to PyPI."""
147 if not Path("dist").exists():
148 ctx.run("false", title="No distribution files found")
149 dists = [str(dist) for dist in Path("dist").iterdir()]
150 ctx.run(
151 tools.twine.upload(*dists, skip_existing=True),
152 title="Publishing source and wheel distributions to PyPI",
153 pty=PTY,
154 )
155
156
157 @duty(post=["build", "publish", "docs-deploy"])
158 def release(ctx: Context, version: str = "") -> None:
159 """Release a new Python package.
160
161 Parameters:
162 version: The new version number to use.
163 """
164 if not (version := (version or input("> Version to release: ")).strip()):
165 ctx.run("false", title="A version must be provided")
166 ctx.run("git add pyproject.toml CHANGELOG.md", title="Staging files", pty=PTY)
167 ctx.run(["git", "commit", "-m", f"chore: Prepare release {version}"], title="Committing changes", pty=PTY)
168 ctx.run(f"git tag -m '' -a {version}", title="Tagging commit", pty=PTY)
169 ctx.run("git push", title="Pushing commits", pty=False)
170 ctx.run("git push --tags", title="Pushing tags", pty=False)
171
172
173 @duty(silent=True, aliases=["cov"])
174 def coverage(ctx: Context) -> None:
175 """Report coverage as text and HTML."""
176 ctx.run(tools.coverage.combine(), nofail=True)
177 ctx.run(tools.coverage.report(rcfile="config/coverage.ini"), capture=False)
178 ctx.run(tools.coverage.html(rcfile="config/coverage.ini"))
179
180
181 @duty(nofail=PY_VERSION == PY_DEV)
182 def test(ctx: Context, *cli_args: str, snapshot: str = "report") -> None: # noqa: PT028
183 """Run the test suite."""
184 os.environ["COVERAGE_FILE"] = f".coverage.{PY_VERSION}"
185 os.environ["PYTHONWARNDEFAULTENCODING"] = "1"
186 args = list(cli_args)
187 if snapshot == "disable" or not snapshot:
188 args = ["-n", "auto", "--inline-snapshot=disable"]
189 else:
190 args = [f"--inline-snapshot={snapshot}"]
191 ctx.run(
192 tools.pytest(
193 "tests",
194 config_file="config/pytest.ini",
195 color="yes",
196 ).add_args(*args),
197 title=pyprefix("Running tests"),
198 )