Repository navigation
Expand file tree
/
Copy pathbenchcode_custom.py
More file actions
1405 lines (1260 loc) · 56.8 KB
/
Copy pathbenchcode_custom.py
File metadata and controls
1405 lines (1260 loc) · 56.8 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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
benchcode_custom — your own terminal commands and your own Python packages
══════════════════════════════════════════════════════════════════════════
Behind the terminal's `cmd`, `alias` and `pkg` commands (offlinai_shell).
Commands
One file each in My work › Commands (~/Documents/Workspace/Commands):
<name>.py runs as a Python script, the arguments in sys.argv[1:]
<name>.sh terminal lines run in order, as if typed, with $1 … $9,
$@, $* and $# standing for the arguments
A file put there by hand is a command too.
Packages
Pure-Python packages the user brings (a .whl, .zip or .tar.gz, a package
folder, a single .py file, or a link to a GitHub / GitLab / Codeberg /
Bitbucket repository or a file in one) are copied into ~/Documents/site-packages,
which is on sys.path for the terminal, the editor's Run and notebooks.
Each gets a small .dist-info (INSTALLER "BenchCode", a RECORD of its
files), so `pip list` shows it and `pkg remove` knows what to take out.
Only a link the user gives is fetched (as the terminal's `git clone` fetches a
repository: its archive over HTTPS); nothing is looked up by name. Code with
native parts (.so, .dylib) is refused: iOS only runs native code that ships
inside the app. Every file added stays readable and editable (`pkg edit`,
`cmd edit`).
"""
import builtins
import email.parser
import importlib
import importlib.machinery
import json
import keyword
import os
import re
import shlex
import shutil
import sys
import tarfile
import tempfile
import time
import zipfile
from pathlib import Path
INSTALLER = "BenchCode"
NATIVE_SUFFIXES = (".so", ".dylib", ".pyd", ".dll", ".a", ".dSYM")
SOURCE_ARCHIVES = (".tar.gz", ".tgz", ".tar", ".tar.bz2", ".tbz", ".tar.xz", ".txz")
# Packages whose job is fetching code from the internet; BenchCode works offline.
NOT_ADDABLE = {"pip": "pip downloads packages from the internet, and BenchCode works offline"}
# Folders in a project that are never part of what gets imported.
NOT_PACKAGES = {
"test", "tests", "testing", "doc", "docs", "example", "examples", "benchmark", "benchmarks",
"build", "dist", "scripts", "tools", "bin", "venv", "env", "site-packages", "__pycache__",
}
NOT_MODULES = {
"setup", "conftest", "noxfile", "tasks", "fabfile", "runtests", "tests", "test",
"ez_setup", "bootstrap", "manage", "setup_build", "build_backend",
}
MAX_UNPACKED = 512 * 1024 * 1024
_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_-]{0,39}$")
class Refused(Exception):
"""A request we turn down, with the words to show."""
# ─── places ──────────────────────────────────────────────────────────
def commands_dir() -> Path:
return Path("~/Documents/Workspace/Commands").expanduser()
def user_site() -> Path:
return Path("~/Documents/site-packages").expanduser()
def _home_short(p) -> str:
s, home = str(p), os.path.expanduser("~")
return "~" + s[len(home):] if s.startswith(home + os.sep) else s
def _canon(name: str) -> str:
return re.sub(r"[-_.]+", "-", name or "").lower()
def _dist_stem(name: str) -> str:
return re.sub(r"[-_.]+", "_", name or "")
def open_in_editor(path) -> None:
"""Ask the app's editor to open `path` (CodeEditorViewController watches
this signal file)."""
sig = os.path.join(tempfile.gettempdir(), "latex_signals")
try:
os.makedirs(sig, exist_ok=True)
with open(os.path.join(sig, "open_in_editor.txt"), "w", encoding="utf-8") as f:
f.write(str(path) + "\n")
except OSError:
pass
# ═══ commands ════════════════════════════════════════════════════════
def find_command(name: str):
"""The file that makes `name` a command, or None."""
if not name or not _NAME_RE.match(name):
return None
d = commands_dir()
for ext in (".py", ".sh"):
p = d / (name + ext)
if p.is_file():
return p
return None
def list_commands():
"""[(name, path)] for every command file, sorted by name."""
d = commands_dir()
out = {}
try:
entries = sorted(d.iterdir())
except OSError:
return []
for p in entries:
if p.suffix in (".py", ".sh") and p.is_file() and _NAME_RE.match(p.stem):
out.setdefault(p.stem, p) # .py before .sh (sorted)
return sorted(out.items())
def summary(path) -> str:
"""First line of the docstring, or the first comment, of a command file,
without a leading "<name> — " (the list shows the name already)."""
line = _first_line(path)
stem = re.escape(Path(path).stem)
return re.sub(r"^%s\s*[—–:-]+\s*" % stem, "", line)
def _first_line(path) -> str:
try:
text = Path(path).read_text(encoding="utf-8", errors="replace")
except OSError:
return ""
if Path(path).suffix == ".py":
m = re.match(r'\s*(?:#[^\n]*\n\s*)*(?:[rRuU]?)("""|\'\'\')(.*?)\1', text, re.S)
if m:
first = m.group(2).strip().splitlines()
return first[0].strip() if first else ""
for line in text.splitlines():
s = line.strip()
if s.startswith("#!"):
continue
if s.startswith("#"):
return s.lstrip("#").strip()
if s:
break
return ""
def help_text(path) -> str:
"""What `help <name>` / `<name> --help` shows for a command file."""
p = Path(path)
try:
text = p.read_text(encoding="utf-8", errors="replace")
except OSError:
return ""
if p.suffix == ".py":
m = re.match(r'\s*(?:#[^\n]*\n\s*)*(?:[rRuU]?)("""|\'\'\')(.*?)\1', text, re.S)
if m:
return m.group(2).strip()
return _first_line(p)
lines = []
for line in text.splitlines():
s = line.strip()
if s.startswith("#!"):
continue
if not s.startswith("#"):
break
lines.append(s.lstrip("#").strip())
return "\n".join(lines).strip()
def name_problem(name: str, taken) -> str:
"""Why `name` can't be a new command, or "" when it can. `taken` is a
container of names the shell already answers to (builtins, aliases)."""
if not name:
return "give the command a name"
if not _NAME_RE.match(name):
return ("%r can't be a command name: use letters, digits, - and _ "
"(starting with a letter), at most 40" % name)
if name in taken:
return "%s is already a BenchCode command" % name
if keyword.iskeyword(name) or keyword.issoftkeyword(name):
return "%s is a Python keyword; the terminal reads it as Python" % name
if hasattr(builtins, name):
return "%s is a Python built-in name; the terminal reads it as Python" % name
return ""
_PY_TEMPLATE = '''"""{name} — {blurb}
Your own terminal command: type `{name}` in the terminal, with any
arguments, to run this file. The arguments are in sys.argv[1:].
Change it however you like; `cmd edit {name}` opens it again.
"""
import sys
def main(args):
who = " ".join(args) or "world"
print(f"Hello, {{who}}!")
if __name__ == "__main__":
main(sys.argv[1:])
'''
_SH_TEMPLATE = """# {name} — {blurb}
#
# Your own terminal command: these lines run in order, as if you typed
# them, when you type `{name}`. $1, $2 … are its arguments, $@ all of them.
# A line can be any terminal command, or a line of Python.
{body}
"""
def _uses_args(line: str) -> bool:
return bool(re.search(r"\$(?:[0-9@*#]|\{[0-9]+\})", line))
def new_command(name: str, line=None, shell=False, overwrite=False) -> Path:
"""Write the command file (Python by default, terminal lines with
`shell` or a `line`) and return its path."""
d = commands_dir()
d.mkdir(parents=True, exist_ok=True)
existing = find_command(name)
if existing is not None and not overwrite:
raise Refused("%s already exists (%s): `cmd edit %s` to change it, or "
"`cmd remove %s` first" % (name, _home_short(existing), name, name))
if line is not None or shell:
if line is not None:
body = line if _uses_args(line) else line + " $@"
blurb = "runs: " + line
else:
body = 'echo "Hello from {0}! Arguments: $@"'.format(name)
blurb = "my terminal command"
path = d / (name + ".sh")
text = _SH_TEMPLATE.format(name=name, blurb=blurb, body=body)
else:
path = d / (name + ".py")
text = _PY_TEMPLATE.format(name=name, blurb="my terminal command")
if existing is not None and existing != path:
existing.unlink()
path.write_text(text, encoding="utf-8")
return path
def remove_command(name: str) -> Path:
p = find_command(name)
if p is None:
raise Refused("no command of yours is called %s (`cmd list` shows them)" % name)
p.unlink()
return p
def expand_args(line: str, name: str, args) -> str:
"""Put a command's arguments into one line of a .sh command: $0 is the
name, $1 … $9 and ${10} the arguments, $@ / $* all of them, $# the count.
Unquoted, each argument is shell-quoted; inside double quotes it is
escaped for that context. '$' before anything else stays as typed."""
args = list(args)
# "$@" as a whole word: every argument as its own word.
line = re.sub(r'(?<![^\s])"\$@"(?![^\s])',
lambda _m: " ".join(shlex.quote(a) for a in args) if args else "", line)
def value(key):
if key == "0":
return name
if key in ("@", "*"):
return None
if key == "#":
return str(len(args))
i = int(key)
return args[i - 1] if 0 < i <= len(args) else ""
out, i, quote = [], 0, None
n = len(line)
while i < n:
c = line[i]
if c == "\\" and quote != "'" and i + 1 < n:
out.append(line[i:i + 2]); i += 2; continue
if quote is None and c in "'\"":
quote = c; out.append(c); i += 1; continue
if quote == c:
quote = None; out.append(c); i += 1; continue
if c == "$" and quote != "'":
m = re.match(r"\$(?:([0-9@*#])|\{([0-9]+)\})", line[i:])
if m:
key = m.group(1) or m.group(2)
v = value(key)
if quote == '"':
raw = " ".join(args) if v is None else v
out.append(raw.replace("\\", "\\\\").replace('"', '\\"'))
elif v is None:
out.append(" ".join(shlex.quote(a) for a in args))
else:
out.append(shlex.quote(v) if v != "" else "")
i += m.end(); continue
out.append(c); i += 1
return "".join(out)
def shell_lines(path, name, args):
"""The lines a .sh command runs, arguments put in, comments and blank
lines left out."""
text = Path(path).read_text(encoding="utf-8", errors="replace")
lines = []
for raw in text.splitlines():
s = raw.strip()
if not s or s.startswith("#"):
continue
lines.append(expand_args(raw, name, args))
return lines
# ═══ packages ════════════════════════════════════════════════════════
def _read_metadata(text: str):
msg = email.parser.Parser().parsestr(text or "")
return {
"name": (msg.get("Name") or "").strip(),
"version": (msg.get("Version") or "").strip(),
"summary": (msg.get("Summary") or "").strip(),
"requires": [r.strip() for r in (msg.get_all("Requires-Dist") or []) if r.strip()],
}
class Dist:
"""A distribution in the user site (one .dist-info folder)."""
def __init__(self, info: Path):
self.info = info
try:
meta = _read_metadata((info / "METADATA").read_text(encoding="utf-8", errors="replace"))
except OSError:
meta = _read_metadata("")
stem = info.name[:-len(".dist-info")]
guess_name, _, guess_ver = stem.partition("-")
self.name = meta["name"] or guess_name
self.version = meta["version"] or guess_ver or "0"
self.summary = meta["summary"]
self.requires = meta["requires"]
self.installer = self._read("INSTALLER").strip()
try:
self.added = json.loads(self._read("benchcode.json") or "{}")
except ValueError:
self.added = {}
def _read(self, fname) -> str:
try:
return (self.info / fname).read_text(encoding="utf-8", errors="replace")
except OSError:
return ""
@property
def key(self) -> str:
return _canon(self.name)
def files(self):
"""Paths relative to the user site, from RECORD (else top_level.txt)."""
rec = self._read("RECORD")
out = []
for line in rec.splitlines():
rel = line.split(",", 1)[0].strip()
if rel:
out.append(rel)
if not out:
for top in self._read("top_level.txt").split():
out.append(top)
return out
def top_level(self):
"""The import names it provides."""
tops = self._read("top_level.txt").split()
if tops:
return tops
seen = []
for rel in self.files():
first = rel.replace("\\", "/").split("/", 1)[0]
if first.endswith((".dist-info", ".data")) or first in ("..", "__pycache__"):
continue
mod = first[:-3] if first.endswith(".py") else first
if mod and mod not in seen:
seen.append(mod)
return seen
def scripts_of(dist) -> list:
"""[(command name, "module:function")] from a distribution's
console_scripts."""
try:
text = (dist.info / "entry_points.txt").read_text(encoding="utf-8", errors="replace")
except OSError:
return []
out, section = [], ""
for line in text.splitlines():
s = line.strip()
if s.startswith("["):
section = s.strip("[]").strip()
elif section == "console_scripts" and "=" in s and not s.startswith("#"):
name, _, value = s.partition("=")
out.append((name.strip(), value.strip()))
return out
def package_commands() -> list:
"""[(command name, Dist, "module:function")] for every command the
user's packages bring, sorted by name."""
out = []
for d in user_dists():
for name, value in scripts_of(d):
out.append((name, d, value))
return sorted(out, key=lambda t: t[0])
def user_dists():
site = user_site()
try:
infos = sorted(p for p in site.iterdir() if p.name.endswith(".dist-info") and p.is_dir())
except OSError:
return []
return [Dist(p) for p in infos]
def find_dist(name: str):
"""A user-site distribution by its name or one of its import names."""
key = _canon(name)
dists = user_dists()
for d in dists:
if d.key == key:
return d
for d in dists:
if name in d.top_level():
return d
return None
def loose_entries():
"""Things in the user site that belong to no distribution (put there by
hand): [(import name, path)]."""
site = user_site()
owned = set()
for d in user_dists():
for rel in d.files():
owned.add(rel.replace("\\", "/").split("/", 1)[0])
owned.update(d.top_level())
out = []
try:
entries = sorted(site.iterdir())
except OSError:
return []
for p in entries:
n = p.name
if n.startswith(".") or n == "__pycache__" or n.endswith((".dist-info", ".egg-info", ".pth")):
continue
mod = n[:-3] if n.endswith(".py") else n
if n in owned or mod in owned:
continue
if n.endswith(".py") or (p.is_dir() and mod.isidentifier()
and any(p.glob("*.py")) or (p / "__init__.py").is_file()):
out.append((mod, p))
return out
def _other_paths():
"""sys.path without the user site and the current folder: where an
import resolves when the user hasn't replaced it."""
site = os.path.realpath(str(user_site()))
cwd = os.path.realpath(os.getcwd()) if os.path.isdir(".") else ""
out = []
for p in sys.path:
if not p:
continue
rp = os.path.realpath(p)
if rp in (site, cwd) or "/Documents/site-packages" in rp:
continue
out.append(p)
return out
def builtin_owner(mod: str) -> str:
"""'' if `mod` isn't importable without the user site; otherwise a short
description of what it is. Those come first on sys.path (PYTHONPATH puts
~/Documents/site-packages last), so a user copy of one is never used."""
if mod in getattr(sys, "stdlib_module_names", ()) or mod in sys.builtin_module_names:
return "part of Python's standard library"
try:
spec = importlib.machinery.PathFinder.find_spec(mod, _other_paths())
except (ImportError, ValueError):
spec = None
if spec is None:
return ""
if spec.origin in (None, "namespace") and spec.loader is None:
return "" # a namespace folder: packages merge, nothing is hidden
return "built into BenchCode"
# ── links ────────────────────────────────────────────────────────────
CODE_HOSTS = ("github.com", "gitlab.com", "codeberg.org", "bitbucket.org")
FILE_HOSTS = CODE_HOSTS + ("raw.githubusercontent.com",)
FILE_SUFFIXES = (".whl", ".zip", ".py") + SOURCE_ARCHIVES
def is_link(s: str) -> bool:
s = (s or "").strip()
return bool(re.match(r"^(git\+)?(https?://|git@)", s, re.I)
or re.match(r"^(www\.)?(%s)/" % "|".join(re.escape(h) for h in CODE_HOSTS), s, re.I))
def parse_link(link: str) -> dict:
"""What a link names: {"kind": "repo"|"file", "url": what to fetch,
"filename", "label" (shown and kept as where it came from), "subdir",
"name" (the repository's name)}. Raises Refused for other links."""
from urllib.parse import urlsplit, unquote
raw = link.strip()
s = raw[4:] if raw.lower().startswith("git+") else raw
subdir = ""
if "#" in s:
s, frag = s.split("#", 1)
m = re.search(r"subdirectory=([^&]+)", frag)
subdir = unquote(m.group(1)) if m else ""
m = re.match(r"^git@([^:]+):(.+)$", s)
if m:
s = "https://%s/%s" % (m.group(1), m.group(2))
if not re.match(r"^https?://", s, re.I):
s = "https://" + s
u = urlsplit(s)
host = (u.hostname or "").lower()
if host.startswith("www."):
host = host[4:]
if u.scheme.lower() not in ("https", "http"):
raise Refused("pkg add takes https links")
if host not in FILE_HOSTS:
raise Refused("pkg add takes links to GitHub, GitLab, Codeberg or Bitbucket (a repository, "
"or a .whl / .tar.gz / .zip / .py file in one); %s isn't one of them. "
"Save the file in Files and pkg add it from there." % (host or raw))
parts = [unquote(x) for x in u.path.split("/") if x]
url = "https://%s%s" % (host, u.path) + ("?" + u.query if u.query else "")
if u.path.lower().endswith(FILE_SUFFIXES) and "/archive/" not in u.path:
# A file: a release asset, or a file shown on the site (blob → raw).
if host == "github.com" and len(parts) > 4 and parts[2] == "blob":
url = "https://raw.githubusercontent.com/%s/%s/%s" % (parts[0], parts[1], "/".join(parts[3:]))
elif host in ("gitlab.com", "codeberg.org") and "blob" in parts:
url = url.replace("/blob/", "/raw/", 1)
elif host == "bitbucket.org" and len(parts) > 3 and parts[2] == "src":
url = url.replace("/src/", "/raw/", 1)
return {"kind": "file", "url": url, "filename": parts[-1], "subdir": "",
"label": "%s/%s" % (host, "/".join(parts)), "name": parts[-1]}
if host == "raw.githubusercontent.com":
raise Refused("that raw link isn't a package file (.whl, .tar.gz, .zip or .py)")
if host == "gitlab.com" and "-" in parts: # gitlab.com/group/sub/repo/-/tree/ref
i = parts.index("-")
repo_parts, rest = parts[:i], parts[i + 1:]
else:
repo_parts, rest = parts[:2], parts[2:]
if len(repo_parts) < 2:
raise Refused("%s isn't a repository link: give https://%s/<owner>/<repository>" % (raw, host))
owner, repo = "/".join(repo_parts[:-1]), repo_parts[-1]
ref = ""
if "@" in repo: # pip's git+https://…/repo@ref
repo, ref = repo.split("@", 1)
if repo.endswith(".git"):
repo = repo[:-4]
if rest[:1] in (["tree"], ["src"]) and len(rest) >= 2:
ref = ref or rest[1]
subdir = subdir or "/".join(rest[2:])
elif rest and rest[0] not in ("tree", "src"):
raise Refused("%s points inside a repository; give the repository's link, or a "
".whl / .tar.gz / .zip / .py file in it" % raw)
if ".." in subdir.split("/"):
raise Refused("that folder isn't inside the repository")
if host == "github.com":
url = "https://api.github.com/repos/%s/%s/zipball%s" % (owner, repo, "/" + ref if ref else "")
elif host == "gitlab.com":
from urllib.parse import quote
url = ("https://gitlab.com/api/v4/projects/%s/repository/archive.zip%s"
% (quote(owner + "/" + repo, safe=""), "?sha=" + ref if ref else ""))
elif host == "bitbucket.org":
url = "https://bitbucket.org/%s/%s/get/%s.zip" % (owner, repo, ref or "HEAD")
else:
url = "https://%s/%s/%s/archive/%s.zip" % (host, owner, repo, ref or "HEAD")
label = "%s/%s/%s" % (host, owner, repo) + ("@" + ref if ref else "") + \
("#subdirectory=" + subdir if subdir else "")
return {"kind": "repo", "url": url, "filename": "%s.zip" % repo, "subdir": subdir,
"label": label, "name": repo}
def fetch(url: str, dest: Path) -> int:
"""Download `url` to `dest`; returns its size. Raises Refused with
the reason in words."""
import urllib.request
import urllib.error
req = urllib.request.Request(url, headers={"User-Agent": "BenchCode-pkg/1.0",
"Accept": "*/*"})
total = 0
try:
with urllib.request.urlopen(req, timeout=60) as resp, open(dest, "wb") as out:
while True:
chunk = resp.read(1 << 16)
if not chunk:
break
total += len(chunk)
if total > MAX_UNPACKED:
raise Refused("that download is over 512 MB; not a pure-Python package")
out.write(chunk)
except urllib.error.HTTPError as e:
if e.code == 404:
raise Refused("nothing there (404): check the link, and that the repository is public")
if e.code in (403, 429):
raise Refused("the site refused for now (%d, often a rate limit); try again later" % e.code)
raise Refused("the site answered %d %s" % (e.code, e.reason))
except urllib.error.URLError as e:
raise Refused("couldn't reach it (%s); check the connection" % getattr(e, "reason", e))
except OSError as e:
raise Refused("couldn't fetch it: %s" % e)
return total
def add_link(link: str, replace=False, say=None):
"""Fetch what `link` names and add it (as add() does). `say` gets a
progress line. Returns add()'s dict, with "fetched" (bytes) and "link"."""
info = parse_link(link)
tmp = Path(tempfile.mkdtemp(prefix="benchcode-fetch-"))
try:
if say:
say("Fetching %s …" % info["label"])
dest = tmp / info["filename"]
size = fetch(info["url"], dest)
if info["kind"] == "repo":
try:
zipfile.ZipFile(dest).close()
except zipfile.BadZipFile:
raise Refused("%s didn't send a repository archive" % info["label"])
r = add(str(dest), replace=replace, origin_note=info["label"],
subdir=info["subdir"] or None, name_hint=info["name"] if info["kind"] == "repo" else None)
r["fetched"] = size
r["link"] = info["label"]
return r
finally:
shutil.rmtree(tmp, ignore_errors=True)
def link_of(dist) -> str:
"""The link a package was added from, or ''."""
src = (dist.added or {}).get("from", "")
return src if re.match(r"^(%s)/" % "|".join(re.escape(h) for h in FILE_HOSTS), src) else ""
# ── staging ──────────────────────────────────────────────────────────
def _safe_unzip(zpath, dest: Path):
total = 0
with zipfile.ZipFile(zpath) as z:
for info in z.infolist():
name = info.filename.replace("\\", "/")
if name.startswith("/") or ".." in name.split("/"):
raise Refused("%s holds a file outside its own folder (%s); not adding it"
% (os.path.basename(str(zpath)), info.filename))
mode = (info.external_attr >> 16) & 0o170000
if mode == 0o120000: # a symlink: skip it
continue
total += info.file_size
if total > MAX_UNPACKED:
raise Refused("%s unpacks to more than 512 MB; that's not a pure-Python package"
% os.path.basename(str(zpath)))
target = dest / name
if info.is_dir():
target.mkdir(parents=True, exist_ok=True)
continue
target.parent.mkdir(parents=True, exist_ok=True)
with z.open(info) as src, open(target, "wb") as out:
shutil.copyfileobj(src, out)
def _safe_untar(tpath, dest: Path):
total = 0
with tarfile.open(tpath) as t:
members = []
for m in t.getmembers():
if not (m.isfile() or m.isdir()):
continue
total += m.size
if total > MAX_UNPACKED:
raise Refused("%s unpacks to more than 512 MB; that's not a pure-Python package"
% os.path.basename(str(tpath)))
members.append(m)
try:
t.extractall(dest, members=members, filter="data")
except tarfile.FilterError as e:
raise Refused("%s holds a file outside its own folder (%s); not adding it"
% (os.path.basename(str(tpath)), e))
def _single_root(d: Path) -> Path:
"""An archive's one top folder, if everything is inside it."""
kids = [k for k in d.iterdir() if k.name not in ("__MACOSX",) and not k.name.startswith("._")]
if len(kids) == 1 and kids[0].is_dir():
return kids[0]
return d
def _sub(root: Path, subdir) -> Path:
"""`subdir` of an unpacked archive (a folder in a repository)."""
if not subdir:
return root
p = root / subdir.strip("/")
if not p.is_dir():
raise Refused("the repository has no folder %s" % subdir)
return p
def _find_version(text: str) -> str:
m = re.search(r"""^__version__\s*=\s*['"]([^'"]+)['"]""", text, re.M)
return m.group(1) if m else ""
def _project_metadata(root: Path):
"""name / version / summary / requires / packages / modules / src
from PKG-INFO, pyproject.toml, setup.cfg or setup.py."""
meta = {"name": "", "version": "", "summary": "", "requires": [],
"packages": None, "modules": None, "src": None,
"entry_points": {}, "native_build": False}
pkg_info = root / "PKG-INFO"
if pkg_info.is_file():
m = _read_metadata(pkg_info.read_text(encoding="utf-8", errors="replace"))
meta.update({k: m[k] for k in ("name", "version", "summary", "requires")})
pyproject = root / "pyproject.toml"
if pyproject.is_file():
try:
import tomllib
data = tomllib.loads(pyproject.read_text(encoding="utf-8", errors="replace"))
except Exception:
data = {}
proj = data.get("project") or {}
eps = {}
for key, group in (("scripts", "console_scripts"), ("gui-scripts", "gui_scripts")):
if isinstance(proj.get(key), dict):
eps[group] = ["%s = %s" % (k, v) for k, v in proj[key].items()]
if isinstance(proj.get("entry-points"), dict):
for group, table in proj["entry-points"].items():
if isinstance(table, dict):
eps.setdefault(group, []).extend("%s = %s" % (k, v) for k, v in table.items())
meta["entry_points"] = eps
backend = str((data.get("build-system") or {}).get("build-backend") or "")
if backend.startswith(("mesonpy", "scikit_build", "maturin", "pybind11", "enscons")):
meta["native_build"] = True
if ((data.get("tool") or {}).get("setuptools") or {}).get("ext-modules"):
meta["native_build"] = True
meta["name"] = meta["name"] or str(proj.get("name") or "")
if isinstance(proj.get("version"), str):
meta["version"] = meta["version"] or proj["version"]
if isinstance(proj.get("description"), str):
meta["summary"] = meta["summary"] or proj["description"]
if not meta["requires"] and isinstance(proj.get("dependencies"), list):
meta["requires"] = [str(r) for r in proj["dependencies"]]
st = ((data.get("tool") or {}).get("setuptools") or {})
if isinstance(st.get("py-modules"), list):
meta["modules"] = [str(x) for x in st["py-modules"]]
if isinstance(st.get("packages"), list):
meta["packages"] = [str(x).split(".", 1)[0] for x in st["packages"]]
pdir = st.get("package-dir")
if isinstance(pdir, dict) and isinstance(pdir.get(""), str):
meta["src"] = pdir[""]
flit = ((data.get("tool") or {}).get("flit") or {}).get("module") or {}
if isinstance(flit.get("name"), str):
meta["packages"] = meta["packages"] or [flit["name"]]
hatch = (((data.get("tool") or {}).get("hatch") or {}).get("build") or {})
hw = ((hatch.get("targets") or {}).get("wheel") or {})
if isinstance(hw.get("packages"), list):
pk = [str(x) for x in hw["packages"]]
if pk and all("/" in x for x in pk):
meta["src"] = meta["src"] or pk[0].rsplit("/", 1)[0]
meta["packages"] = meta["packages"] or [x.rsplit("/", 1)[-1] for x in pk]
setup_cfg = root / "setup.cfg"
if setup_cfg.is_file():
import configparser
cp = configparser.ConfigParser(interpolation=None)
try:
cp.read_string(setup_cfg.read_text(encoding="utf-8", errors="replace"))
meta["name"] = meta["name"] or cp.get("metadata", "name", fallback="")
v = cp.get("metadata", "version", fallback="")
if v and not v.startswith(("attr:", "file:")):
meta["version"] = meta["version"] or v
if not meta["requires"]:
meta["requires"] = [r.strip() for r in
cp.get("options", "install_requires", fallback="").splitlines()
if r.strip()]
pd = cp.get("options", "package_dir", fallback="")
m = re.search(r"=\s*([\w./-]+)", pd)
if m:
meta["src"] = meta["src"] or m.group(1)
mods = cp.get("options", "py_modules", fallback="").split()
if mods:
meta["modules"] = meta["modules"] or mods
if cp.has_section("options.entry_points") and not meta["entry_points"]:
for group, val in cp.items("options.entry_points"):
lines = [l.strip() for l in val.splitlines() if "=" in l]
if lines:
meta["entry_points"][group] = lines
except Exception:
pass
setup_py = root / "setup.py"
if setup_py.is_file():
text = setup_py.read_text(encoding="utf-8", errors="replace")
if re.search(r"\bext_modules\b|\bExtension\(|cythonize\(", text):
meta["native_build"] = True
if not meta["entry_points"]:
m = re.search(r"""['"]console_scripts['"]\s*:\s*\[([^\]]*)\]""", text)
if m:
found = re.findall(r"""['"]([^'"]+=[^'"]+)['"]""", m.group(1))
if found:
meta["entry_points"]["console_scripts"] = [f.strip() for f in found]
if setup_py.is_file() and not meta["name"]:
m = re.search(r"""\bname\s*=\s*['"]([^'"]+)['"]""", text)
if m:
meta["name"] = m.group(1)
m = re.search(r"""\bversion\s*=\s*['"]([^'"]+)['"]""", text)
if m:
meta["version"] = meta["version"] or m.group(1)
m = re.search(r"""py_modules\s*=\s*\[([^\]]*)\]""", text)
if m:
meta["modules"] = meta["modules"] or re.findall(r"""['"]([\w.]+)['"]""", m.group(1))
return meta
def _project_entries(root: Path, meta):
"""The folders and .py files of a project that make up its importable
code: [Path]."""
candidates = []
if meta.get("src"):
candidates.append(root / meta["src"])
candidates += [root / "src", root]
src = next((c for c in candidates if c.is_dir() and any(
(k.is_dir() and (k / "__init__.py").is_file()) or k.suffix == ".py" for k in c.iterdir())), root)
entries = []
wanted = meta.get("packages")
for k in sorted(src.iterdir()):
if k.name.startswith(".") or k.name in NOT_PACKAGES or k.name.endswith((".egg-info", ".dist-info")):
continue
if k.is_dir() and (k / "__init__.py").is_file():
if wanted is None or k.name in wanted:
entries.append(k)
if wanted:
for w in wanted:
p = src / w
if p.is_dir() and p not in entries:
entries.append(p) # a namespace package, named outright
proj = _dist_stem(meta.get("name") or "").lower()
mods = meta.get("modules")
for k in sorted(src.iterdir()):
if k.suffix != ".py" or not k.is_file():
continue
stem = k.stem
if mods is not None:
if stem in mods:
entries.append(k)
continue
if stem in NOT_MODULES or stem.startswith("test_") or stem.endswith("_test"):
continue
if not entries or stem.lower() == proj:
entries.append(k)
if not entries and proj:
p = src / proj
if p.is_dir():
entries.append(p)
return entries
def _copy_entry(src: Path, dest_dir: Path):
ignore = shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo", ".git", ".DS_Store")
if src.is_dir():
shutil.copytree(src, dest_dir / src.name, ignore=ignore, symlinks=False)
else:
shutil.copy2(src, dest_dir / src.name)
class Staged:
"""A package unpacked into a temporary folder, ready to copy."""
def __init__(self, origin: str):
self.origin = origin # what the user gave (a file name)
self.tmp = Path(tempfile.mkdtemp(prefix="benchcode-pkg-"))
self.root = self.tmp / "site"
self.root.mkdir()
self.name = ""
self.version = ""
self.summary = ""
self.requires = []
self.wheel_info = None # the wheel's own .dist-info, if any
self.c_sources = []
self.native_build = False # the project compiles extensions
self.entry_points = {} # group -> ["name = module:func"]
self.dropped = [] # wheel .data parts we leave out
def close(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def entries(self):
return sorted(p for p in self.root.iterdir()
if p.name != "__pycache__" and not p.name.endswith(".dist-info"))
def import_names(self):
return [p.stem if p.suffix == ".py" else p.name for p in self.entries()]
def _stage_wheel(path: Path, st: Staged):
_safe_unzip(path, st.root)
infos = [p for p in st.root.iterdir() if p.name.endswith(".dist-info") and p.is_dir()]
if len(infos) != 1:
raise Refused("%s isn't a wheel: it has no single .dist-info folder" % path.name)
info = infos[0]
st.wheel_info = info
wheel = (info / "WHEEL").read_text(encoding="utf-8", errors="replace") if (info / "WHEEL").is_file() else ""
tags = re.findall(r"^Tag:\s*(\S+)", wheel, re.M)
native = [t for t in tags if not t.endswith("-none-any")]
if native and len(native) == len(tags):
raise Refused("%s is built for %s, with compiled (native) code. BenchCode adds "
"pure-Python packages only (a wheel ending in -none-any): iOS runs only "
"native code that ships inside the app." % (path.name, native[0].split("-")[-1]))
meta = _read_metadata((info / "METADATA").read_text(encoding="utf-8", errors="replace")
if (info / "METADATA").is_file() else "")
st.name, st.version, st.summary, st.requires = meta["name"], meta["version"], meta["summary"], meta["requires"]
for data in [p for p in st.root.iterdir() if p.name.endswith(".data") and p.is_dir()]:
for part in data.iterdir():
if part.name in ("purelib", "platlib"):
for item in part.iterdir():
target = st.root / item.name
if target.exists():
if item.is_dir() and target.is_dir():
shutil.copytree(item, target, dirs_exist_ok=True)
continue
shutil.move(str(item), str(target))
else:
st.dropped.append(part.name)
shutil.rmtree(data)
def _stage_project(root: Path, st: Staged, fallback_name: str):
meta = _project_metadata(root)
entries = _project_entries(root, meta)
if not entries:
raise Refused("found no Python package in %s: no folder with an __init__.py and "
"no .py module beside its setup files" % st.origin)
for e in entries:
_copy_entry(e, st.root)
name = meta["name"] or fallback_name
m = re.match(r"^(.*?)-(\d[\w.+-]*)$", name)
if m and not meta["version"]:
name, meta["version"] = m.group(1), m.group(2)
st.name = name
st.version = meta["version"] or _version_of(st) or "0"
st.summary = meta["summary"]
st.requires = meta["requires"]
st.entry_points = meta["entry_points"]
st.native_build = meta["native_build"]
def _version_of(st: Staged) -> str:
for e in st.entries():
f = e / "__init__.py" if e.is_dir() else e
if f.is_file():
v = _find_version(f.read_text(encoding="utf-8", errors="replace"))
if v:
return v
return ""
def stage(path_str: str, subdir=None, name_hint=None) -> Staged:
"""Unpack what the user gave into a Staged folder (or raise Refused).
`subdir`: use that folder of an archive; `name_hint`: the name to fall
back on when the project names none (a repository's)."""
path = Path(os.path.expanduser(path_str))
if not path.is_absolute():
path = Path(os.getcwd()) / path
if not path.exists():
bare = path_str.strip()
looks_like_file = "/" in bare or bare.lower().endswith((".whl", ".zip", ".py") + SOURCE_ARCHIVES)
if not looks_like_file and re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]*(\[.*\])?([<>=!~]=?.*)?$", bare):
pname = re.split(r"[\[<>=!~]", bare, 1)[0]
if _is_available(pname):
raise Refused("%s is already here (built in): just import it; "
"`pip show %s` tells its version" % (pname, pname))
raise Refused("no file or folder called %s here. pkg adds a package from a file you "
"have or a repository link; it doesn't look packages up by name. "
"pkg add <its .whl or .tar.gz>, or pkg add https://github.com/<owner>/<repo>"
% bare)
raise Refused("no such file or folder: %s" % path_str)
st = Staged(path.name)
try: