dist-precheck 1.0.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.
@@ -0,0 +1,302 @@
1
+ #!/usr/bin/env python3
2
+ """dist-precheck: catch the archive problems PyPI rejects *before* you upload.
3
+
4
+ Stdlib only.
5
+ Usage: dist-precheck dist/* archive checks + first-upload name check (exit 1 on any ERROR)
6
+ dist-precheck name <project> is this name free *and allowed* on PyPI?
7
+ Rules follow https://docs.pypi.org/archives/ and the PyPI blog post of 2026-11-18
8
+ ("Stricter checks for uploaded distributions on PyPI"). WARN = allowed today but
9
+ PyPI has said it will reject it later (GNU tarballs, any ZIP archive comment).
10
+ """
11
+ import email.parser, gzip, io, json, os, re, struct, sys, tarfile, time, unicodedata, urllib.error, urllib.request, zipfile
12
+
13
+ UNSUPPORTED_PLATFORM = re.compile(r"^linux_(x86_64|i686|aarch64|armv7l|ppc64le|s390x|riscv64)$")
14
+ VENDOR_PAX = re.compile(r"^[A-Z][A-Z0-9]*\.") # e.g. SCHILY., LIBARCHIVE., GNU.
15
+ STD_PAX = {"atime","charset","comment","gid","gname","hdrcharset","linkpath","mtime","path","size","uid","uname","ctime"}
16
+
17
+ def unprintable(name):
18
+ # docs.pypi.org/archives says 0x00-0x20 and 0x7F, but PyPI accepts spaces in practice
19
+ # (setuptools 84.2.1's wheel has 'launcher manifest.xml'), so space is allowed here.
20
+ return any((ord(c) < 0x20) or ord(c) == 0x7F for c in name)
21
+
22
+ def check_wheel(path):
23
+ out = []
24
+ data = open(path, "rb").read()
25
+ eocd = data.rfind(b"PK\x05\x06")
26
+ if eocd < 0:
27
+ return [("ERROR", "not a ZIP archive (no end-of-central-directory record)")]
28
+ if data.count(b"PK\x05\x06") > 1 and data.find(b"PK\x05\x06") != eocd:
29
+ out.append(("ERROR", "more than one end-of-central-directory record"))
30
+ (_, disk, cd_disk, n_disk, n_total, cd_size, cd_off, clen) = struct.unpack("<IHHHHIIH", data[eocd:eocd+22])
31
+ comment = data[eocd+22:eocd+22+clen]
32
+ if disk or cd_disk or n_disk != n_total:
33
+ out.append(("ERROR", "multi-disk ZIP"))
34
+ if eocd + 22 + clen != len(data):
35
+ out.append(("ERROR", f"{len(data)-(eocd+22+clen)} bytes of trailing data after the ZIP"))
36
+ if clen:
37
+ out.append(("WARN", f"archive-level ZIP comment ({clen} bytes); PyPI says it will reject all ZIP comments"))
38
+ if cd_off + cd_size != eocd:
39
+ out.append(("ERROR", "central directory size/offset does not line up with its end record"))
40
+ names, p, ranges = {}, cd_off, []
41
+ for _ in range(n_total):
42
+ if data[p:p+4] != b"PK\x01\x02":
43
+ out.append(("ERROR", "malformed central directory entry")); break
44
+ (flags, csize, lho, nlen, xlen, mclen) = (struct.unpack("<H", data[p+8:p+10])[0], struct.unpack("<I", data[p+20:p+24])[0],
45
+ struct.unpack("<I", data[p+42:p+46])[0], *struct.unpack("<HHH", data[p+28:p+34]))
46
+ raw = data[p+46:p+46+nlen]
47
+ try:
48
+ name = raw.decode("utf-8")
49
+ except UnicodeDecodeError:
50
+ name = raw.decode("cp437"); out.append(("ERROR", f"filename is not UTF-8: {name!r}"))
51
+ if unprintable(name):
52
+ out.append(("ERROR", f"unprintable character in filename {name!r}"))
53
+ if name in names:
54
+ out.append(("ERROR", f"duplicate entry {name!r}"))
55
+ names[name] = 1
56
+ if mclen:
57
+ out.append(("ERROR", f"member comment on {name!r}"))
58
+ if flags & 0x08:
59
+ out.append(("ERROR", f"{name!r} uses a data descriptor (PyPI: 'ZIP contains a data descriptor')"))
60
+ if data[lho:lho+4] != b"PK\x03\x04":
61
+ out.append(("ERROR", f"central directory points to no local header for {name!r}"))
62
+ else:
63
+ lflags = struct.unpack("<H", data[lho+6:lho+8])[0]
64
+ lnlen, lxlen = struct.unpack("<HH", data[lho+26:lho+30])
65
+ if lflags & 0x08 and not flags & 0x08:
66
+ out.append(("ERROR", f"{name!r} local header uses a data descriptor"))
67
+ end = lho + 30 + lnlen + lxlen + csize + (16 if lflags & 0x08 else 0)
68
+ ranges.append((lho, end))
69
+ p += 46 + nlen + xlen + mclen
70
+ ranges.sort()
71
+ if ranges and ranges[0][0] != 0:
72
+ out.append(("ERROR", f"{ranges[0][0]} bytes of prepended data before the first entry"))
73
+ pos = 0
74
+ for a, b in ranges:
75
+ if a > pos:
76
+ out.append(("ERROR", f"{a-pos} unreferenced bytes at offset {pos} (file missing from central directory?)"))
77
+ pos = max(pos, b)
78
+ if ranges and pos < cd_off:
79
+ out.append(("ERROR", f"{cd_off-pos} unreferenced bytes before the central directory"))
80
+ m = re.match(r"^(?P<n>.+?)-(?P<v>[^-]+)(-\d[^-]*)?-(?P<py>[^-]+)-(?P<abi>[^-]+)-(?P<plat>[^-]+)\.whl$", os.path.basename(path))
81
+ if not m:
82
+ out.append(("ERROR", "wheel filename does not follow name-version-py-abi-platform.whl"))
83
+ else:
84
+ for plat in m["plat"].split("."):
85
+ if UNSUPPORTED_PLATFORM.match(plat):
86
+ out.append(("ERROR", f"platform tag {plat!r} is rejected by PyPI; use manylinux/musllinux (auditwheel repair)"))
87
+ return out
88
+
89
+ def check_sdist(path):
90
+ out = []
91
+ raw = open(path, "rb").read()
92
+ try:
93
+ tar = gzip.decompress(raw)
94
+ except Exception as e:
95
+ return [("ERROR", f"not a gzip file: {e}")]
96
+ off, kinds = 0, set()
97
+ while off + 512 <= len(tar):
98
+ h = tar[off:off+512]
99
+ if h == b"\0" * 512:
100
+ break
101
+ magic, typ = h[257:265], h[156:157]
102
+ name = h[0:100].split(b"\0")[0]
103
+ size = int((h[124:136].split(b"\0")[0].strip() or b"0"), 8) if h[124] < 0x80 else int.from_bytes(h[125:136], "big")
104
+ if magic == b"ustar\x0000": kinds.add("ustar")
105
+ elif magic == b"ustar \x00": kinds.add("gnu")
106
+ else: kinds.add("v7")
107
+ if typ in (b"L", b"K"): out.append(("WARN", f"GNU long-name header ({typ.decode()}) for {name[:60]!r}"))
108
+ if typ == b"S": out.append(("ERROR", f"GNU sparse member {name[:60]!r}"))
109
+ if typ in (b"x", b"g"):
110
+ body = tar[off+512:off+512+size].decode("utf-8", "replace")
111
+ for line in body.splitlines():
112
+ m = re.match(r"^\d+ ([^=]+)=", line)
113
+ if not m: continue
114
+ k = m.group(1)
115
+ if k.startswith("GNU.sparse"): out.append(("ERROR", f"pax sparse member key {k!r}"))
116
+ elif VENDOR_PAX.match(k): out.append(("ERROR", f"pax vendor extension {k!r} (e.g. macOS bsdtar xattrs; set COPYFILE_DISABLE=1 / use a build backend)"))
117
+ try:
118
+ name.decode("utf-8")
119
+ except UnicodeDecodeError:
120
+ out.append(("ERROR", f"member name is not UTF-8: {name[:60]!r}"))
121
+ off += 512 + ((size + 511) // 512) * 512
122
+ if "v7" in kinds: out.append(("ERROR", "V7-format tar headers (PyPI rejects these since Nov 2026)"))
123
+ if "gnu" in kinds: out.append(("WARN", "GNU-format tar (allowed today; PyPI plans to reject, see pypi/warehouse#21012). Use tar --format=pax or a build backend"))
124
+ return out
125
+
126
+ __version__ = "1.0.0"
127
+
128
+ # ---------------------------------------------------------------- name checks
129
+ # Mirrors pypi/warehouse ProjectService.check_project_name (warehouse/packaging/services.py):
130
+ # 1) PROJECT_NAME_RE 2) stdlib module names 3) existing project (PEP 503 normalized)
131
+ # 4) admin-prohibited names (not public, can't be checked) 5) "too similar": ultranormalize_name()
132
+ # equal to an existing project's (migration d18d443f89f0: drop . _ -, l/L/i/I -> 1, o/O -> 0, lower).
133
+ PROJECT_NAME_RE = re.compile(r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])\Z", re.IGNORECASE | re.ASCII)
134
+ SIMPLE_URL = "https://pypi.org/simple/"
135
+
136
+ def normalize(name):
137
+ return re.sub(r"[-_.]+", "-", name).lower()
138
+
139
+ def ultranormalize(name):
140
+ s = re.sub(r"[._-]", "", name)
141
+ s = re.sub(r"[lLiI]", "1", s)
142
+ s = re.sub(r"[oO]", "0", s)
143
+ return s.lower()
144
+
145
+ _STDLIB_CACHE = None
146
+
147
+ def _stdlib_names():
148
+ """Canonical names Warehouse blocks as stdlib modules (vendored list, see stdlib_prohibited.txt)."""
149
+ global _STDLIB_CACHE
150
+ if _STDLIB_CACHE is None:
151
+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stdlib_prohibited.txt")
152
+ with open(path, encoding="utf-8") as f:
153
+ _STDLIB_CACHE = {l.strip() for l in f if l.strip() and not l.startswith("#")}
154
+ _STDLIB_CACHE |= {normalize(n) for n in getattr(sys, "stdlib_module_names", ())}
155
+ return _STDLIB_CACHE
156
+
157
+ def load_index(cache_dir=None, max_age=86400, url=SIMPLE_URL):
158
+ """All project names on PyPI (PEP 691 JSON simple index, ~10 MB gzip), cached for a day."""
159
+ cache_dir = cache_dir or os.path.join(os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache")), "dist-precheck")
160
+ path = os.path.join(cache_dir, "simple-index.json")
161
+ if os.path.exists(path) and time.time() - os.path.getmtime(path) < max_age:
162
+ with open(path, encoding="utf-8") as f:
163
+ return json.load(f)
164
+ req = urllib.request.Request(url, headers={"Accept": "application/vnd.pypi.simple.v1+json",
165
+ "Accept-Encoding": "gzip", "User-Agent": f"dist-precheck/{__version__}"})
166
+ with urllib.request.urlopen(req, timeout=120) as r:
167
+ raw = r.read()
168
+ if r.headers.get("Content-Encoding") == "gzip":
169
+ raw = gzip.decompress(raw)
170
+ names = [p["name"] for p in json.loads(raw)["projects"]]
171
+ os.makedirs(cache_dir, exist_ok=True)
172
+ tmp = path + ".tmp"
173
+ with open(tmp, "w", encoding="utf-8") as f:
174
+ json.dump(names, f)
175
+ os.replace(tmp, path)
176
+ return names
177
+
178
+ def check_name(name, index):
179
+ """Return (verdict, message). verdict: TAKEN (exists; fine if it's yours), FREE, or one of the rejections."""
180
+ if not PROJECT_NAME_RE.match(name):
181
+ return "INVALID", f"{name!r} is not a valid project name (letters, digits, . _ -; must start and end with a letter or digit)"
182
+ n = normalize(name)
183
+ if n in _stdlib_names():
184
+ return "STDLIB", f"{name!r} matches a Python standard-library module; PyPI refuses it"
185
+ by_norm = {}
186
+ by_ultra = {}
187
+ for p in index:
188
+ by_norm.setdefault(normalize(p), p)
189
+ by_ultra.setdefault(ultranormalize(p), []).append(p)
190
+ if n in by_norm:
191
+ return "TAKEN", f"{by_norm[n]!r} already exists on PyPI (fine if it is your project)"
192
+ similar = by_ultra.get(ultranormalize(name), [])
193
+ if similar:
194
+ return "TOO_SIMILAR", (f"PyPI will refuse {name!r} as too similar to existing {', '.join(repr(s) for s in similar[:5])} "
195
+ f"(same name once . _ - are dropped, l/i read as 1 and o as 0). Pick another name, "
196
+ f"or ask in pypi/support for a name-similarity review")
197
+ return "FREE", f"{name!r} is free and passes PyPI's public name rules (admin-prohibited names can't be checked)"
198
+
199
+ SUFFIXES = ("py", "kit", "tool", "lib", "sdk", "cli", "core", "io", "dev", "hq")
200
+
201
+ def suggest_names(name, index, limit=5):
202
+ """Free alternatives for a refused or taken name, checked with the same rules as check_name."""
203
+ norms = {normalize(p) for p in index}
204
+ ultras = {ultranormalize(p) for p in index}
205
+ stdlib = _stdlib_names()
206
+ base = normalize(name)
207
+ cands = [f"{base}-{s}" for s in SUFFIXES] + [f"py-{base}", f"{base}2", f"{base}-ai"]
208
+ out = []
209
+ for c in cands:
210
+ if (PROJECT_NAME_RE.match(c) and c not in stdlib and c not in norms
211
+ and ultranormalize(c) not in ultras and c not in out):
212
+ out.append(c)
213
+ if len(out) >= limit:
214
+ break
215
+ return out
216
+
217
+ def dist_name(path):
218
+ """Project name from a wheel's METADATA or an sdist's PKG-INFO."""
219
+ try:
220
+ if path.endswith(".whl"):
221
+ with zipfile.ZipFile(path) as z:
222
+ meta = next(m for m in z.namelist() if m.count("/") == 1 and m.endswith(".dist-info/METADATA"))
223
+ text = z.read(meta).decode("utf-8", "replace")
224
+ else:
225
+ with tarfile.open(path) as t:
226
+ m = next(m for m in t.getmembers() if m.name.count("/") == 1 and m.name.endswith("/PKG-INFO"))
227
+ text = t.extractfile(m).read().decode("utf-8", "replace")
228
+ return email.parser.Parser().parsestr(text, headersonly=True).get("Name")
229
+ except Exception:
230
+ return None
231
+
232
+ def project_exists(name, url=SIMPLE_URL):
233
+ req = urllib.request.Request(url + normalize(name) + "/", headers={"Accept": "application/vnd.pypi.simple.v1+json",
234
+ "User-Agent": f"dist-precheck/{__version__}"})
235
+ try:
236
+ with urllib.request.urlopen(req, timeout=30):
237
+ return True
238
+ except urllib.error.HTTPError as e:
239
+ if e.code == 404:
240
+ return False
241
+ raise
242
+
243
+ USAGE = """usage: dist-precheck <dist files>... [--no-name-check]
244
+ dist-precheck name <project>... [--no-suggest]
245
+ dist-precheck --version
246
+
247
+ Check built wheels and sdists against PyPI's upload rules, and on a first upload
248
+ check the project name. Exit 1 if PyPI would reject anything.
249
+
250
+ --no-name-check skip the first-upload name check (no network needed)
251
+ --no-suggest with 'name', do not print free alternative names"""
252
+
253
+ def main(argv=None):
254
+ argv = list(sys.argv[1:] if argv is None else argv)
255
+ if argv[:1] == ["--version"]:
256
+ print(__version__); return 0
257
+ if argv[:1] in (["-h"], ["--help"]):
258
+ print(USAGE); return 0
259
+ if argv[:1] == ["name"]:
260
+ if len(argv) < 2:
261
+ print("usage: dist-precheck name <project> [<project>...] [--no-suggest]"); return 2
262
+ index = load_index()
263
+ bad = 0
264
+ for nm in [a for a in argv[1:] if not a.startswith("--")]:
265
+ verdict, msg = check_name(nm, index)
266
+ bad += verdict not in ("FREE", "TAKEN")
267
+ print(f"{verdict:<11} {msg}")
268
+ if verdict in ("TOO_SIMILAR", "TAKEN", "STDLIB") and "--no-suggest" not in argv:
269
+ alts = suggest_names(nm, index)
270
+ if alts:
271
+ print(f"{'':<11} free alternatives (same rules): {', '.join(alts)}")
272
+ return 1 if bad else 0
273
+ skip_name = "--no-name-check" in argv
274
+ files = [f for f in argv if f.endswith((".whl", ".tar.gz"))]
275
+ if not files:
276
+ print(USAGE); return 2
277
+ errors = 0
278
+ for f in files:
279
+ res = check_wheel(f) if f.endswith(".whl") else check_sdist(f)
280
+ e = sum(1 for lvl, _ in res if lvl == "ERROR")
281
+ errors += e
282
+ print(f"{'FAIL' if e else 'OK '} {os.path.basename(f)}")
283
+ for lvl, msg in res:
284
+ print(f" {lvl}: {msg}")
285
+ if not skip_name:
286
+ names = sorted({n for n in (dist_name(f) for f in files) if n})
287
+ for nm in names:
288
+ try:
289
+ if project_exists(nm):
290
+ print(f"NAME {nm}: already on PyPI, so this is not a first upload (name check skipped)")
291
+ continue
292
+ verdict, msg = check_name(nm, load_index())
293
+ except (urllib.error.URLError, OSError) as ex:
294
+ print(f"NAME {nm}: WARN could not reach PyPI ({ex}); name not checked"); continue
295
+ print(f"NAME {nm}: {verdict} {msg}")
296
+ if verdict not in ("FREE", "TAKEN"):
297
+ errors += 1
298
+ alts = suggest_names(nm, load_index())
299
+ if alts:
300
+ print(f"NAME {nm}: free alternatives (same rules): {', '.join(alts)}")
301
+ return 1 if errors else 0
302
+
@@ -0,0 +1,4 @@
1
+ import sys
2
+ from . import main
3
+
4
+ sys.exit(main())