Coverage for src/rhiza_task/tasks/dist.py: 100%

134 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-11-30 09:28 +0000

1"""``dist-check``: build the distributions, and check them before anything publishes them. 

2 

3The release workflows already compared the *filenames* ``uv build`` wrote against the tag. 

4Two failures pass that comparison, and both have shipped: 

5 

6- **A declared licence file that is not in the package.** chebfun 0.11.0 declared 

7 ``license-files = ["LICENSE"]`` while the repository held ``LICENSE.rst``. The build 

8 succeeded, the release succeeded, and the published metadata did not carry the licence 

9 (rhiza#1743, chebpy#518). Nothing reads ``License-File`` until someone needs it. 

10- **A version that only exists inside the checkout.** A version derived from the VCS -- 

11 hatch-vcs, setuptools-scm -- is read from git when the sdist is built, and has to be 

12 frozen into the sdist's ``PKG-INFO`` for anyone building *from* it: conda-forge, a distro, 

13 ``pip install`` of the sdist. When it is not, a rebuild outside the repository falls back 

14 to ``0.0.0`` or ``0.1.dev1`` with a green build and no error. 

15 

16So this task builds into ``dist/``, then reads what it built rather than what the manifest 

17says: the version in each artifact's metadata, every ``License-File`` entry and whether the 

18file is really in the archive, and every file the project *declares* as a licence. It then 

19unpacks the sdist into a temporary directory -- outside any git repository, with version 

20overrides such as ``SETUPTOOLS_SCM_PRETEND_VERSION`` removed from the environment -- and 

21rebuilds a wheel from it, which has to come out at the same version with the same licences. 

22 

23``dist/`` is left holding exactly the artifacts that passed. That is the point of building 

24here rather than checking a folder someone else filled: a release job can upload the 

25directory this task validated, and nothing can be rebuilt in between. Earlier sdists and 

26wheels in ``dist/`` are removed first, because a stale one would be validated -- or 

27published -- alongside the new. 

28 

29What it does not do is compare the version with a release tag. Tag handling (``v`` prefixes, 

30semver-to-PEP 440 normalisation) needs ``packaging``, which is not a dependency of this 

31package, and the release workflows already make that comparison against the filenames this 

32task leaves in ``dist/``. The two halves meet there. 

33""" 

34 

35from __future__ import annotations 

36 

37import os 

38import tarfile 

39import tempfile 

40import tomllib 

41import zipfile 

42from dataclasses import dataclass, field 

43from email.message import Message 

44from email.parser import HeaderParser 

45from pathlib import Path 

46 

47from ..config import Config 

48from ..spec import Failed, Skip, task 

49from ..uv import uv 

50 

51DIST_FOLDER = "dist" 

52"""Where the validated artifacts are left: ``uv build``'s own default, and what ``clean`` removes.""" 

53 

54VERSION_OVERRIDES = ("SETUPTOOLS_SCM_PRETEND_VERSION", "PDM_BUILD_SCM_VERSION") 

55"""Prefixes of the variables that override a VCS-derived version, removed for the rebuild. 

56 

57Prefixes, because setuptools-scm (and hatch-vcs, which drives it) also reads a per-distribution 

58``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_<NAME>``. A rebuild that inherits one of these reports the 

59override rather than what the sdist carries, which is the exact thing the rebuild is there to 

60find out. 

61""" 

62 

63SKIPPED_ROOTS = ("dist", "build") 

64"""Top-level folders a licence glob is not matched in, besides hidden ones such as ``.venv``. 

65 

66A pattern like ``**/LICENSE*`` would otherwise count a dependency's licence in the virtualenv, 

67or a previous build's copy, as the project's own. 

68""" 

69 

70 

71@dataclass(frozen=True) 

72class Artifact: 

73 """What one distribution says about itself, read from the archive. 

74 

75 Attributes: 

76 name: The archive's filename, for messages. 

77 version: ``Version`` from its metadata. 

78 license_files: Its ``License-File`` entries, in order. 

79 contents: The bytes of each licence file found in the archive, keyed by the path the 

80 metadata (or the project's declaration) uses. A path with no entry is missing. 

81 """ 

82 

83 name: str 

84 version: str 

85 license_files: tuple[str, ...] 

86 contents: dict[str, bytes] = field(default_factory=dict) 

87 

88 

89@task( 

90 "dist-check", 

91 "build the sdist and wheel, and check their version and licence metadata", 

92 section="Python", 

93 layer="python", 

94 needs=("setup",), 

95) 

96def dist_check(cfg: Config) -> None: 

