Debian Codegraph @

scripts/update-plugin-list.py

raw
1 # mypy: disallow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Iterable
5 from collections.abc import Iterator
6 import datetime
7 import pathlib
8 import re
9 from textwrap import dedent
10 from textwrap import indent
11 from typing import Any
12 from typing import TypedDict
13
14 import packaging.version
15 import platformdirs
16 from requests_cache import CachedResponse
17 from requests_cache import CachedSession
18 from requests_cache import OriginalResponse
19 from requests_cache import SQLiteCache
20 import tabulate
21 from tqdm import tqdm
22 import wcwidth
23
24
25 FILE_HEAD = r"""
26 .. Note this file is autogenerated by scripts/update-plugin-list.py - usually weekly via github action
27
28 .. _plugin-list:
29
30 Pytest Plugin List
31 ==================
32
33 Below is an automated compilation of ``pytest`` plugins available on `PyPI <https://pypi.org>`_.
34 It includes PyPI projects whose names begin with ``pytest-`` or ``pytest_`` and a handful of manually selected projects.
35 Packages classified as inactive are excluded.
36
37 For detailed insights into how this list is generated,
38 please refer to `the update script <https://github.com/pytest-dev/pytest/blob/main/scripts/update-plugin-list.py>`_.
39
40 .. warning::
41
42 Please be aware that this list is not a curated collection of projects
43 and does not undergo a systematic review process.
44 It serves purely as an informational resource to aid in the discovery of ``pytest`` plugins.
45
46 Do not presume any endorsement from the ``pytest`` project or its developers,
47 and always conduct your own quality assessment before incorporating any of these plugins into your own projects.
48
49
50 .. The following conditional uses a different format for this list when
51 creating a PDF, because otherwise the table gets far too wide for the
52 page.
53
54 """
55 DEVELOPMENT_STATUS_CLASSIFIERS = (
56 "Development Status :: 1 - Planning",
57 "Development Status :: 2 - Pre-Alpha",
58 "Development Status :: 3 - Alpha",
59 "Development Status :: 4 - Beta",
60 "Development Status :: 5 - Production/Stable",
61 "Development Status :: 6 - Mature",
62 "Development Status :: 7 - Inactive",
63 )
64 ADDITIONAL_PROJECTS = { # set of additional projects to consider as plugins
65 "logassert",
66 "logot",
67 "nuts",
68 "flask_fixture",
69 "databricks-labs-pytester",
70 "tursu",
71 }
72
73
74 def escape_rst(text: str) -> str:
75 """Rudimentary attempt to escape special RST characters to appear as
76 plain text."""
77 text = (
78 text.replace("*", "\\*")
79 .replace("<", "\\<")
80 .replace(">", "\\>")
81 .replace("`", "\\`")
82 )
83 text = re.sub(r"_\b", "", text)
84 return text
85
86
87 def project_response_with_refresh(
88 session: CachedSession, name: str, last_serial: int
89 ) -> OriginalResponse | CachedResponse:
90 """Get a http cached pypi project
91
92 force refresh in case of last serial mismatch
93 """
94 response = session.get(f"https://pypi.org/pypi/{name}/json")
95 if int(response.headers.get("X-PyPI-Last-Serial", -1)) != last_serial:
96 response = session.get(f"https://pypi.org/pypi/{name}/json", refresh=True)
97 return response
98
99
100 def get_session() -> CachedSession:
101 """Configures the requests-cache session"""
102 cache_path = platformdirs.user_cache_path("pytest-plugin-list")
103 cache_path.mkdir(exist_ok=True, parents=True)
104 cache_file = cache_path.joinpath("http_cache.sqlite3")
105 return CachedSession(backend=SQLiteCache(cache_file))
106
107
108 def pytest_plugin_projects_from_pypi(session: CachedSession) -> dict[str, int]:
109 response = session.get(
110 "https://pypi.org/simple",
111 headers={"Accept": "application/vnd.pypi.simple.v1+json"},
112 refresh=True,
113 )
114 return {
115 name: p["_last-serial"]
116 for p in response.json()["projects"]
117 if (
118 (name := p["name"]).startswith(("pytest-", "pytest_"))
119 or name in ADDITIONAL_PROJECTS
120 )
121 }
122
123
124 class PluginInfo(TypedDict):
125 """Relevant information about a plugin to generate the summary."""
126
127 name: str
128 summary: str
129 last_release: str
130 status: str
131 requires: str
132
133
134 def iter_plugins() -> Iterator[PluginInfo]:
135 session = get_session()
136 name_2_serial = pytest_plugin_projects_from_pypi(session)
137
138 for name, last_serial in tqdm(name_2_serial.items(), smoothing=0):
139 response = project_response_with_refresh(session, name, last_serial)
140 if response.status_code == 404:
141 # Some packages, like pytest-azurepipelines42, are included in https://pypi.org/simple
142 # but return 404 on the JSON API. Skip.
143 continue
144 response.raise_for_status()
145 info = response.json()["info"]
146 if "Development Status :: 7 - Inactive" in info["classifiers"]:
147 continue
148 for classifier in DEVELOPMENT_STATUS_CLASSIFIERS:
149 if classifier in info["classifiers"]:
150 status = classifier[22:]
151 break
152 else:
153 status = "N/A"
154 requires = "N/A"
155 if info["requires_dist"]:
156 for requirement in info["requires_dist"]:
157 if re.match(r"pytest(?![-.\w])", requirement):
158 requires = requirement
159 break
160
161 def version_sort_key(version_string: str) -> Any:
162 """
163 Return the sort key for the given version string
164 returned by the API.
165 """
166 try:
167 return packaging.version.parse(version_string)
168 except packaging.version.InvalidVersion:
169 # Use a hard-coded pre-release version.
170 return packaging.version.Version("0.0.0alpha")
171
172 releases = response.json()["releases"]
173 for release in sorted(releases, key=version_sort_key, reverse=True):
174 if releases[release]:
175 release_date = datetime.date.fromisoformat(
176 releases[release][-1]["upload_time_iso_8601"].split("T")[0]
177 )
178 last_release = release_date.strftime("%b %d, %Y")
179 break
180 name = f":pypi:`{info['name']}`"
181 summary = ""
182 if info["summary"]:
183 summary = escape_rst(info["summary"].replace("\n", ""))
184 yield {
185 "name": name,
186 "summary": summary.strip(),
187 "last_release": last_release,
188 "status": status,
189 "requires": requires,
190 }
191
192
193 def plugin_definitions(plugins: Iterable[PluginInfo]) -> Iterator[str]:
194 """Return RST for the plugin list that fits better on a vertical page."""
195 for plugin in plugins:
196 yield dedent(
197 f"""
198 {plugin["name"]}
199 *last release*: {plugin["last_release"]},
200 *status*: {plugin["status"]},
201 *requires*: {plugin["requires"]}
202
203 {plugin["summary"]}
204 """
205 )
206
207
208 def main() -> None:
209 plugins = [*iter_plugins()]
210
211 reference_dir = pathlib.Path("doc", "en", "reference")
212
213 plugin_list = reference_dir / "plugin_list.rst"
214 with plugin_list.open("w", encoding="UTF-8") as f:
215 f.write(FILE_HEAD)
216 f.write(f"This list contains {len(plugins)} plugins.\n\n")
217 f.write(".. only:: not latex\n\n")
218
219 _ = wcwidth # reference library that must exist for tabulate to work
220 plugin_table = tabulate.tabulate(plugins, headers="keys", tablefmt="rst")
221 f.write(indent(plugin_table, " "))
222 f.write("\n\n")
223
224 f.write(".. only:: latex\n\n")
225 f.write(indent("".join(plugin_definitions(plugins)), " "))
226
227
228 if __name__ == "__main__":
229 main()