Repository navigation
Expand file tree
/
Copy pathbenchcode_pip.py
More file actions
411 lines (357 loc) · 16 KB
/
Copy pathbenchcode_pip.py
File metadata and controls
411 lines (357 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""
benchcode_pip — `pip` for an app whose packages are built in
═════════════════════════════════════════════════════════════
BenchCode ships its Python packages inside the app and works offline; pip
itself is left out of the shipped bundle (it downloads and installs code).
So `pip list`, `pip show` and `pip freeze` — the commands people use to see
what they have — are answered here from the installed distributions'
metadata (importlib.metadata), in pip's own output formats, so a notebook
copied from Colab or a tutorial still works. Commands that would download
(`install`, `download`, `wheel`, …) say in one line why they can't, and
name the packages that are already built in.
Used by the terminal's `pip` (offlinai_shell, when pip isn't importable)
and by the notebook's `pip …`, `!pip …` and `%pip …` lines.
import benchcode_pip
rc = benchcode_pip.main(["list"]) # prints, returns an exit code
"""
import json
import os
import re
import sys
_OFFLINE_LINE = "BenchCode's packages come built in and work offline. Library lists every package included."
# Verbs that would reach the internet or change installed code.
_NETWORK_VERBS = {"install", "download", "wheel", "index", "search", "lock"}
def _md():
import importlib.metadata as md
return md
def _canon(name: str) -> str:
"""PEP 503 normalised name: 'Scikit_Learn' and 'scikit-learn' match."""
return re.sub(r"[-_.]+", "-", name or "").lower()
def _user_site() -> str:
return os.path.expanduser("~/Documents/site-packages")
def _location(dist) -> str:
try:
return str(dist.locate_file("")).rstrip("/")
except Exception:
return ""
def _is_user_installed(dist) -> bool:
loc = _location(dist)
return bool(loc) and ("/Documents/site-packages" in loc or loc.startswith(_user_site()))
def installed():
"""Every installed distribution once, by normalised name: the first
on sys.path wins, as it would for an import."""
seen = {}
for dist in _md().distributions():
try:
name = dist.metadata["Name"]
except Exception:
name = None
if not name:
continue
key = _canon(name)
if key not in seen:
seen[key] = dist
return seen
def _requirement_names(dist):
"""Names `dist` needs at run time (no extras), markers evaluated for
this Python where `packaging` is available."""
out = []
for raw in (dist.requires or []):
try:
from packaging.requirements import Requirement
req = Requirement(raw)
if req.marker is not None and not req.marker.evaluate({"extra": ""}):
continue
out.append((req.name, req))
except Exception:
if "extra ==" in raw or "extra==" in raw:
continue
m = re.match(r"\s*([A-Za-z0-9][A-Za-z0-9._-]*)", raw)
if m:
out.append((m.group(1), None))
return out
def _print_table(rows, headers):
widths = [max(len(str(r[i])) for r in [headers] + rows) for i in range(len(headers))]
def line(cells):
return " ".join(str(c).ljust(w) for c, w in zip(cells, widths)).rstrip()
print(line(headers))
print(" ".join("-" * w for w in widths))
for r in rows:
print(line(r))
# ─── list / freeze ────────────────────────────────────────────────
def _list(args):
fmt = "columns"
verbose = False
user_only = False
not_required = False
i = 0
while i < len(args):
a = args[i]
if a in ("-o", "--outdated", "-u", "--uptodate"):
print("pip list %s compares with PyPI, which needs the internet; "
"BenchCode works offline." % a)
return 1
if a.startswith("--format="):
fmt = a.split("=", 1)[1]
elif a == "--format" and i + 1 < len(args):
fmt = args[i + 1]; i += 1
elif a in ("-v", "--verbose"):
verbose = True
elif a == "--user":
user_only = True
elif a == "--not-required":
not_required = True
elif a in ("-e", "--editable"):
return 0 # nothing here is installed in editable mode
elif a in ("-l", "--local", "--disable-pip-version-check", "--no-color", "-q", "--quiet",
"--exclude-editable", "--include-editable"):
pass
else:
sys.stderr.write("ERROR: pip list: no such option: %s\n" % a)
return 2
i += 1
dists = installed()
items = sorted(dists.items())
if user_only:
items = [(k, d) for k, d in items if _is_user_installed(d)]
if not_required:
needed = set()
for d in dists.values():
needed.update(_canon(n) for n, _ in _requirement_names(d))
items = [(k, d) for k, d in items if k not in needed]
if fmt == "freeze":
for _, d in items:
print("%s==%s" % (d.metadata["Name"], d.version))
elif fmt == "json":
print(json.dumps([{"name": d.metadata["Name"], "version": d.version} for _, d in items]))
elif fmt == "columns":
if verbose:
rows = [(d.metadata["Name"], d.version, _location(d),
"pip" if _is_user_installed(d) else "BenchCode") for _, d in items]
_print_table(rows, ("Package", "Version", "Location", "Installer"))
else:
_print_table([(d.metadata["Name"], d.version) for _, d in items], ("Package", "Version"))
else:
sys.stderr.write("ERROR: pip list: invalid --format: %s (choose columns, freeze or json)\n" % fmt)
return 2
return 0
def _freeze(args):
for _, d in sorted(installed().items()):
print("%s==%s" % (d.metadata["Name"], d.version))
return 0
# ─── show ─────────────────────────────────────────────────────────
def _show(args):
files = "-f" in args or "--files" in args
verbose = "-v" in args or "--verbose" in args
names = [a for a in args if not a.startswith("-")]
if not names:
sys.stderr.write("ERROR: Please provide a package name or names.\n")
return 1
dists = installed()
found, missing = [], []
for n in names:
d = dists.get(_canon(n))
(found if d is not None else missing).append(d if d is not None else n)
if missing:
sys.stderr.write("WARNING: Package(s) not found: %s\n" % ", ".join(missing))
required_by = {}
if found:
wanted = {_canon(d.metadata["Name"]) for d in found}
for d in dists.values():
for n, _ in _requirement_names(d):
if _canon(n) in wanted:
required_by.setdefault(_canon(n), set()).add(d.metadata["Name"])
for i, d in enumerate(found):
m = d.metadata
if i:
print("---")
home = m.get("Home-page") or ""
if not home:
for pu in (m.get_all("Project-URL") or []):
label, _, url = pu.partition(",")
if label.strip().lower() in ("homepage", "home", "source", "repository"):
home = url.strip()
break
lic = m.get("License-Expression") or m.get("License") or ""
lic = lic.strip().splitlines()[0] if lic.strip() else ""
requires = sorted({n for n, _ in _requirement_names(d)}, key=str.lower)
print("Name: %s" % m["Name"])
print("Version: %s" % d.version)
print("Summary: %s" % (m.get("Summary") or ""))
print("Home-page: %s" % home)
print("Author: %s" % (m.get("Author") or ""))
print("Author-email: %s" % (m.get("Author-email") or ""))
print("License: %s" % lic)
print("Location: %s" % os.path.dirname(_location(d) + "/x"))
print("Requires: %s" % ", ".join(requires))
print("Required-by: %s" % ", ".join(sorted(required_by.get(_canon(m["Name"]), ()), key=str.lower)))
if verbose:
print("Metadata-Version: %s" % (m.get("Metadata-Version") or ""))
print("Installer: %s" % ("pip" if _is_user_installed(d) else "BenchCode (built in)"))
cls = m.get_all("Classifier") or []
print("Classifiers:")
for c in cls:
print(" %s" % c)
eps = list(getattr(d, "entry_points", []) or [])
print("Entry-points:")
for ep in eps:
print(" [%s] %s = %s" % (ep.group, ep.name, ep.value))
if files:
print("Files:")
for f in (d.files or []):
print(" %s" % f)
return 1 if missing and not found else 0
# ─── check ────────────────────────────────────────────────────────
def _check(args):
dists = installed()
problems = []
for key, d in sorted(dists.items()):
for name, req in _requirement_names(d):
other = dists.get(_canon(name))
if other is None:
problems.append("%s %s requires %s, which is not installed."
% (d.metadata["Name"], d.version, name))
elif req is not None and req.specifier and not req.specifier.contains(other.version, prereleases=True):
problems.append("%s %s has requirement %s%s, but you have %s %s."
% (d.metadata["Name"], d.version, name, req.specifier,
other.metadata["Name"], other.version))
for p in problems:
print(p)
if not problems:
print("No broken requirements found.")
return 1 if problems else 0
# ─── install and the other network verbs ──────────────────────────
def _requested(args):
"""Package names an install line asks for, from its arguments and any
-r requirements files, without versions or extras."""
names = []
i = 0
with_value = {"-r", "--requirement", "-c", "--constraint", "-i", "--index-url", "--extra-index-url",
"-f", "--find-links", "-t", "--target", "--prefix", "--root", "--platform",
"--python-version", "--implementation", "--abi", "--no-binary", "--only-binary",
"--report", "--upgrade-strategy", "-d", "--dest", "-w", "--wheel-dir"}
while i < len(args):
a = args[i]
if a in ("-r", "--requirement") and i + 1 < len(args):
try:
with open(os.path.expanduser(args[i + 1]), encoding="utf-8") as fh:
for line in fh:
line = line.split("#", 1)[0].strip()
if line and not line.startswith("-"):
names.append(line)
except OSError as e:
sys.stderr.write("ERROR: Could not open requirements file: %s\n" % e)
i += 2
continue
if a in with_value:
i += 2
continue
if not a.startswith("-"):
names.append(a)
i += 1
return names
def _satisfies(dist, spec):
"""Whether the built-in version meets a pinned spec ("torch==2.1")."""
try:
from packaging.requirements import Requirement
req = Requirement(spec)
return not req.specifier or req.specifier.contains(dist.version, prereleases=True)
except Exception:
return True
def _is_local(spec):
"""A requirement that names a file or folder the user has."""
s = spec.strip()
if s.startswith(("./", "../", "/", "~")) or s.lower().endswith(
(".whl", ".zip", ".tar.gz", ".tgz", ".tar", ".tar.bz2", ".tar.xz")):
return True
return os.path.exists(os.path.expanduser(s)) and ("/" in s or os.path.isdir(s) or s.endswith(".py"))
def _network(verb, args):
dists = installed()
if verb == "install":
missing = []
specs = _requested(args)
if not specs:
sys.stderr.write('ERROR: You must give at least one requirement to install (see "pip help install")\n')
return 1
local = [s for s in specs if _is_local(s)]
if local:
print("A package file you have is added with pkg (pure Python only):")
for spec in local:
print(" pkg add %s" % spec)
return 1
for spec in specs:
bare = re.split(r"[\[<>=!~;@ ]", spec, 1)[0]
d = dists.get(_canon(bare))
if d is not None and not _satisfies(d, spec):
d = None # a different version than the one built in
if d is not None:
print("Requirement already satisfied: %s %s (built into BenchCode)"
% (d.metadata["Name"], d.version))
else:
missing.append(spec)
if missing:
print("pip can't download %s: %s" % (", ".join(missing), _OFFLINE_LINE))
print("A pure-Python package's file (.whl or .tar.gz) or its GitHub link: pkg add adds it.")
return 1
return 0
print("pip %s isn't available: %s" % (verb, _OFFLINE_LINE))
return 1
# ─── entry point ──────────────────────────────────────────────────
_USAGE = """Usage:
pip <command> [options]
Commands that work here (BenchCode reads the built-in packages; no internet needed):
list List installed packages.
show <package> [...] Show information about installed packages (-f lists files).
freeze Output installed packages in requirements format.
check Verify installed packages have compatible dependencies.
Not available (they download or remove code):
install, download, wheel, uninstall, index, search
BenchCode's packages come built in and work offline; Library lists every one."""
def main(argv=None):
"""Run one pip command line (without the leading 'pip'). Prints like pip
and returns its exit code."""
args = list(sys.argv[1:] if argv is None else argv)
# Global options pip takes before the verb.
while args and args[0] in ("-q", "--quiet", "-v", "--verbose", "--no-color", "--isolated",
"--disable-pip-version-check", "--no-cache-dir", "--no-input"):
args.pop(0)
if not args or args[0] in ("help", "-h", "--help", "-H", "--h", "-help", "-?", "/?"):
print(_USAGE)
return 0
if args[0] in ("-V", "--version", "version"):
print("pip (BenchCode offline: list, show, freeze and check read the built-in packages; "
"Python %d.%d)" % sys.version_info[:2])
return 0
verb, rest = args[0], args[1:]
if any(a in ("-h", "--help") for a in rest):
print(_USAGE)
return 0
if verb == "list":
return _list(rest)
if verb == "freeze":
return _freeze(rest)
if verb == "show":
return _show(rest)
if verb == "check":
return _check(rest)
if verb == "uninstall":
names = [a for a in rest if not a.startswith("-")]
dists = installed()
mine = [n for n in names if _canon(n) in dists and _is_user_installed(dists[_canon(n)])]
if mine:
print("Packages you added come out with pkg:")
for n in mine:
print(" pkg remove %s" % n)
return 1
print("pip uninstall isn't available here: BenchCode's packages are built into the app "
"and can't be removed.")
return 1
if verb in _NETWORK_VERBS:
return _network(verb, rest)
if verb in ("cache", "config", "debug", "hash", "completion", "inspect"):
print("pip %s isn't part of BenchCode's offline pip. %s" % (verb, "Try pip list or pip show."))
return 1
sys.stderr.write('ERROR: unknown command "%s"\n' % verb)
return 1
if __name__ == "__main__":
sys.exit(main())