wheeltruth 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wheeltruth/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """wheeltruth: check that your built wheel/sdist contains what it should."""
2
+
3
+ __version__ = "0.1.0"
wheeltruth/check.py ADDED
@@ -0,0 +1,774 @@
1
+ """Core checks for wheeltruth: does the built artifact contain what it should?"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import csv
7
+ import hashlib
8
+ import io
9
+ import os
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ import tarfile
14
+ import tempfile
15
+ import zipfile
16
+
17
+ SEVERITIES = ("info", "warning", "error")
18
+
19
+ # Top-level sdist dirs that are never shipped inside a wheel.
20
+ _NON_PACKAGE_TOPS = {
21
+ "tests", "test", "docs", "doc", "examples", "example",
22
+ ".github", ".git", "tools", "scripts",
23
+ }
24
+
25
+
26
+ class Finding:
27
+ def __init__(self, severity, code, message, artifact="", detail=""):
28
+ assert severity in SEVERITIES
29
+ self.severity = severity
30
+ self.code = code
31
+ self.message = message
32
+ self.artifact = artifact
33
+ self.detail = detail
34
+
35
+ def __repr__(self): # pragma: no cover - debugging helper
36
+ return f"Finding({self.severity!r}, {self.code!r}, {self.message!r})"
37
+
38
+
39
+ class ArtifactReport:
40
+ def __init__(self, path, kind):
41
+ self.path = path
42
+ self.kind = kind # "wheel" | "sdist"
43
+ self.findings = []
44
+
45
+ def add(self, severity, code, message, detail=""):
46
+ self.findings.append(
47
+ Finding(severity, code, message, artifact=self.path, detail=detail)
48
+ )
49
+
50
+ @property
51
+ def has_issues(self):
52
+ return any(f.severity in ("warning", "error") for f in self.findings)
53
+
54
+ @property
55
+ def errors(self):
56
+ return [f for f in self.findings if f.severity == "error"]
57
+
58
+
59
+ def _is_dist_info(path):
60
+ return bool(re.match(r"[^/]+\.dist-info/", path))
61
+
62
+
63
+ def _is_signature_record(path):
64
+ return bool(re.match(r"[^/]+\.dist-info/RECORD(\.jws|\.p7s)?$", path))
65
+
66
+
67
+ def parse_wheel_filename(filename):
68
+ """Return (name, version) from a wheel filename, or (None, None)."""
69
+ base = os.path.basename(filename)
70
+ if not base.endswith(".whl"):
71
+ return None, None
72
+ parts = base[:-4].split("-")
73
+ if len(parts) < 5:
74
+ return None, None
75
+ rest = parts[:-3] # name, version, [build]
76
+ if len(rest) == 3:
77
+ name, version = rest[0], rest[1]
78
+ elif len(rest) == 2:
79
+ name, version = rest
80
+ else:
81
+ return None, None
82
+ return name, version
83
+
84
+
85
+ def parse_sdist_filename(filename):
86
+ base = os.path.basename(filename)
87
+ for suffix in (".tar.gz", ".tgz", ".zip"):
88
+ if base.endswith(suffix):
89
+ stem = base[: -len(suffix)]
90
+ if "-" in stem:
91
+ name, version = stem.rsplit("-", 1)
92
+ return name, version
93
+ return None, None
94
+
95
+
96
+ def _norm_name(name):
97
+ return re.sub(r"[-_.]+", "-", name or "").lower()
98
+
99
+
100
+ def parse_rfc822_headers(text):
101
+ """Minimal RFC822 header parser -> {key: [values]}. Stops at first blank line."""
102
+ headers = {}
103
+ key = None
104
+ for line in text.splitlines():
105
+ if not line.strip():
106
+ break
107
+ if line[0] in " \t" and key:
108
+ headers[key][-1] += "\n" + line.strip()
109
+ elif ":" in line:
110
+ k, v = line.split(":", 1)
111
+ key = k.strip()
112
+ headers.setdefault(key, []).append(v.strip())
113
+ else:
114
+ key = None
115
+ return headers
116
+
117
+
118
+ def parse_entry_points(text):
119
+ """Parse entry_points.txt -> {group: [(name, value), ...]}."""
120
+ groups = {}
121
+ current = None
122
+ for raw in text.splitlines():
123
+ line = raw.strip()
124
+ if not line or line.startswith(("#", ";")):
125
+ continue
126
+ if line.startswith("[") and line.endswith("]"):
127
+ current = line[1:-1].strip()
128
+ groups.setdefault(current, [])
129
+ elif current is not None and "=" in line:
130
+ name, value = line.split("=", 1)
131
+ groups[current].append((name.strip(), value.strip()))
132
+ return groups
133
+
134
+
135
+ class WheelData:
136
+ def __init__(self, path):
137
+ self.path = path
138
+ self.files = []
139
+ self.record = {} # path -> (hash, size)
140
+ self.metadata = {}
141
+ self.entry_points = {}
142
+ self.dist_info = ""
143
+ self.filename_name, self.filename_version = parse_wheel_filename(path)
144
+
145
+
146
+ def read_wheel(path):
147
+ wheel = WheelData(path)
148
+ with zipfile.ZipFile(path) as zf:
149
+ wheel.files = [n for n in zf.namelist() if not n.endswith("/")]
150
+ dist_infos = {n.split("/")[0] for n in wheel.files if _is_dist_info(n)}
151
+ wheel.dist_info = sorted(dist_infos)[0] if dist_infos else ""
152
+ for name in wheel.files:
153
+ if name == f"{wheel.dist_info}/METADATA" and wheel.dist_info:
154
+ wheel.metadata = parse_rfc822_headers(
155
+ zf.read(name).decode("utf-8", "replace")
156
+ )
157
+ elif name == f"{wheel.dist_info}/entry_points.txt" and wheel.dist_info:
158
+ wheel.entry_points = parse_entry_points(
159
+ zf.read(name).decode("utf-8", "replace")
160
+ )
161
+ elif name.endswith(".dist-info/RECORD") and "/RECORD" in name:
162
+ text = zf.read(name).decode("utf-8", "replace")
163
+ for row in csv.reader(io.StringIO(text)):
164
+ if len(row) >= 1 and row[0]:
165
+ wheel.record[row[0]] = (
166
+ row[1] if len(row) > 1 else "",
167
+ row[2] if len(row) > 2 else "",
168
+ )
169
+ return wheel
170
+
171
+
172
+ class SdistData:
173
+ def __init__(self, path):
174
+ self.path = path
175
+ self.files = []
176
+ self.pkg_info = {}
177
+ self.filename_name, self.filename_version = parse_sdist_filename(path)
178
+
179
+
180
+ def read_sdist(path):
181
+ sdist = SdistData(path)
182
+ base = os.path.basename(path)
183
+ if base.endswith(".zip"):
184
+ with zipfile.ZipFile(path) as zf:
185
+ sdist.files = [n for n in zf.namelist() if not n.endswith("/")]
186
+ for n in sdist.files:
187
+ if n.count("/") == 1 and n.endswith("PKG-INFO"):
188
+ sdist.pkg_info = parse_rfc822_headers(
189
+ zf.read(n).decode("utf-8", "replace")
190
+ )
191
+ else:
192
+ with tarfile.open(path, "r:*") as tf:
193
+ for member in tf.getmembers():
194
+ if member.isfile():
195
+ sdist.files.append(member.name)
196
+ for n in sdist.files:
197
+ if n.count("/") == 1 and n.endswith("PKG-INFO"):
198
+ f = tf.extractfile(n)
199
+ if f:
200
+ sdist.pkg_info = parse_rfc822_headers(
201
+ f.read().decode("utf-8", "replace")
202
+ )
203
+ return sdist
204
+
205
+
206
+ def _meta_name_version(headers):
207
+ name = (headers.get("Name") or [""])[0]
208
+ version = (headers.get("Version") or [""])[0]
209
+ return name, version
210
+
211
+
212
+ # ---------------------------------------------------------------- checks
213
+
214
+
215
+ def check_metadata_consistency(kind, headers, filename_name, filename_version, rep):
216
+ name, version = _meta_name_version(headers)
217
+ if not name:
218
+ rep.add("error", "metadata-no-name", "METADATA/PKG-INFO has no Name field")
219
+ if not version:
220
+ rep.add("error", "metadata-no-version", "METADATA/PKG-INFO has no Version field")
221
+ if filename_name and name and _norm_name(filename_name) != _norm_name(name):
222
+ rep.add(
223
+ "error",
224
+ "metadata-name-mismatch",
225
+ f"filename implies name {filename_name!r} but metadata says {name!r}",
226
+ )
227
+ if filename_version and version and filename_version != version:
228
+ rep.add(
229
+ "warning",
230
+ "metadata-version-mismatch",
231
+ f"filename implies version {filename_version!r} but metadata says {version!r}",
232
+ )
233
+
234
+
235
+ def _b64_nopad(data):
236
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
237
+
238
+
239
+ def check_record(wheel, rep):
240
+ """Every file in the zip must be listed in RECORD with a valid hash/size."""
241
+ try:
242
+ zf = zipfile.ZipFile(wheel.path)
243
+ except zipfile.BadZipFile:
244
+ rep.add("error", "bad-wheel", f"{wheel.path} is not a valid zip file")
245
+ return
246
+ with zf:
247
+ if not wheel.record:
248
+ rep.add("error", "record-missing", "wheel has no .dist-info/RECORD")
249
+ return
250
+ zfiles = set(wheel.files)
251
+ for f in sorted(zfiles):
252
+ if _is_signature_record(f):
253
+ continue
254
+ if f not in wheel.record:
255
+ rep.add(
256
+ "error",
257
+ "record-entry-missing",
258
+ f"file {f} is in the wheel but not listed in RECORD",
259
+ )
260
+ for f in sorted(wheel.record):
261
+ digest, size = wheel.record[f]
262
+ if f not in zfiles:
263
+ rep.add(
264
+ "error",
265
+ "record-dangling",
266
+ f"RECORD lists {f} but it is missing from the wheel",
267
+ )
268
+ continue
269
+ if digest:
270
+ algo, _, expected = digest.partition("=")
271
+ if algo.lower() == "sha256":
272
+ try:
273
+ actual = _b64_nopad(hashlib.sha256(zf.read(f)).digest())
274
+ except KeyError:
275
+ continue
276
+ if actual != expected:
277
+ rep.add(
278
+ "error",
279
+ "record-hash-mismatch",
280
+ f"RECORD hash mismatch for {f} (file changed after RECORD was written)",
281
+ )
282
+ if size and size.isdigit():
283
+ try:
284
+ actual_size = zf.getinfo(f).file_size
285
+ except KeyError:
286
+ continue
287
+ if int(size) != actual_size:
288
+ rep.add(
289
+ "error",
290
+ "record-size-mismatch",
291
+ f"RECORD size mismatch for {f}: listed {size}, actual {actual_size}",
292
+ )
293
+
294
+
295
+ def _entry_point_target_path(value, files):
296
+ """Resolve 'module:attr [extras]' to a path inside the wheel, or None."""
297
+ target = value.split()[0] # strip "[extra]" markers
298
+ module = target.split(":")[0].strip()
299
+ if not module or not re.match(r"^[A-Za-z_][\w.]*$", module):
300
+ return None
301
+ rel = module.replace(".", "/")
302
+ for candidate in (rel + ".py", rel + "/__init__.py"):
303
+ if candidate in files:
304
+ return candidate
305
+ return None
306
+
307
+
308
+ def check_entry_points(wheel, rep):
309
+ files = set(wheel.files)
310
+ for group in sorted(wheel.entry_points):
311
+ for name, value in wheel.entry_points[group]:
312
+ if _entry_point_target_path(value, files) is None:
313
+ rep.add(
314
+ "error",
315
+ "entry-point-dangling",
316
+ f"[{group}] {name} = {value}: target module not found in wheel",
317
+ )
318
+
319
+
320
+ def _top_package_dirs(files):
321
+ """Map top-level package dir -> {'py': set, 'pyi': set, 'py_typed': bool}."""
322
+ pkgs = {}
323
+ for f in files:
324
+ if _is_dist_info(f) or "/" not in f:
325
+ continue
326
+ top = f.split("/")[0]
327
+ if top in _NON_PACKAGE_TOPS or top.endswith(".data"):
328
+ continue
329
+ entry = pkgs.setdefault(top, {"py": set(), "pyi": set(), "py_typed": False})
330
+ base = f.rsplit("/", 1)[-1]
331
+ if f.endswith("/py.typed") or base == "py.typed":
332
+ entry["py_typed"] = True
333
+ elif f.endswith(".py"):
334
+ entry["py"].add(f[: -len(".py")])
335
+ elif f.endswith(".pyi"):
336
+ entry["pyi"].add(f[: -len(".pyi")])
337
+ return pkgs
338
+
339
+
340
+ def check_typing(wheel, rep):
341
+ """Stub consistency: packages shipping some .pyi should ship them all."""
342
+ pkgs = _top_package_dirs(wheel.files)
343
+ for pkg in sorted(pkgs):
344
+ entry = pkgs[pkg]
345
+ if entry["py_typed"]:
346
+ rep.add(
347
+ "info",
348
+ "typing-py-typed",
349
+ f"package {pkg}/ ships py.typed (typed package marker)",
350
+ )
351
+ if entry["pyi"]:
352
+ missing = sorted(
353
+ s for s in entry["py"] - entry["pyi"]
354
+ if s.split("/")[-1] != "__init__"
355
+ # __init__.py rarely carries annotations worth stubbing;
356
+ # flagging it would drown the signal in noise.
357
+ )
358
+ for stem in missing:
359
+ rep.add(
360
+ "warning",
361
+ "typing-stub-missing",
362
+ f"{pkg}/ ships .pyi stubs but {stem}.py has no sibling .pyi "
363
+ f"(downstream type checkers may fail)",
364
+ detail=f"{stem}.py",
365
+ )
366
+ for stem in sorted(entry["pyi"] - entry["py"]):
367
+ # A stub for a C extension (stem.so) or namespace edge is fine;
368
+ # only flag when neither .py nor a sibling module exists.
369
+ rep.add(
370
+ "info",
371
+ "typing-stub-orphan",
372
+ f"{stem}.pyi has no sibling {stem}.py in the wheel",
373
+ detail=f"{stem}.pyi",
374
+ )
375
+
376
+
377
+ def check_wheel_contents(wheel, rep):
378
+ py_files = [
379
+ f
380
+ for f in wheel.files
381
+ if f.endswith(".py") and not _is_dist_info(f) and "__pycache__" not in f
382
+ ]
383
+ if not py_files:
384
+ rep.add(
385
+ "warning", "wheel-no-python", "wheel contains no .py files at all"
386
+ )
387
+ check_metadata_consistency(
388
+ "wheel", wheel.metadata, wheel.filename_name, wheel.filename_version, rep
389
+ )
390
+ check_record(wheel, rep)
391
+ check_entry_points(wheel, rep)
392
+ check_typing(wheel, rep)
393
+
394
+
395
+ def check_sdist_contents(sdist, rep):
396
+ if not sdist.pkg_info:
397
+ rep.add("error", "sdist-no-pkg-info", "sdist has no PKG-INFO")
398
+ else:
399
+ check_metadata_consistency(
400
+ "sdist",
401
+ sdist.pkg_info,
402
+ sdist.filename_name,
403
+ sdist.filename_version,
404
+ rep,
405
+ )
406
+ py_files = [f for f in sdist.files if f.endswith(".py")]
407
+ if not py_files:
408
+ rep.add("warning", "sdist-no-python", "sdist contains no .py files at all")
409
+
410
+
411
+ def _normalize_sdist_path(path):
412
+ """Strip '<name>-<version>/' and an optional 'src/' prefix."""
413
+ parts = path.split("/")
414
+ if len(parts) < 2:
415
+ return None
416
+ rest = parts[1:]
417
+ if rest and rest[0] == "src":
418
+ rest = rest[1:]
419
+ return "/".join(rest) if rest else None
420
+
421
+
422
+ def check_wheel_vs_sdist(wheel, sdist, rep):
423
+ """Files tracked in the sdist's packages should survive into the wheel."""
424
+ wfiles = {
425
+ f
426
+ for f in wheel.files
427
+ if not _is_dist_info(f)
428
+ and not f.endswith("/")
429
+ and "__pycache__" not in f
430
+ }
431
+ # Group sdist files by top-level entry (after normalization).
432
+ s_groups = {}
433
+ for f in sdist.files:
434
+ n = _normalize_sdist_path(f)
435
+ if not n or n.endswith("/"):
436
+ continue
437
+ top = n.split("/")[0]
438
+ # Only compare things that look like shippable packages/modules.
439
+ s_groups.setdefault(top, []).append(n)
440
+
441
+ w_groups = {}
442
+ for f in wfiles:
443
+ top = f.split("/")[0]
444
+ w_groups.setdefault(top, []).append(f)
445
+
446
+ for top in sorted(s_groups):
447
+ if top in _NON_PACKAGE_TOPS:
448
+ continue
449
+ s_here = s_groups[top]
450
+ # Skip top-level non-package files (setup.py, README, ...) and dirs
451
+ # with no Python files at all.
452
+ if "/" not in s_here[0] and not s_here[0].endswith(".py"):
453
+ continue
454
+ if not any(p.endswith(".py") for p in s_here):
455
+ continue
456
+ s_rel = {p[len(top) + 1 :] for p in s_here}
457
+ w_rel = {p[len(top) + 1 :] for p in w_groups.get(top, []) if "/" in p}
458
+ # Also cover top-level modules (top.py in wheel vs top/<file> mismatch):
459
+ for missing in sorted(s_rel - w_rel):
460
+ # .pyi presence differences are covered by check_typing; still
461
+ # worth flagging here since sdist->wheel drops are the core story.
462
+ rep.add(
463
+ "warning",
464
+ "sdist-file-missing-in-wheel",
465
+ f"{top}/{missing} is in the sdist but missing from the wheel",
466
+ detail=f"{top}/{missing}",
467
+ )
468
+ for extra in sorted(w_rel - s_rel):
469
+ rep.add(
470
+ "info",
471
+ "wheel-file-not-in-sdist",
472
+ f"{top}/{extra} is in the wheel but not in the sdist",
473
+ detail=f"{top}/{extra}",
474
+ )
475
+ # Top-level modules (foo.py) that exist in sdist but not wheel.
476
+ s_toplevel_py = {
477
+ n for n in (_normalize_sdist_path(f) for f in sdist.files) if n and "/" not in n and n.endswith(".py")
478
+ }
479
+ w_toplevel_py = {f for f in wfiles if "/" not in f and f.endswith(".py")}
480
+ for missing in sorted(s_toplevel_py - w_toplevel_py):
481
+ rep.add(
482
+ "warning",
483
+ "sdist-file-missing-in-wheel",
484
+ f"{missing} is in the sdist but missing from the wheel",
485
+ detail=missing,
486
+ )
487
+
488
+ # ------------------------------------------------- --project heuristics
489
+
490
+
491
+ def _read_text(path):
492
+ try:
493
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
494
+ return fh.read()
495
+ except OSError:
496
+ return ""
497
+
498
+
499
+ def expected_packages_from_project(projdir):
500
+ """Best-effort (name, [top-level packages]) from project config files.
501
+
502
+ Returns (name_or_None, packages_or_None). Parses pyproject.toml,
503
+ setup.cfg and setup.py with small targeted parsers (no external deps).
504
+ """
505
+ name = None
506
+ packages = None
507
+
508
+ pyproject = _read_text(os.path.join(projdir, "pyproject.toml"))
509
+ if pyproject:
510
+ # [project] name
511
+ m = re.search(
512
+ r"(?ms)^\[project\].*?^\s*name\s*=\s*[\"']([^\"']+)[\"']", pyproject
513
+ )
514
+ if m:
515
+ name = m.group(1)
516
+ # [tool.setuptools.packages.find] namespaces / include
517
+ m = re.search(
518
+ r"(?ms)^\[tool\.setuptools\.packages\.find\].*?^\s*namespaces\s*=\s*(true|false)",
519
+ pyproject,
520
+ )
521
+ # explicit [tool.setuptools] packages = [...]
522
+ m2 = re.search(
523
+ r"(?ms)^\[tool\.setuptools\].*?^\s*packages\s*=\s*\[([^\]]*)\]",
524
+ pyproject,
525
+ )
526
+ if m2:
527
+ packages = re.findall(r"[\"']([\w.]+)[\"']", m2.group(1))
528
+
529
+ setup_cfg = _read_text(os.path.join(projdir, "setup.cfg"))
530
+ if setup_cfg:
531
+ m = re.search(r"(?m)^\[metadata\].*?^name\s*=\s*(.+)$", setup_cfg)
532
+ if m and not name:
533
+ name = m.group(1).strip()
534
+ m = re.search(r"(?m)^\[options\].*?^packages\s*=\s*(.+)$", setup_cfg)
535
+ if m and packages is None:
536
+ first = m.group(1).strip()
537
+ if first == "find:":
538
+ packages = None # auto-discovery; handled below
539
+ else:
540
+ # multi-line list under [options]
541
+ block = re.search(
542
+ r"(?m)^\[options\].*?^packages\s*=\s*\n((?:[ \t]+\S.*\n?)+)",
543
+ setup_cfg,
544
+ )
545
+ if block:
546
+ packages = [
547
+ ln.strip()
548
+ for ln in block.group(1).splitlines()
549
+ if ln.strip()
550
+ ]
551
+ else:
552
+ packages = [p.strip() for p in first.split(",") if p.strip()]
553
+
554
+ setup_py = _read_text(os.path.join(projdir, "setup.py"))
555
+ if setup_py:
556
+ if not name:
557
+ m = re.search(r"name\s*=\s*[\"']([^\"']+)[\"']", setup_py)
558
+ if m:
559
+ name = m.group(1)
560
+ if packages is None:
561
+ m = re.search(r"packages\s*=\s*\[([^\]]*)\]", setup_py)
562
+ if m:
563
+ packages = re.findall(r"[\"']([\w.]+)[\"']", m.group(1))
564
+
565
+ if packages is None:
566
+ # Auto-discovery fallback: top-level dirs with __init__.py (+ src/ layout).
567
+ found = []
568
+ for base in ("", "src"):
569
+ d = os.path.join(projdir, base) if base else projdir
570
+ try:
571
+ entries = os.listdir(d)
572
+ except OSError:
573
+ continue
574
+ for entry in entries:
575
+ full = os.path.join(d, entry)
576
+ if os.path.isdir(full) and os.path.isfile(
577
+ os.path.join(full, "__init__.py")
578
+ ):
579
+ found.append(entry)
580
+ packages = sorted(set(found)) or None
581
+
582
+ # Normalize dotted names to top-level dirs.
583
+ if packages:
584
+ tops = sorted({p.split(".")[0] for p in packages})
585
+ else:
586
+ tops = None
587
+ return name, tops
588
+
589
+
590
+ def check_project_against_wheel(wheel, projdir, rep):
591
+ name, tops = expected_packages_from_project(projdir)
592
+ if name and wheel.filename_name and _norm_name(name) != _norm_name(
593
+ wheel.filename_name
594
+ ):
595
+ rep.add(
596
+ "warning",
597
+ "project-name-mismatch",
598
+ f"project config names the distribution {name!r} "
599
+ f"but the wheel file says {wheel.filename_name!r}",
600
+ )
601
+ if not tops:
602
+ rep.add(
603
+ "info",
604
+ "project-no-packages",
605
+ "could not determine expected packages from project config",
606
+ )
607
+ return
608
+ wheel_tops = {f.split("/")[0] for f in wheel.files if "/" in f}
609
+ wheel_toplevel_py = {
610
+ f[:-3] for f in wheel.files if "/" not in f and f.endswith(".py")
611
+ }
612
+ for top in tops:
613
+ if top not in wheel_tops and top not in wheel_toplevel_py:
614
+ rep.add(
615
+ "error",
616
+ "project-package-missing",
617
+ f"package {top!r} is configured in the project but missing from the wheel",
618
+ )
619
+
620
+
621
+ # ------------------------------------------------------------------ smoke
622
+
623
+
624
+ def _top_level_modules(wheel):
625
+ mods = set()
626
+ for f in wheel.files:
627
+ if _is_dist_info(f) or "__pycache__" in f:
628
+ continue
629
+ if "/" not in f and f.endswith(".py"):
630
+ mods.add(f[:-3])
631
+ elif f.endswith("/__init__.py"):
632
+ mods.add(f.split("/")[0])
633
+ return sorted(m for m in mods if m.isidentifier())[:25]
634
+
635
+
636
+ def smoke_test_wheel(wheel, rep, timeout=180):
637
+ """Install the wheel into a throwaway venv and import top-level modules."""
638
+ mods = _top_level_modules(wheel)
639
+ if not mods:
640
+ rep.add("info", "smoke-no-modules", "smoke test skipped: no importable modules found")
641
+ return
642
+ tmp = tempfile.mkdtemp(prefix="wheeltruth-smoke-")
643
+ venv_dir = os.path.join(tmp, "venv")
644
+ try:
645
+ proc = subprocess.run(
646
+ [sys.executable, "-m", "venv", venv_dir],
647
+ capture_output=True, text=True, timeout=120,
648
+ )
649
+ except (OSError, subprocess.TimeoutExpired) as exc:
650
+ rep.add("info", "smoke-unavailable", f"smoke test unavailable: {exc}")
651
+ return
652
+ if proc.returncode != 0:
653
+ rep.add("info", "smoke-unavailable", "smoke test unavailable: venv creation failed")
654
+ return
655
+ bindir = os.path.join(venv_dir, "Scripts" if os.name == "nt" else "bin")
656
+ pip = os.path.join(bindir, "pip")
657
+ vpy = os.path.join(bindir, "python")
658
+ try:
659
+ proc = subprocess.run(
660
+ [pip, "install", "--no-deps", "--no-index", "--quiet", wheel.path],
661
+ capture_output=True, text=True, timeout=120,
662
+ )
663
+ except (OSError, subprocess.TimeoutExpired) as exc:
664
+ rep.add("warning", "smoke-install-failed", f"smoke test: pip install failed: {exc}")
665
+ return
666
+ if proc.returncode != 0:
667
+ rep.add(
668
+ "error", "smoke-install-failed",
669
+ "smoke test: pip install of the wheel failed",
670
+ detail=proc.stderr[-2000:],
671
+ )
672
+ return
673
+ failed = []
674
+ for mod in mods:
675
+ try:
676
+ proc = subprocess.run(
677
+ [vpy, "-c", f"import {mod}"],
678
+ capture_output=True, text=True, timeout=30,
679
+ )
680
+ except (OSError, subprocess.TimeoutExpired):
681
+ failed.append((mod, "timeout"))
682
+ continue
683
+ if proc.returncode != 0:
684
+ failed.append((mod, proc.stderr.strip().splitlines()[-1][:200] if proc.stderr.strip() else "import failed"))
685
+ for mod, err in failed:
686
+ rep.add("error", "smoke-import-failed", f"smoke test: import {mod} failed: {err}")
687
+ if not failed:
688
+ rep.add("info", "smoke-ok", f"smoke test: {len(mods)} top-level module(s) imported cleanly")
689
+
690
+
691
+ # ----------------------------------------------------------------- reports
692
+
693
+
694
+ def render_text(reports):
695
+ lines = []
696
+ for rep in reports:
697
+ lines.append(f"== {rep.path} ({rep.kind}) ==")
698
+ if not rep.findings:
699
+ lines.append(" OK: no issues found")
700
+ for f in rep.findings:
701
+ lines.append(f" [{f.severity.upper():7}] {f.code}: {f.message}")
702
+ lines.append("")
703
+ return "\n".join(lines).rstrip() + "\n"
704
+
705
+
706
+ def render_markdown(reports):
707
+ lines = ["# wheeltruth report", ""]
708
+ for rep in reports:
709
+ lines.append(f"## `{os.path.basename(rep.path)}` ({rep.kind})")
710
+ lines.append("")
711
+ if not rep.findings:
712
+ lines.append("OK: no issues found")
713
+ else:
714
+ lines.append("| severity | code | message |")
715
+ lines.append("|---|---|---|")
716
+ for f in rep.findings:
717
+ msg = f.message.replace("|", "\\|")
718
+ lines.append(f"| {f.severity} | `{f.code}` | {msg} |")
719
+ lines.append("")
720
+ return "\n".join(lines)
721
+
722
+
723
+ def check_artifacts(paths, project=None, smoke=False):
724
+ """Run all checks over the given artifact paths. Returns [ArtifactReport]."""
725
+ reports = []
726
+ wheels = []
727
+ sdists = []
728
+ for path in paths:
729
+ base = os.path.basename(path)
730
+ rep = None
731
+ try:
732
+ if base.endswith(".whl"):
733
+ rep = ArtifactReport(path, "wheel")
734
+ wheel = read_wheel(path)
735
+ wheels.append((wheel, rep))
736
+ check_wheel_contents(wheel, rep)
737
+ if project:
738
+ check_project_against_wheel(wheel, project, rep)
739
+ if smoke:
740
+ smoke_test_wheel(wheel, rep)
741
+ elif base.endswith((".tar.gz", ".tgz", ".zip")):
742
+ rep = ArtifactReport(path, "sdist")
743
+ sdist = read_sdist(path)
744
+ sdists.append((sdist, rep))
745
+ check_sdist_contents(sdist, rep)
746
+ else:
747
+ rep = ArtifactReport(path, "unknown")
748
+ rep.add("error", "unknown-artifact",
749
+ f"don't know how to check {base!r}: expected .whl or .tar.gz")
750
+ except (zipfile.BadZipFile, tarfile.TarError, OSError) as exc:
751
+ if rep is None:
752
+ rep = ArtifactReport(path, "unknown")
753
+ rep.add("error", "unreadable-artifact", f"could not read {base}: {exc}")
754
+ reports.append(rep)
755
+
756
+ # Cross-artifact comparison when we have both kinds.
757
+ if wheels and sdists:
758
+ # Pair each wheel with the sdist of the same distribution when possible.
759
+ for wheel, wrep in wheels:
760
+ wn = _norm_name(wheel.filename_name or (wheel.metadata.get("Name") or [""])[0])
761
+ partner = None
762
+ for sdist, _srep in sdists:
763
+ sn = _norm_name(sdist.filename_name or (sdist.pkg_info.get("Name") or [""])[0])
764
+ if wn and sn and wn == sn:
765
+ partner = sdist
766
+ break
767
+ if partner is None:
768
+ partner = sdists[0][0]
769
+ cross = ArtifactReport(f"{wheel.path} vs {partner.path}", "wheel-vs-sdist")
770
+ check_wheel_vs_sdist(wheel, partner, cross)
771
+ # Merge cross findings into the wheel's report for simpler output.
772
+ wrep.findings.extend(cross.findings)
773
+
774
+ return reports
wheeltruth/cli.py ADDED
@@ -0,0 +1,65 @@
1
+ """wheeltruth: does your built wheel/sdist actually contain what it should?"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from . import check as _check
9
+
10
+ __version__ = "0.1.0"
11
+
12
+
13
+ def _exit_code(reports):
14
+ for rep in reports:
15
+ for f in rep.findings:
16
+ if f.severity in ("warning", "error"):
17
+ return 1
18
+ # Operational failures (unreadable artifacts) are errors too, but they
19
+ # already surface as error findings above. Exit 2 is reserved for CLI
20
+ # usage errors, which argparse handles itself.
21
+ return 0
22
+
23
+
24
+ def cmd_check(args):
25
+ reports = _check.check_artifacts(args.artifacts, project=args.project, smoke=args.smoke)
26
+ if args.report == "md":
27
+ sys.stdout.write(_check.render_markdown(reports))
28
+ elif not args.quiet:
29
+ sys.stdout.write(_check.render_text(reports))
30
+ return _exit_code(reports)
31
+
32
+
33
+ def build_parser():
34
+ parser = argparse.ArgumentParser(
35
+ prog="wheeltruth",
36
+ description="Check that your built wheel/sdist actually contains "
37
+ "everything the package needs.",
38
+ )
39
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
40
+ sub = parser.add_subparsers(dest="command", required=True)
41
+
42
+ p = sub.add_parser("check", help="check built artifacts for missing content")
43
+ p.add_argument("artifacts", nargs="+", help=".whl and/or .tar.gz files to check")
44
+ p.add_argument("--project", default=None,
45
+ help="project directory with pyproject.toml/setup.cfg/setup.py "
46
+ "to derive expected packages from")
47
+ p.add_argument("--smoke", action="store_true",
48
+ help="install the wheel into a throwaway venv and import "
49
+ "top-level modules")
50
+ p.add_argument("--report", choices=["text", "md"], default="text",
51
+ help="output format (default: text)")
52
+ p.add_argument("--quiet", "-q", action="store_true",
53
+ help="suppress output; only the exit code signals issues")
54
+ p.set_defaults(func=cmd_check)
55
+ return parser
56
+
57
+
58
+ def main(argv=None):
59
+ parser = build_parser()
60
+ args = parser.parse_args(argv)
61
+ return args.func(args)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ sys.exit(main())
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: wheeltruth
3
+ Version: 0.1.0
4
+ Summary: Check that your built wheel/sdist actually contains everything the package needs
5
+ Author: hao li
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/hahahahahahahahah6/wheeltruth
8
+ Keywords: pypi,wheel,packaging,ci,sdist
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # wheeltruth
15
+
16
+ **Your tests passed. Your published wheel is missing files.**
17
+
18
+ `wheeltruth` checks that your built wheel/sdist actually contains everything the
19
+ package needs — before your users find out the hard way.
20
+
21
+ ## The problem
22
+
23
+ `twine check` verifies your README renders. Nothing in the standard toolchain
24
+ verifies that the *files* made it into the artifact. Two real cases from 2026:
25
+
26
+ - **MLX v0.32.0** (2026-07-25): the macOS ARM64 wheel shipped `py.typed` but
27
+ silently dropped every `.pyi` stub the previous release had. Downstream type
28
+ checking broke, and the test suite never noticed — because tests run against
29
+ the source tree, not the wheel.
30
+ - **OpenSpace** (2026-06-14): a tracked `host_skills/` directory vanished from
31
+ the built distribution, breaking integrations for everyone who installed it.
32
+
33
+ Build backends, MANIFEST.in glitches, and `package-data` misconfigurations drop
34
+ files quietly. `wheeltruth` inspects the artifact itself — the thing PyPI
35
+ actually serves — not your repo.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install wheeltruth
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ ```bash
46
+ # Check one or more built artifacts
47
+ wheeltruth check dist/*
48
+
49
+ # Compare a wheel against its sdist (catches files dropped between the two)
50
+ wheeltruth check dist/mypkg-1.0-py3-none-any.whl dist/mypkg-1.0.tar.gz
51
+
52
+ # Also verify expected packages from the project config
53
+ wheeltruth check dist/* --project .
54
+
55
+ # Install into a throwaway venv and import every top-level module
56
+ wheeltruth check dist/*.whl --smoke
57
+
58
+ # Machine-readable report for CI logs / PR comments
59
+ wheeltruth check dist/* --report md
60
+ ```
61
+
62
+ Exit code is `0` when clean, `1` when issues are found — drop it straight into CI:
63
+
64
+ ```yaml
65
+ - name: Build
66
+ run: python -m build
67
+ - name: Verify artifacts
68
+ run: |
69
+ pip install wheeltruth
70
+ wheeltruth check dist/*
71
+ ```
72
+
73
+ ## What it checks
74
+
75
+ **Wheel only**
76
+ - `RECORD` completeness: every file in the zip is listed, every listed file
77
+ exists, and sha256 hashes/sizes match (tampered or hand-edited wheels fail).
78
+ - `entry_points.txt`: every `console_scripts`/`gui_scripts` target resolves to
79
+ a module actually inside the wheel (no more `ModuleNotFoundError` on first run).
80
+ - Typing stub consistency: if a package ships *some* `.pyi` stubs, every
81
+ module should have one — a half-dropped stub set (the MLX case) is flagged.
82
+ - `METADATA` name/version consistency with the wheel filename.
83
+
84
+ **Wheel vs sdist**
85
+ - Files tracked in the sdist's packages that never made it into the wheel
86
+ (the OpenSpace case), and vice versa. Handles `src/` layouts and ignores
87
+ `tests/`, `docs/`, etc.
88
+
89
+ **With `--project .`**
90
+ - Packages declared in `pyproject.toml` / `setup.cfg` / `setup.py` (or
91
+ auto-discovered) actually exist in the wheel.
92
+
93
+ **With `--smoke`**
94
+ - Installs the wheel into a throwaway venv (`--no-deps --no-index`) and
95
+ imports every top-level module.
96
+
97
+ ## Limitations (v0.1)
98
+
99
+ - v0.1 is **check-only**: it reports problems, it doesn't fix your build config.
100
+ - Heuristics, not proof: "expected files" are inferred from the sdist or
101
+ project config. Exotic layouts may produce false positives — file an issue.
102
+ - `--smoke` needs a working `venv` + `pip` and takes a few seconds per wheel.
103
+ - Stub checks are consistency checks; they can't know what the *previous*
104
+ release shipped.
105
+
106
+ ## License
107
+
108
+ MIT
@@ -0,0 +1,9 @@
1
+ wheeltruth/__init__.py,sha256=4JdoQJvr1CX5mFZFzvW-lfcKbUgMzcWvuEyIHqnugjk,100
2
+ wheeltruth/check.py,sha256=E62FJrH5Z3bDOPrsAt99NYiBsFzPoHtsNBWShcEWH6s,27545
3
+ wheeltruth/cli.py,sha256=7iTbm_eehZBjreoClGt2b1gQMY5w61LjWjdOx2uAsGM,2266
4
+ wheeltruth-0.1.0.dist-info/licenses/LICENSE,sha256=OYhQDg7nxWoFtnF6J8NkFUA8NMw5TKv9a1WTXHY-fu4,1063
5
+ wheeltruth-0.1.0.dist-info/METADATA,sha256=ZKGzGlLCKI_bgdvC_QWECetVyUYhMXk1NG19P4D__Rk,3672
6
+ wheeltruth-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
7
+ wheeltruth-0.1.0.dist-info/entry_points.txt,sha256=t1dDTJuYwj-E_IGPWQp7Aaa62_nJHtMPxxue6rNJN3U,51
8
+ wheeltruth-0.1.0.dist-info/top_level.txt,sha256=pCpdnnYQLdO5dbW7QiSuf_p6C8byCUquEw3LQJ3QDgs,11
9
+ wheeltruth-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ wheeltruth = wheeltruth.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hao li
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ wheeltruth