97 """Build into ``dist/``, read the artifacts back, and rebuild a wheel from the sdist. 

98 

99 Args: 

100 cfg: The resolved configuration. 

101 

102 Raises: 

103 Skip: When the project declares no ``[build-system]``, so there is nothing to build. 

104 Failed: When the build produced an unexpected set of files, or any check failed. 

105 """ 

106 root = cfg.root 

107 if not _buildable(root / "pyproject.toml"): 

108 raise Skip("no [build-system] in pyproject.toml: nothing is built") 

109 

110 dist = root / DIST_FOLDER 

111 _clear(dist) 

112 uv("build", "--out-dir", str(dist), cwd=root) 

113 sdists, wheels = sorted(dist.glob("*.tar.gz")), sorted(dist.glob("*.whl")) 

114 if len(sdists) != 1 or not wheels: 

115 raise Failed( 

116 1, f"expected one sdist and at least one wheel in {DIST_FOLDER}/, found {len(sdists)} and {len(wheels)}" 

117 ) 

118 

119 declared, problems = declared_license_files(root) 

120 artifacts = [read_sdist(sdists[0], declared), *(read_wheel(w, declared) for w in wheels)] 

121 with tempfile.TemporaryDirectory(prefix="rhiza-dist-check-") as tmp: 

122 artifacts.append(read_wheel(_rebuild(sdists[0], Path(tmp)), declared, rebuilt=True)) 

123 

124 for artifact in artifacts: 

125 print( 

126 f"[INFO] {artifact.name}: {artifact.version}, License-File: {', '.join(artifact.license_files) or 'none'}" 

127 ) 

128 problems += check(artifacts, declared, root) 

129 if problems: 

130 for problem in problems: 

131 print(f"[ERROR] {problem}") 

132 raise Failed(1, f"{len(problems)} problem(s) in the built distributions") 

133 print( 

134 f"[INFO] {DIST_FOLDER}/ holds {len(sdists) + len(wheels)} validated distribution(s) at {artifacts[0].version}" 

135 ) 

136 

137 

138def _buildable(pyproject: Path) -> bool: 

139 """Return whether the project declares a build backend. 

140 

141 Args: 

142 pyproject: The manifest's path. 

143 

144 Returns: 

145 True when it exists and has a ``[build-system]`` table. A uv *virtual* project has 

146 none, and builds nothing -- rhiza itself is one. 

147 """ 

148 return pyproject.is_file() and "build-system" in tomllib.loads(pyproject.read_text(encoding="utf-8")) 

149 

150 

151def _clear(dist: Path) -> None: 

152 """Remove earlier sdists and wheels, leaving anything else in the folder alone. 

153 

154 Args: 

155 dist: The output folder, which may not exist yet. 

156 """ 

157 for stale in [*dist.glob("*.tar.gz"), *dist.glob("*.whl")]: 

158 print(f"[INFO] removing earlier build {stale.name}") 

159 stale.unlink() 

160 

161 

162def declared_license_files(root: Path) -> tuple[list[str], list[str]]: 

163 """Resolve the licence files ``pyproject.toml`` declares against the project tree. 

164 

165 Reads PEP 639's ``[project].license-files`` globs and the older ``license = {file = ...}`` 

166 table. A project that declares neither gets no expectation here -- its backend's defaults 

167 are still checked for consistency by :func:`check`, through the ``License-File`` entries. 

168 

169 Args: 

170 root: The project root. 

171 

172 Returns: 

173 The matched paths, POSIX-style and relative to ``root``, and one problem for each 

174 pattern that matches nothing -- which is the chebfun case: a declaration naming a file 

175 the repository does not have, which the backend accepted without a word. 

176 """ 

177 found: list[str] = [] 

178 problems: list[str] = [] 

179 for pattern in _declared_patterns(root): 

180 matches = _matches(root, pattern) 

181 if not matches: 

182 problems.append(f"pyproject.toml declares licence file {pattern!r}, which matches no file in the project") 

183 found += [m for m in matches if m not in found] 

184 return found, problems 

185 

186 

187def _declared_patterns(root: Path) -> list[str]: 

188 """Return the licence globs and paths ``[project]`` declares, in declaration order. 

189 

190 Args: 

191 root: The project root. 

192 

193 Returns: 

194 ``license-files``' patterns, then ``license.file`` when the table form is used. 

195 """ 

196 project = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8")).get("project") or {} 

197 patterns = list(project.get("license-files") or []) 

198 legacy = project.get("license") 

199 if isinstance(legacy, dict) and "file" in legacy: 

200 patterns.append(legacy["file"]) 

201 return patterns 

202 

203 

204def _matches(root: Path, pattern: str) -> list[str]: 

205 """Return the project's own files a pattern matches. 

206 

207 Args: 

208 root: The project root. 

209 pattern: A glob relative to it. 

210 

211 Returns: 

212 POSIX-style relative paths, sorted, outside hidden folders and :data:`SKIPPED_ROOTS`. 

213 """ 

214 relative = (p.relative_to(root) for p in root.glob(pattern) if p.is_file()) 

215 return sorted(r.as_posix() for r in relative if not _skipped(r.parts[0])) 

216 

217 

218def _skipped(top: str) -> bool: 

219 """Return whether a top-level path component is outside the project's own files. 

220 

221 Args: 

222 top: The first component of a path relative to the root. 

223 

224 Returns: 

225 True for hidden folders and :data:`SKIPPED_ROOTS`. 

226 """ 

227 return top.startswith(".") or top in SKIPPED_ROOTS 

228 

229 

230def read_sdist(path: Path, declared: list[str]) -> Artifact: 

231 """Read an sdist's ``PKG-INFO`` and the licence files it holds. 

232 

233 Args: 

234 path: The ``.tar.gz``. 

235 declared: The project's declared licence files, looked up as well as the metadata's. 

236 

237 Returns: 

238 The artifact as the archive describes it. 

239 

240 Raises: 

241 Failed: When the archive has no top-level ``PKG-INFO``. 

242 """ 

243 with tarfile.open(path) as archive: 

244 members = {m.name: m for m in archive.getmembers() if m.isfile()} 

245 top = next(iter(members), "").split("/")[0] 

246 info = members.get(f"{top}/PKG-INFO") 

247 if info is None: 

248 raise Failed(1, f"{path.name} has no {top}/PKG-INFO") 

249 metadata = _parse(_read_member(archive, info)) 

250 license_files = tuple(metadata.get_all("License-File") or ()) 

251 contents = { 

252 p: _read_member(archive, members[f"{top}/{p}"]) 

253 for p in {*license_files, *declared} 

254 if f"{top}/{p}" in members 

255 } 

256 return Artifact(path.name, metadata.get("Version", ""), license_files, contents) 

257 

258 

259def read_wheel(path: Path, declared: list[str], rebuilt: bool = False) -> Artifact: 

260 """Read a wheel's ``METADATA`` and the licence files it holds. 

261 

262 PEP 639 puts a licence file under ``<dist-info>/licenses/<path>``; setuptools before it 

263 wrote ``<dist-info>/<path>``. Either counts as present. 

264 

265 Args: 

266 path: The ``.whl``. 

267 declared: The project's declared licence files, looked up as well as the metadata's. 

268 rebuilt: Whether this wheel was rebuilt from the sdist, which the name then says. 

269 

270 Returns: 

271 The artifact as the archive describes it. 

272 

273 Raises: 

274 Failed: When the wheel does not hold exactly one ``.dist-info/METADATA``. 

275 """ 

276 with zipfile.ZipFile(path) as archive: 

277 names = set(archive.namelist()) 

278 found = [n for n in names if n.endswith(".dist-info/METADATA") and n.count("/") == 1] 

279 if len(found) != 1: 

280 raise Failed(1, f"{path.name} holds {len(found)} .dist-info/METADATA files, not one") 

281 info = found[0].rsplit("/", 1)[0] 

282 metadata = _parse(archive.read(found[0])) 

283 license_files = tuple(metadata.get_all("License-File") or ()) 

284 members = {p: _wheel_member(names, info, p) for p in {*license_files, *declared}} 

285 contents = {p: archive.read(m) for p, m in members.items() if m is not None} 

286 name = f"{path.name} (rebuilt from the sdist)" if rebuilt else path.name 

287 return Artifact(name, metadata.get("Version", ""), license_files, contents) 

288 

289 

290def _wheel_member(names: set[str], info: str, path: str) -> str | None: 

291 """Locate a licence file in a wheel, in either layout. 

292 

293 Args: 

294 names: Every member name in the wheel. 

295 info: Its ``.dist-info`` folder. 

296 path: The licence file's project-relative path. 

297 

298 Returns: 

299 The member name, or ``None`` when the wheel does not hold it. 

300 """ 

301 return next((m for m in (f"{info}/licenses/{path}", f"{info}/{path}") if m in names), None) 

302 

303 

304def _read_member(archive: tarfile.TarFile, member: tarfile.TarInfo) -> bytes: 

305 """Return a regular file's bytes from a tar archive. 

306 

307 Args: 

308 archive: The open archive. 

309 member: A regular-file member of it. 

310 

311 Returns: 

312 The file's contents. 

313 """ 

