-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathknowledge_acquisition.py
More file actions
executable file
·1769 lines (1621 loc) · 77.4 KB
/
Copy pathknowledge_acquisition.py
File metadata and controls
executable file
·1769 lines (1621 loc) · 77.4 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
from utils.util import *
from utils.kb_report import generate as kb_report_generate, append_status as kb_append_status
from extraction.getCall import get_all_used_api
from extraction.lib_module_and_package_extraction import *
from extraction.library_api_and_module import *
from call_graph.get_FDG import *
import platform, argparse, os, json, time, requests, logging, tempfile, uuid, fcntl
from packaging.specifiers import SpecifierSet, InvalidSpecifier
from packaging.version import parse as parse_version
from packaging.utils import parse_wheel_filename
from packaging.tags import cpython_tags, compatible_tags
import tarfile
import zipfile
import shutil
import sys
from multiprocessing import Pool, cpu_count
if (platform.system() == 'Windows'):
slash = "\\"
else:
slash = r"/"
library_path_prefix = ""
constraint_path_prefix = ""
version_path_prefix = ""
api_path_prefix = ""
_stats = {"downloaded": 0, "failed": 0, "skipped": 0, "crashed": 0}
def setup_path(library_path_prefix_pass, constraint_path_prefix_pass, version_path_prefix_pass, api_path_prefix_pass):
global library_path_prefix, constraint_path_prefix, version_path_prefix, api_path_prefix
library_path_prefix = library_path_prefix_pass
constraint_path_prefix = constraint_path_prefix_pass
version_path_prefix = version_path_prefix_pass
api_path_prefix = api_path_prefix_pass
setup_path_1(library_path_prefix, constraint_path_prefix, version_path_prefix, api_path_prefix)
def load_config(config_path):
with open(f"./configure/{config_path}", 'r') as file:
config = json.load(file)
return config
def get_proj_dependency_from_requirements(file_path):
requirements_dict = {}
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
if line and not line.startswith('#') and '@' not in line:
package, version = line.split('==')
requirements_dict[package.lower()] = version
return requirements_dict
def get_available_version(FDG, sub_graph, python_version, target_proj_dependency, target_library, target_version):
target_library_constraint = get_library_constraint_from_metadata(target_library, target_version, python_version)
available_versions1 = {}
available_versions2 = {}
available_versions = {}
target_library_dependency = FDG[target_library]
available_versions[target_library] = []
available_versions[target_library].append(target_version)
with open(f"{version_path_prefix}library_version.json", 'r') as file:
version_ls = json.load(file)
for proj_dependency in sub_graph:
flag = False
if proj_dependency not in target_proj_dependency:
continue
condidate_version = []
if proj_dependency not in target_library_dependency:
try:
condidate_version = version_ls[proj_dependency.lower()][python_version]
except:
logging.warning("Package %s not found in version list for py%s",
proj_dependency.lower(), python_version)
if len(condidate_version) >= 150:
condidate_version = condidate_version[-150:]
elif len(condidate_version) >= 30:
condidate_version = condidate_version[-30:]
target_ver = target_proj_dependency[proj_dependency]
target_ver_norm = str(parse_version(target_ver))
match_idx = None
for idx, v in enumerate(condidate_version):
if str(parse_version(v)) == target_ver_norm:
match_idx = idx
break
if match_idx is not None:
condidate_version.pop(match_idx)
condidate_version.append(target_ver)
flag = True
else:
condidate_version.append(target_ver)
flag = True
else:
try:
for version in version_ls[proj_dependency][python_version]:
try:
if is_version_compat(version, target_library_constraint[proj_dependency]):
condidate_version.append(version)
except:
condidate_version = version_ls[proj_dependency][python_version]
break
except:
logging.warning("Package %s not found in version list (constrained path)",
proj_dependency)
target_ver = target_proj_dependency[proj_dependency]
target_ver_norm = str(parse_version(target_ver))
match_idx = None
for idx, v in enumerate(condidate_version):
if str(parse_version(v)) == target_ver_norm:
match_idx = idx
break
if match_idx is not None:
condidate_version.pop(match_idx)
condidate_version.append(target_ver)
flag = True
if flag:
available_versions1[proj_dependency] = condidate_version
else:
available_versions2[proj_dependency] = condidate_version
sorted_available_versions1 = dict(sorted(available_versions1.items(), key=lambda item: len(item[1])))
sorted_available_versions2 = dict(sorted(available_versions2.items(), key=lambda item: len(item[1])))
for i in sorted_available_versions1:
available_versions[i] = sorted_available_versions1[i]
for i in sorted_available_versions2:
if i not in available_versions:
available_versions[i] = sorted_available_versions2[i]
return available_versions
def filter_versions(version_list):
"""Remove versions that fail parse_version (e.g. date-like strings)."""
result = []
for v in version_list:
try:
parse_version(v)
result.append(v)
except Exception:
pass
return result
# Point 29: packaging.tags-based wheel compatibility (runtime platform)
def _is_runtime_compat_wheel(filename, compat_tags):
"""Return True if *filename* wheel is compatible with the current platform."""
if not filename.endswith(".whl"):
return False
try:
_, _, _, tags = parse_wheel_filename(filename)
except Exception:
return False
return any(t in compat_tags for t in tags)
def _py_version_is_compatible(python_version, requires_python):
"""Check if any version in the python_version range satisfies requires_python."""
if not requires_python:
return True
rp_spec = SpecifierSet(requires_python)
if python_version.count('.') == 1:
major, minor = python_version.split('.')
candidates = [f"{major}.{minor}.1", f"{major}.{minor}.99"]
return any(rp_spec.contains(c) for c in candidates)
else:
return rp_spec.contains(python_version)
def get_compatible_versions(package_name, python_version):
url = f"https://pypi.org/pypi/{package_name}/json"
try:
response = requests.get(url).json()
except (requests.RequestException, json.JSONDecodeError, ValueError):
return []
compatible_versions = []
new_python_version = python_version.replace(".", "")
if "releases" not in response:
return []
# Pre-compute runtime platform compatibility tags (Point 29)
_ver_major, _ver_minor = (int(python_version.split('.')[0]),
int(python_version.split('.')[1]))
_compat_tags = set(cpython_tags((_ver_major, _ver_minor)))
# Point 32: supplement with pure-python any-platform tags from pip
_interp = f'cp{_ver_major}{_ver_minor}'
for t in compatible_tags(python_version=(_ver_major, _ver_minor),
interpreter=_interp):
if '-none-any' in str(t):
_compat_tags.add(t)
for version, files in response["releases"].items():
# Point 29: skip versions with no runtime-compatible artifact
if not any(f.get("packagetype") == "sdist"
or _is_runtime_compat_wheel(f.get("filename", ""),
_compat_tags)
for f in files if f):
continue
for file_info in files:
if file_info.get("python_version"):
try:
if file_info["python_version"] == f"cp{new_python_version}":
rp = file_info.get("requires_python")
if rp is None or _py_version_is_compatible(python_version, rp):
compatible_versions.append(version)
break
elif file_info["python_version"] != None and f"py{python_version.split('.')[0]}" in file_info["python_version"]:
requires_python = file_info.get("requires_python")
if requires_python is not None and ("=" in requires_python or ">" in requires_python or "<" in requires_python):
if _py_version_is_compatible(python_version, requires_python):
compatible_versions.append(version)
break
else:
compatible_versions.append(version)
break
elif file_info.get("requires_python") == None:
compatible_versions.append(version)
break
elif _py_version_is_compatible(python_version, file_info["requires_python"]):
compatible_versions.append(version)
break
except (KeyError, TypeError, InvalidSpecifier):
pass
compatible_versions = filter_versions(compatible_versions)
compatible_versions.sort(key=parse_version)
if package_name == "torchvision" and "0.11.0" in compatible_versions:
compatible_versions.remove("0.11.0")
return compatible_versions
# ---------------------------------------------------------------------------
# Download infrastructure
# ---------------------------------------------------------------------------
def _wheel_priority(filename, python_version):
"""Return pip-native priority (position in compat tag list, 0 = best).
Returns -1 for incompatible wheels, 999 for sdist.
Uses packaging.tags.cpython_tags for pip's native ordering (Point 29).
"""
if not filename.endswith(".whl"):
return -1 # sdist handled separately by caller
major, minor = int(python_version.split('.')[0]), int(python_version.split('.')[1])
compat = list(cpython_tags((major, minor)))
compat_set = set(compat)
# Point 32: supplement with pure-python any-platform tags from pip
_interp = f'cp{major}{minor}'
for t in compatible_tags(python_version=(major, minor), interpreter=_interp):
if '-none-any' in str(t) and t not in compat_set:
compat.append(t)
compat_set.add(t)
try:
_, _, _, tags = parse_wheel_filename(filename)
except Exception:
return -1
best = 99999
for t in tags:
if t in compat_set:
pos = compat.index(t)
if pos < best:
best = pos
return best if best < 99999 else -1
def _select_download_urls(package_name, version, python_version):
"""Return priority-sorted download URLs from version constraint JSON.
Priority (platform-independent):
1: py3-none-any 5: cp{ver}-*-{platform}
2: cp{ver}-*-any 6: other py3/cp3 + {platform}
3: other py3/cp3 + any 7: sdist
4: py3-none-{platform}
Python 2-only wheels are skipped.
"""
norm_name = norm_pkg(package_name)
_resolved = resolve_pkg_dir(package_name, constraint_path_prefix)
nv = norm_ver(version)
json_path = None
for name in (norm_name, _resolved):
_candidate = f"{constraint_path_prefix}{name}/{name}{nv}/{name}.json"
if os.path.exists(_candidate):
json_path = _candidate
break
if json_path is None:
return []
try:
with open(json_path) as f:
data = json.load(f)
except json.JSONDecodeError:
try:
os.remove(json_path)
except FileNotFoundError:
pass
return []
except OSError:
return []
urls = data.get("urls", [])
if not urls:
return []
scored = []
for u in urls:
pkg_type = u.get("packagetype")
filename = u.get("filename", "")
url = u.get("url", "")
if not url:
continue
if filename.endswith((".exe", ".msi", ".dmg", ".rpm", ".deb")):
continue
if pkg_type == "bdist_wheel":
priority = _wheel_priority(filename, python_version)
if priority < 0:
continue
elif pkg_type == "sdist":
priority = 999
else:
continue
scored.append((priority, url))
scored.sort(key=lambda x: (x[0], x[1]))
return [url for _, url in scored]
def _build_fallback_candidates(package_name, version, python_version):
"""Return [(url, is_wheel), ...] from PyPI JSON API, sorted by priority.
Same platform-independent priority as _select_download_urls.
"""
candidates = []
pypi_url = f"https://pypi.org/pypi/{package_name}/{version}/json"
try:
r = requests.get(pypi_url, timeout=7200)
if r.status_code != 200:
return candidates
data = r.json()
for u in data.get("urls", []):
fname = u.get("filename", "")
url = u.get("url", "")
if not url or fname.endswith((".exe", ".msi", ".dmg", ".rpm", ".deb")):
continue
pkg_type = u.get("packagetype", "")
if pkg_type == "bdist_wheel":
priority = _wheel_priority(fname, python_version)
if priority < 0:
continue
candidates.append((priority, url, True))
elif pkg_type == "sdist":
candidates.append((999, url, False))
candidates.sort(key=lambda x: (x[0], x[1]))
except requests.RequestException:
pass
return [(url, is_wheel) for _, url, is_wheel in candidates]
def _safe_target(base_dir, member_name):
"""Return safe absolute target path, or None if traversal detected.
Guarantees the resolved path stays within *base_dir*, blocking:
- ``../`` and ``..\\`` parent traversal
- absolute paths (``/etc/passwd``)
"""
name = member_name.replace("\\", "/")
if os.path.isabs(name):
return None
target = os.path.abspath(os.path.join(base_dir, name))
base = os.path.abspath(base_dir)
if os.path.commonpath([base, target]) != base:
return None
return target
def _should_extract(name):
"""Return True if *name* is Python source or packaging metadata.
Keeps:
- ``.py``, ``.pyi``, ``.pyw``, ``.pxi`` source files
- ``.dist-info/``, ``.egg-info/`` metadata directories (whole tree)
- ``.data/purelib/`` and ``.data/platlib/``: ``.py`` source only
- ``setup.py``, ``setup.cfg``, ``pyproject.toml`` (build configs)
Skips:
- ``.so``, ``.dll``, ``.pyc`` binaries
- ``.data/scripts/``, ``.data/headers/``, ``.data/data/`` (non-source)
"""
# .dist-info and .egg-info: keep entire tree
if ".dist-info/" in name or name.endswith(".dist-info/"):
return True
if ".egg-info/" in name or name.endswith(".egg-info/"):
return True
# .data/purelib and .data/platlib: keep .py source only
if ".data/purelib/" in name or ".data/platlib/" in name:
return name.endswith((".py", ".pyi", ".pyw", ".pxi"))
# .data/ other (scripts, headers, data): skip entirely
if ".data/" in name:
return False
# Top-level source files
if name.endswith((".py", ".pyi", ".pyw", ".pxi")):
return True
if os.path.basename(name) in ("setup.py", "setup.cfg", "pyproject.toml"):
return True
return False
def _extract_archive(archive_path, target_dir):
"""Extract archive to *target_dir*, flattening single-top-level-dir wrappers.
Per-member safety validation (Point 6):
- rejects ``../`` and absolute-path traversal
- rejects symlink, hardlink, device and fifo tar members
Selective extraction (Point 14):
- only writes ``.py/.pyi/.pyw/.pxi`` + metadata + build configs
- skips ``.so``, ``.dll``, ``.pyc`` and other non-source files
"""
extract_tmp = tempfile.mkdtemp(dir=os.path.dirname(target_dir),
prefix=".extract-")
# Try tarfile first (auto-detects compression from magic bytes:
# .tar.gz, .tar.bz2, .tar.xz, .tar, .tgz, .tbz2, .txz)
try:
with tarfile.open(archive_path) as tf:
# --- Point 6: per-member safety validation ---------------
extract_ok = []
for member in tf.getmembers():
if member.issym() or member.islnk():
continue # skip symlinks/hardlinks (rare, not .py source)
if member.isdev():
raise ValueError(
f"Unsafe tar member (device): {member.name}")
if member.isfifo():
raise ValueError(
f"Unsafe tar member (fifo): {member.name}")
target = _safe_target(extract_tmp, member.name)
if target is None:
raise ValueError(
f"Path traversal in tar: {member.name}")
extract_ok.append(member)
# --- Point 6+14: selective per-member extract ------------
for member in extract_ok:
if not _should_extract(member.name):
continue
tf.extract(member, extract_tmp)
except (tarfile.ReadError, tarfile.CompressionError):
# Fall back to zipfile (handles .whl, .zip)
with zipfile.ZipFile(archive_path) as zf:
# --- Point 6: per-entry safety validation ----------------
extract_ok = []
for info in zf.infolist():
if _safe_target(extract_tmp, info.filename) is None:
raise ValueError(
f"Path traversal in zip: {info.filename}")
extract_ok.append(info)
# --- Point 6+14: selective per-entry extract -------------
for info in extract_ok:
if not _should_extract(info.filename):
continue
zf.extract(info, extract_tmp)
for root, dirs, files in os.walk(extract_tmp):
for d in dirs:
try:
os.chmod(os.path.join(root, d), 0o755)
except OSError:
pass
for f in files:
try:
os.chmod(os.path.join(root, f), 0o644)
except OSError:
pass
items = os.listdir(extract_tmp)
os.makedirs(target_dir, exist_ok=True)
if len(items) == 1 and os.path.isdir(os.path.join(extract_tmp, items[0])):
src_dir = os.path.join(extract_tmp, items[0])
for item in os.listdir(src_dir):
try:
shutil.move(os.path.join(src_dir, item),
os.path.join(target_dir, item))
except OSError:
pass
else:
for item in items:
try:
shutil.move(os.path.join(extract_tmp, item),
os.path.join(target_dir, item))
except OSError:
pass
shutil.rmtree(extract_tmp, ignore_errors=True)
# ---------------------------------------------------------------------------
# Post-processing
# ---------------------------------------------------------------------------
def _promote_purelib(target_dir):
"""Lift .data/purelib/ and .data/platlib/ contents to target_dir root."""
for d in os.listdir(target_dir):
if not d.endswith(".data"):
continue
data_dir = os.path.join(target_dir, d)
for sub in ("purelib", "platlib"):
sub_path = os.path.join(data_dir, sub)
if os.path.isdir(sub_path):
for item in os.listdir(sub_path):
src = os.path.join(sub_path, item)
dst = os.path.join(target_dir, item)
if not os.path.exists(dst):
shutil.move(src, dst)
shutil.rmtree(data_dir)
break
def _read_top_level(extract_dir):
"""Read top_level.txt from .dist-info/ in extract_dir. Returns list or None."""
for d in os.listdir(extract_dir):
if d.endswith(".dist-info"):
tl = os.path.join(extract_dir, d, "top_level.txt")
if not os.path.isfile(tl):
continue
try:
with open(tl) as f:
entries = [l.strip() for l in f if l.strip()]
except OSError:
continue
return entries if entries else None
return None
def _install_source(target_dir, extract_dir, call_module, is_wheel=True):
"""Move Python packages from extract_dir to target_dir.
*is_wheel* controls how aggressive the fallback strategy is:
- wheel: allow recursive os.walk and whitelist relaxation
- sdist: strict — refuse recursive walk and whitelist relaxation
to avoid pulling in tests/docs/examples
Returns True if at least one .py file ends up in target_dir.
"""
os.makedirs(target_dir, exist_ok=True)
whitelist = _read_top_level(extract_dir)
src_dir = os.path.join(extract_dir, "src")
has_src_layout = os.path.isdir(src_dir)
lib_dir = os.path.join(extract_dir, "lib")
has_lib_layout = os.path.isdir(lib_dir)
def _should_move(item):
if item.startswith("."):
return False
if whitelist:
mod = item[:-3] if item.endswith(".py") else item
# Normalize hyphen/underscore (PyPI name vs import name)
mod_norm = mod.lower().replace("-", "_")
wl_norm = {w.lower().replace("-", "_") for w in whitelist}
return mod_norm in wl_norm
return True
def _move_items(source_dir, allow_recursive_fallback=True):
any_moved = False
for item in sorted(os.listdir(source_dir)):
if not _should_move(item):
continue
src = os.path.join(source_dir, item)
dst = os.path.join(target_dir, item)
if os.path.exists(dst):
try:
if os.path.isdir(dst):
shutil.rmtree(dst)
else:
os.remove(dst)
except OSError:
pass
if os.path.exists(dst):
continue
if os.path.isdir(src) and os.path.isfile(os.path.join(src, "__init__.py")):
try:
shutil.move(src, dst)
any_moved = True
except OSError:
pass
elif os.path.isdir(src) and whitelist and item in whitelist:
# PEP 420 namespace package: no __init__.py but in whitelist
os.makedirs(dst, exist_ok=True)
for sub_item in os.listdir(src):
s_src = os.path.join(src, sub_item)
s_dst = os.path.join(dst, sub_item)
try:
shutil.move(s_src, s_dst)
except OSError:
pass
any_moved = True
elif os.path.isdir(src) and not allow_recursive_fallback:
# P39: detect nested packages in sdist non-standard layouts
# (wheel uses recursive fallback below instead).
# Mode A: nested __init__.py (e.g. python/curl/__init__.py)
# Mode B: single-file modules (e.g. regex_3/regex.py, no __init__.py)
_skip_dirs = {'test', 'tests', 'docs', 'examples'}
try:
_contents = os.listdir(src)
except OSError:
_contents = []
# Separate subdirectories from files
_sub_dirs = sorted(
[c for c in _contents if os.path.isdir(os.path.join(src, c))],
reverse=True)
_files = [c for c in _contents
if os.path.isfile(os.path.join(src, c))]
_nested_found = False
# Mode A: nested __init__.py in subdirectories
for _sub in _sub_dirs:
if _sub.lower() in _skip_dirs:
continue
_sub_path = os.path.join(src, _sub)
if os.path.isfile(os.path.join(_sub_path, "__init__.py")):
_dst_sub = os.path.join(target_dir, _sub)
if not os.path.exists(_dst_sub):
try:
shutil.move(_sub_path, _dst_sub)
_nested_found = True
any_moved = True
except OSError:
pass
# Mode B: single-file module (no __init__.py, .py files directly
# in this directory, e.g. regex_3/regex.py)
if not _nested_found and not os.path.isfile(
os.path.join(src, "__init__.py")):
_has_module_py = any(
f.endswith('.py') and not f.startswith('_')
for f in _files)
if _has_module_py:
_dst_sub = os.path.join(target_dir, call_module)
os.makedirs(_dst_sub, exist_ok=True)
for _f in _files:
if _f.endswith(('.py', '.so', '.pyd')):
_s_src = os.path.join(src, _f)
_s_dst = os.path.join(_dst_sub, _f)
if not os.path.exists(_s_dst):
try:
shutil.move(_s_src, _s_dst)
any_moved = True
except OSError:
pass
_nested_found = True
elif os.path.isfile(src) and item.endswith(".py") and item != "setup.py":
try:
shutil.move(src, dst)
any_moved = True
except OSError:
pass
# Fallback: recursively find .py files in non-package subdirs.
# Allowed for wheel (structured), refused for sdist (tests/docs mixed in).
if not any_moved and allow_recursive_fallback:
for root, dirs, files in os.walk(source_dir):
for f in files:
if f.endswith(".py") and f != "setup.py":
src_f = os.path.join(root, f)
dst_f = os.path.join(target_dir, os.path.relpath(src_f, source_dir))
os.makedirs(os.path.dirname(dst_f), exist_ok=True)
try:
shutil.copy2(src_f, dst_f)
any_moved = True
except OSError:
pass
return any_moved
moved = False
if has_lib_layout:
moved = _move_items(lib_dir, allow_recursive_fallback=is_wheel) or moved
if has_src_layout:
moved = _move_items(src_dir, allow_recursive_fallback=is_wheel) or moved
if not moved:
moved = _move_items(extract_dir, allow_recursive_fallback=is_wheel)
# top_level.txt whitelist may fail when import name differs from
# directory name (e.g. "cv2" vs "opencv_python"). Fall back.
# Only wheel can relax the whitelist — sdist would pull in tests/docs.
if whitelist and not moved and is_wheel:
whitelist_orig = whitelist
whitelist = None
if has_lib_layout:
moved = _move_items(lib_dir, allow_recursive_fallback=True) or moved
if has_src_layout:
moved = _move_items(src_dir, allow_recursive_fallback=True) or moved
if not moved:
moved = _move_items(extract_dir, allow_recursive_fallback=True)
whitelist = whitelist_orig
# Move .dist-info, .egg-info, .data metadata directories
for item in sorted(os.listdir(extract_dir)):
if item.startswith("."):
continue
src = os.path.join(extract_dir, item)
dst = os.path.join(target_dir, item)
if os.path.exists(dst):
continue
if os.path.isdir(src) and item.endswith((".dist-info", ".egg-info", ".data")):
try:
shutil.move(src, dst)
except (shutil.Error, OSError):
pass
# Move loose metadata files left after _extract_archive flattened
# a single .dist-info directory (e.g. metadata-only wheels)
_METADATA_FILES = ('METADATA', 'PKG-INFO', 'top_level.txt',
'RECORD', 'WHEEL', 'INSTALLER', 'entry_points.txt')
_loose_metadata = [item for item in sorted(os.listdir(extract_dir))
if item in _METADATA_FILES]
if _loose_metadata:
# _extract_archive flattened a single .dist-info directory.
# Re-wrap files into a .dist-info so get_library_constraint_from_metadata
# can find Requires-Dist constraints.
_dist_dir = os.path.join(target_dir, f"{call_module}.dist-info")
os.makedirs(_dist_dir, exist_ok=True)
for item in _loose_metadata:
src = os.path.join(extract_dir, item)
dst = os.path.join(_dist_dir, item)
if not os.path.exists(dst):
try:
shutil.move(src, dst)
except (shutil.Error, OSError):
pass
return any(f.endswith('.py') for _, _, files in os.walk(target_dir) for f in files) \
or _has_metadata(target_dir)
def _keep_dist_info(target_dir, package_name, version):
"""Verify .dist-info/ is preserved for METADATA access."""
dist_dir = os.path.join(target_dir, f"{norm_pkg(package_name)}-{version}.dist-info")
return os.path.isdir(dist_dir)
# ---------------------------------------------------------------------------
# Call module detection
# ---------------------------------------------------------------------------
# Known library → module name mappings where the PyPI name differs from
# the import name and cannot be detected via top_level.txt. Used to
# decide whether the call_module source is trusted for .complete marker.
_CALL_MODULE_MAP = {
'scikit-learn': 'sklearn',
'pillow': 'PIL',
'grpcio': 'grpc',
'absl-py': 'absl',
'pytorch-lightning': 'pytorch_lightning',
'opencv-python': 'cv2',
'scikit-image': 'skimage',
'tensorboardx': 'tensorboardX',
'python-dateutil': 'dateutil',
'python-dotenv': 'dotenv',
'pysocks': 'socks',
'python-gflags': 'gflags',
'websocket-client': 'websocket',
'nvidia-ml-py3': 'pynvml',
'greenlet': 'greenlet',
}
def _py_file_count(entry, target_dir):
"""Count .py files under *entry* if it is a directory; 0 otherwise."""
epath = os.path.join(target_dir, entry)
if os.path.isdir(epath):
return sum(1 for _, _, fs in os.walk(epath)
for f in fs if f.endswith(".py"))
return 0
def _select_best_module_name(entries, target_dir, package_name):
"""Pick best module name from *entries*: prefer pkg name match, then most .py files."""
if not entries:
return None
if len(entries) == 1:
return entries[0]
norm_pkg = package_name.replace("-", "_")
matching = [e for e in entries if e.replace("-", "_") == norm_pkg]
if matching:
return matching[0]
return max(entries, key=lambda e: _py_file_count(e, target_dir))
def _read_top_level_txt(target_dir, package_name):
"""Read top_level.txt from .dist-info/ or .egg-info/ to get module name.
Multi-.dist-info priority: prefer the directory whose name matches
*package_name*, then fall back to the first candidate. This mirrors
the P71 fix in :func:`detect_call_modules`.
"""
if not os.path.isdir(target_dir):
return None
# Phase A: collect all candidates from .dist-info first, then .egg-info
for suffix in (".dist-info", ".egg-info"):
all_candidates = [] # (dir_name, entries)
for d in sorted(os.listdir(target_dir)):
if d.endswith(suffix):
tl_path = os.path.join(target_dir, d, "top_level.txt")
if not os.path.isfile(tl_path):
continue
try:
with open(tl_path) as f:
entries = [l.strip() for l in f if l.strip()]
except OSError:
continue
if entries:
all_candidates.append((d, entries))
if not all_candidates:
continue
# Phase B: prefer candidate whose directory name matches package_name
if package_name:
norm_pkg = package_name.replace("-", "_")
for d, entries in all_candidates:
d_name = d[:-(len(suffix) + 1)].rsplit("-", 1)[0]
if d_name.replace("-", "_") == norm_pkg:
return _select_best_module_name(entries, target_dir,
package_name)
# Phase C: fallback — first candidate (backward-compatible)
return _select_best_module_name(
all_candidates[0][1], target_dir, package_name)
return None
def _detect_call_module(target_dir, fallback):
"""Auto-detect module from extracted source: __init__.py dir, then matching .py file."""
if not os.path.isdir(target_dir):
return fallback
_ignore = {"tests", "test", "docs", "examples", "example",
"benchmarks", "benchmark", "ez_setup", "scripts", "tools"}
# Prefer directory whose name matches the expected package
_fallback_norm = fallback.replace('-', '_')
for d in sorted(os.listdir(target_dir)):
if d.startswith(".") or d.endswith((".dist-info", ".egg-info", ".data")):
continue
full = os.path.join(target_dir, d)
if os.path.isdir(full) and os.path.isfile(os.path.join(full, "__init__.py")):
if d.replace('-', '_') == _fallback_norm:
return d
# Any other __init__.py directory (excluding known non-module dirs)
for d in sorted(os.listdir(target_dir)):
if d.startswith(".") or d.endswith((".dist-info", ".egg-info", ".data")):
continue
if d.lower() in _ignore:
continue
full = os.path.join(target_dir, d)
if os.path.isdir(full) and os.path.isfile(os.path.join(full, "__init__.py")):
return d
for d in sorted(os.listdir(target_dir)):
if d.startswith("."):
continue
full = os.path.join(target_dir, d)
if os.path.isfile(full) and d.endswith(".py") and d != "setup.py":
name = d[:-3]
if name.replace('-', '_') == fallback.replace('-', '_'):
return name
# Namespace package: dir without __init__.py but containing subdirs with __init__.py
# (e.g., google/ has google/protobuf/__init__.py but no google/__init__.py)
for d in sorted(os.listdir(target_dir)):
if d.startswith(".") or d.endswith((".dist-info", ".egg-info", ".data")):
continue
if d.lower() in _ignore:
continue
full = os.path.join(target_dir, d)
if os.path.isdir(full):
for sub in os.listdir(full):
if os.path.isfile(os.path.join(full, sub, "__init__.py")):
return d
return fallback
# ---------------------------------------------------------------------------
# Download
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Multiprocessing worker logging
# ---------------------------------------------------------------------------
_worker_knowledge_path = None
def _set_worker_knowledge_path(path):
global _worker_knowledge_path
_worker_knowledge_path = path
def _init_worker():
"""Configure logging for Pool worker processes."""
import faulthandler, signal
faulthandler.enable()
# Dump stacks on SIGUSR1 for manual inspection
signal.signal(signal.SIGUSR1,
lambda *_: faulthandler.dump_traceback())
if _worker_knowledge_path:
log_file = os.path.join(_worker_knowledge_path, "knowledge_acquisition.log")
h = logging.FileHandler(log_file, mode='a')
h.setLevel(logging.INFO)
h.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logging.getLogger().addHandler(h)
logging.getLogger().setLevel(logging.INFO)
def _mark_no_source(target_dir, reason=""):
"""Write ``.no_source`` marker **inside** *target_dir* with optional *reason*.
Creates the directory if it does not exist (Point 8).
"""
os.makedirs(target_dir, exist_ok=True)
marker = os.path.join(target_dir, ".no_source")
with open(marker, "w") as f:
if reason:
f.write(reason + "\n")
def _has_metadata(directory):
"""Return True if *directory* contains .dist-info or .egg-info metadata.
Handles two cases:
- Normal: ``.dist-info/`` or ``.egg-info/`` directory exists
- Flattened: _extract_archive flattened a single .dist-info directory,
leaving METADATA / top_level.txt loose in *directory*
"""
try:
entries = os.listdir(directory)
except OSError:
return False
# Case 1: metadata directory present
if any(d.endswith(('.dist-info', '.egg-info'))
for d in entries
if os.path.isdir(os.path.join(directory, d))):
return True
# Case 2: flattened metadata (METADATA / PKG-INFO files after
# _extract_archive flattened a single .dist-info directory)
if any(f in ('METADATA', 'PKG-INFO') for f in entries):
return True
return False
def _check_source(td, cm):
"""Check if a Python module is already extracted in *td* under *cm* or its variants.
Marker protocol (Point 13):
- ``.complete`` exists → trust completed build, return True
- ``.building`` exists without ``.complete`` → incomplete, return False
- no markers → fall back to legacy source scan
"""
if not os.path.isdir(td):
return False
# Point 13: .complete marker is authoritative for finished builds
if os.path.isfile(os.path.join(td, ".complete")):
return True
# Point 13: .building without .complete → interrupted build
if os.path.isfile(os.path.join(td, ".building")):
return False
# 1. Flat package: __init__.py directly in target_dir
if os.path.isfile(os.path.join(td, "__init__.py")):
return True
# 2. Try naming variants including namespace paths (zope.event → zope/event)
names = {cm, cm.replace('-', '_'), cm.replace('_', '-')}
for n in list(names):
names.add(n.replace('.', '/'))
for name in names:
p = os.path.join(td, name)
if os.path.isdir(p) or os.path.isfile(p + ".py"):
return True
# 3. Check top_level.txt for packages with different module names (e.g. cv2 ← opencv-contrib-python)
for d in os.listdir(td):
if d.endswith(".dist-info"):
tl = os.path.join(td, d, "top_level.txt")
if os.path.isfile(tl):
try:
with open(tl) as f:
for entry in f:
entry = entry.strip()
if entry:
ep = os.path.join(td, entry)
if os.path.isdir(ep) or os.path.isfile(ep + ".py"):
return True
except OSError:
pass
break
return False
def download_pypi_source(package_name, version=None, python_version="3.7", output_dir="."):
norm_name = norm_pkg(package_name)
norm_ver_name = norm_ver(version)
target_dir = f"{library_path_prefix}{norm_name}/{norm_name}{norm_ver_name}"
call_module = get_library_call_module(package_name)
if _check_source(target_dir, call_module):
_stats["skipped"] += 1
return
# backward compat: check old KB underscore path
_resolved_lib = resolve_pkg_dir(package_name, library_path_prefix)
if _resolved_lib != norm_name:
_old_dir = f"{library_path_prefix}{_resolved_lib}/{_resolved_lib}{norm_ver_name}"
if _check_source(_old_dir, call_module):
_stats["skipped"] += 1
return
if os.path.exists(os.path.join(target_dir, ".no_source")) or (
_resolved_lib != norm_name and
os.path.exists(os.path.join(f"{library_path_prefix}{_resolved_lib}/"
f"{_resolved_lib}{norm_ver_name}",
".no_source"))):