314 handle = archive.extractfile(member) 

315 return handle.read() if handle is not None else b"" 

316 

317 

318def _parse(raw: bytes) -> Message: 

319 """Parse core metadata, which is RFC 822 headers followed by an optional body. 

320 

321 Args: 

322 raw: The bytes of ``PKG-INFO`` or ``METADATA``. 

323 

324 Returns: 

325 The parsed headers, read with ``get``/``get_all``. 

326 """ 

327 return HeaderParser().parsestr(raw.decode("utf-8", errors="replace")) 

328 

329 

330def _rebuild(sdist: Path, tmp: Path) -> Path: 

331 """Unpack the sdist outside any repository and build a wheel from what it holds. 

332 

333 Args: 

334 sdist: The ``.tar.gz`` to rebuild from. 

335 tmp: An empty temporary directory, which must outlive the read of the result. 

336 

337 Returns: 

338 The rebuilt wheel. 

339 

340 Raises: 

341 Failed: When the sdist does not unpack to one folder or the build yields no wheel. 

342 """ 

343 source, out = tmp / "source", tmp / "out" 

344 with tarfile.open(sdist) as archive: 

345 # The "data" filter refuses absolute paths, links out of the tree and device files, 

346 # which is what makes unpacking an archive this task did not write safe. 

347 archive.extractall(source, filter="data") 

348 tops = [p for p in source.iterdir() if p.is_dir()] 

349 if len(tops) != 1: 

350 raise Failed(1, f"{sdist.name} unpacks to {len(tops)} top-level folders, not one") 

351 

352 # GIT_CEILING_DIRECTORIES stops git's upward search at the temporary directory, so a 

353 # backend that asks git for the version finds no repository, as a downstream builder 

354 # would not -- and the version has to come from the sdist's own PKG-INFO. 

355 overrides = [name for name in os.environ if name.startswith(VERSION_OVERRIDES)] 

356 uv( 

357 "build", 

358 "--wheel", 

359 "--out-dir", 

360 str(out), 

361 str(tops[0]), 

362 cwd=tmp, 

363 env={"GIT_CEILING_DIRECTORIES": str(tmp)}, 

364 unset=overrides, 

365 ) 

366 wheels = sorted(out.glob("*.whl")) 

367 if len(wheels) != 1: 

368 raise Failed(1, f"rebuilding {sdist.name} produced {len(wheels)} wheels, not one") 

369 return wheels[0] 

370 

371 

372def check(artifacts: list[Artifact], declared: list[str], root: Path) -> list[str]: 

373 """Compare the artifacts with each other and with the project's declared licences. 

374 

375 The first artifact is the sdist, and the reference: every other one must carry its 

376 version and its ``License-File`` set. 

377 

378 Args: 

379 artifacts: The sdist first, then the wheels, the rebuilt one last. 

380 declared: The project's declared licence files. 

381 root: The project root, for the declared files' contents. 

382 

383 Returns: 

384 One message per problem, empty when everything agrees. 

385 """ 

386 reference = artifacts[0] 

387 problems: list[str] = [] 

388 for artifact in artifacts: 

389 if artifact.version != reference.version: 

390 problems.append(f"{artifact.name} has version {artifact.version!r}, the sdist {reference.version!r}") 

391 if set(artifact.license_files) != set(reference.license_files): 

392 problems.append( 

393 f"{artifact.name} records License-File {sorted(artifact.license_files)}, " 

394 f"the sdist {sorted(reference.license_files)}" 

395 ) 

396 problems += _license_problems(artifact, declared, root) 

397 return problems 

398 

399 

400def _license_problems(artifact: Artifact, declared: list[str], root: Path) -> list[str]: 

401 """Check one artifact's licence files against its metadata and the project. 

402 

403 Args: 

404 artifact: The distribution. 

405 declared: The project's declared licence files. 

406 root: The project root. 

407 

408 Returns: 

409 A message for each declared file the metadata does not record, each recorded file the 

410 archive does not hold, and each declared file whose packaged copy differs from the 

411 project's. 

412 """ 

413 problems = [ 

414 f"{artifact.name} does not record declared licence file {p!r} as a License-File" 

415 for p in declared 

416 if p not in artifact.license_files 

417 ] 

418 problems += [ 

419 f"{artifact.name} records License-File {p!r} but does not contain it" 

420 for p in artifact.license_files 

421 if p not in artifact.contents 

422 ] 

423 problems += [ 

424 f"{artifact.name} contains a copy of {p!r} that differs from the project's" 

425 for p in declared 

426 if p in artifact.contents and artifact.contents[p] != (root / p).read_bytes() 

427 ] 

428 return problems