/
setup_info.py
1947 lines (1759 loc) · 69.2 KB
/
setup_info.py
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
# -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function
import ast
import atexit
import contextlib
import importlib
import io
import operator
import os
import shutil
import sys
from functools import partial
import attr
import chardet
import packaging.specifiers
import packaging.utils
import packaging.version
import pep517.envbuild
import pep517.wrappers
import six
from appdirs import user_cache_dir
from distlib.wheel import Wheel
from packaging.markers import Marker
from pip_shims.utils import call_function_with_correct_args
from six.moves import configparser
from six.moves.urllib.parse import unquote, urlparse, urlunparse
from vistir.compat import FileNotFoundError, Iterable, Mapping, Path, finalize, lru_cache
from vistir.contextmanagers import cd, temp_path
from vistir.misc import run
from vistir.path import create_tracked_tempdir, ensure_mkdir_p, mkdir_p, rmtree
from ..environment import MYPY_RUNNING
from ..exceptions import RequirementError
from .utils import (
get_default_pyproject_backend,
get_name_variants,
get_pyproject,
init_requirement,
read_source,
split_vcs_method_from_uri,
strip_extras_markers_from_requirement,
)
try:
import pkg_resources.extern.packaging.requirements as pkg_resources_requirements
except ImportError:
pkg_resources_requirements = None
try:
from setuptools.dist import distutils, Distribution
except ImportError:
import distutils
from distutils.core import Distribution
try:
from contextlib import ExitStack
except ImportError:
from contextlib2 import ExitStack
try:
from os import scandir
except ImportError:
from scandir import scandir
if MYPY_RUNNING:
from typing import (
Any,
Callable,
Dict,
List,
Generator,
Optional,
Union,
Tuple,
TypeVar,
Text,
Set,
AnyStr,
Sequence,
)
import requests
from pip_shims.shims import InstallRequirement, PackageFinder
from pkg_resources import (
PathMetadata,
DistInfoDistribution,
EggInfoDistribution,
Requirement as PkgResourcesRequirement,
)
from packaging.requirements import Requirement as PackagingRequirement
TRequirement = TypeVar("TRequirement")
RequirementType = TypeVar(
"RequirementType", covariant=True, bound=PackagingRequirement
)
MarkerType = TypeVar("MarkerType", covariant=True, bound=Marker)
STRING_TYPE = Union[str, bytes, Text]
S = TypeVar("S", bytes, str, Text)
AST_SEQ = TypeVar("AST_SEQ", ast.Tuple, ast.List)
CACHE_DIR = os.environ.get("PIPENV_CACHE_DIR", user_cache_dir("pipenv"))
# The following are necessary for people who like to use "if __name__" conditionals
# in their setup.py scripts
_setup_stop_after = None
_setup_distribution = None
def pep517_subprocess_runner(cmd, cwd=None, extra_environ=None):
# type: (List[AnyStr], Optional[AnyStr], Optional[Mapping[S, S]]) -> None
"""The default method of calling the wrapper subprocess."""
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
run(
cmd,
cwd=cwd,
env=env,
block=True,
combine_stderr=True,
return_object=False,
write_to_stdout=False,
nospin=True,
)
class BuildEnv(pep517.envbuild.BuildEnvironment):
def pip_install(self, reqs):
cmd = [
sys.executable,
"-m",
"pip",
"install",
"--ignore-installed",
"--prefix",
self.path,
] + list(reqs)
run(
cmd,
block=True,
combine_stderr=True,
return_object=False,
write_to_stdout=False,
nospin=True,
)
class HookCaller(pep517.wrappers.Pep517HookCaller):
def __init__(self, source_dir, build_backend, backend_path=None):
self.source_dir = os.path.abspath(source_dir)
self.build_backend = build_backend
self._subprocess_runner = pep517_subprocess_runner
if backend_path:
backend_path = [
pep517.wrappers.norm_and_check(self.source_dir, p) for p in backend_path
]
self.backend_path = backend_path
def parse_special_directives(setup_entry, package_dir=None):
# type: (S, Optional[STRING_TYPE]) -> S
rv = setup_entry
if not package_dir:
package_dir = os.getcwd()
if setup_entry.startswith("file:"):
_, path = setup_entry.split("file:")
path = path.strip()
if os.path.exists(path):
rv = read_source(path)
elif setup_entry.startswith("attr:"):
_, resource = setup_entry.split("attr:")
resource = resource.strip()
with temp_path():
sys.path.insert(0, package_dir)
if "." in resource:
resource, _, attribute = resource.rpartition(".")
package, _, path = resource.partition(".")
base_path = os.path.join(package_dir, package)
if path:
path = os.path.join(base_path, os.path.join(*path.split(".")))
else:
path = base_path
if not os.path.exists(path) and os.path.exists("{0}.py".format(path)):
path = "{0}.py".format(path)
elif os.path.isdir(path):
path = os.path.join(path, "__init__.py")
rv = ast_parse_attribute_from_file(path, attribute)
if rv:
return str(rv)
module = importlib.import_module(resource)
rv = getattr(module, attribute)
if not isinstance(rv, six.string_types):
rv = str(rv)
return rv
def make_base_requirements(reqs):
# type: (Sequence[STRING_TYPE]) -> Set[BaseRequirement]
requirements = set()
if not isinstance(reqs, (list, tuple, set)):
reqs = [reqs]
for req in reqs:
if isinstance(req, BaseRequirement):
requirements.add(req)
elif pkg_resources_requirements is not None and isinstance(
req, pkg_resources_requirements.Requirement
):
requirements.add(BaseRequirement.from_req(req))
elif req and isinstance(req, six.string_types) and not req.startswith("#"):
requirements.add(BaseRequirement.from_string(req))
return requirements
def setuptools_parse_setup_cfg(path):
from setuptools.config import read_configuration
parsed = read_configuration(path)
results = parsed.get("metadata", {})
results.update(parsed.get("options", {}))
results["install_requires"] = make_base_requirements(
results.get("install_requires", [])
)
extras = {}
for extras_section, extras_reqs in results.get("extras_require", {}).items():
new_reqs = tuple(make_base_requirements(extras_reqs))
if new_reqs:
extras[extras_section] = new_reqs
results["extras_require"] = extras
results["setup_requires"] = make_base_requirements(results.get("setup_requires", []))
return results
def get_package_dir_from_setupcfg(parser, base_dir=None):
# type: (configparser.ConfigParser, STRING_TYPE) -> Text
if base_dir is not None:
package_dir = base_dir
else:
package_dir = os.getcwd()
if parser.has_option("options.packages.find", "where"):
pkg_dir = parser.get("options.packages.find", "where")
if isinstance(pkg_dir, Mapping):
pkg_dir = pkg_dir.get("where")
package_dir = os.path.join(package_dir, pkg_dir)
elif parser.has_option("options", "packages"):
pkg_dir = parser.get("options", "packages")
if "find:" in pkg_dir:
_, pkg_dir = pkg_dir.split("find:")
pkg_dir = pkg_dir.strip()
package_dir = os.path.join(package_dir, pkg_dir)
elif os.path.exists(os.path.join(package_dir, "setup.py")):
setup_py = ast_parse_setup_py(os.path.join(package_dir, "setup.py"))
if "package_dir" in setup_py:
package_lookup = setup_py["package_dir"]
if not isinstance(package_lookup, Mapping):
package_dir = package_lookup
package_dir = package_lookup.get(
next(iter(list(package_lookup.keys()))), package_dir
)
if not os.path.isabs(package_dir):
if not base_dir:
package_dir = os.path.join(os.path.getcwd(), package_dir)
else:
package_dir = os.path.join(base_dir, package_dir)
return package_dir
def get_name_and_version_from_setupcfg(parser, package_dir):
# type: (configparser.ConfigParser, STRING_TYPE) -> Tuple[Optional[S], Optional[S]]
name, version = None, None
if parser.has_option("metadata", "name"):
name = parse_special_directives(parser.get("metadata", "name"), package_dir)
if parser.has_option("metadata", "version"):
version = parse_special_directives(parser.get("metadata", "version"), package_dir)
return name, version
def get_extras_from_setupcfg(parser):
# type: (configparser.ConfigParser) -> Dict[STRING_TYPE, Tuple[BaseRequirement, ...]]
extras = {} # type: Dict[STRING_TYPE, Tuple[BaseRequirement, ...]]
if "options.extras_require" not in parser.sections():
return extras
extras_require_section = parser.options("options.extras_require")
for section in extras_require_section:
if section in ["options", "metadata"]:
continue
section_contents = parser.get("options.extras_require", section)
section_list = section_contents.split("\n")
section_extras = tuple(make_base_requirements(section_list))
if section_extras:
extras[section] = section_extras
return extras
def parse_setup_cfg(
setup_cfg_contents, # type: S
base_dir, # type: S
):
# type: (...) -> Dict[S, Union[S, None, Set[BaseRequirement], List[S], Dict[STRING_TYPE, Tuple[BaseRequirement]]]]
default_opts = {
"metadata": {"name": "", "version": ""},
"options": {
"install_requires": "",
"python_requires": "",
"build_requires": "",
"setup_requires": "",
"extras": "",
"packages.find": {"where": "."},
},
}
parser = configparser.ConfigParser(default_opts)
if six.PY2:
buff = io.BytesIO(setup_cfg_contents)
parser.readfp(buff)
else:
parser.read_string(setup_cfg_contents)
results = {}
package_dir = get_package_dir_from_setupcfg(parser, base_dir=base_dir)
name, version = get_name_and_version_from_setupcfg(parser, package_dir)
results["name"] = name
results["version"] = version
install_requires = set() # type: Set[BaseRequirement]
if parser.has_option("options", "install_requires"):
install_requires = make_base_requirements(
parser.get("options", "install_requires").split("\n")
)
results["install_requires"] = install_requires
if parser.has_option("options", "python_requires"):
results["python_requires"] = parse_special_directives(
parser.get("options", "python_requires"), package_dir
)
if parser.has_option("options", "build_requires"):
results["build_requires"] = parser.get("options", "build_requires")
results["extras_require"] = get_extras_from_setupcfg(parser)
return results
@contextlib.contextmanager
def _suppress_distutils_logs():
# type: () -> Generator[None, None, None]
"""Hack to hide noise generated by `setup.py develop`.
There isn't a good way to suppress them now, so let's monky-patch.
See https://bugs.python.org/issue25392.
"""
f = distutils.log.Log._log
def _log(log, level, msg, args):
if level >= distutils.log.ERROR:
f(log, level, msg, args)
distutils.log.Log._log = _log
yield
distutils.log.Log._log = f
def build_pep517(source_dir, build_dir, config_settings=None, dist_type="wheel"):
if config_settings is None:
config_settings = {}
requires, backend = get_pyproject(source_dir)
hookcaller = HookCaller(source_dir, backend)
if dist_type == "sdist":
get_requires_fn = hookcaller.get_requires_for_build_sdist
build_fn = hookcaller.build_sdist
else:
get_requires_fn = hookcaller.get_requires_for_build_wheel
build_fn = hookcaller.build_wheel
with BuildEnv() as env:
env.pip_install(requires)
reqs = get_requires_fn(config_settings)
env.pip_install(reqs)
return build_fn(build_dir, config_settings)
@ensure_mkdir_p(mode=0o775)
def _get_src_dir(root):
# type: (AnyStr) -> AnyStr
src = os.environ.get("PIP_SRC")
if src:
return src
virtual_env = os.environ.get("VIRTUAL_ENV")
if virtual_env is not None:
return os.path.join(virtual_env, "src")
if root is not None:
# Intentionally don't match pip's behavior here -- this is a temporary copy
src_dir = create_tracked_tempdir(prefix="requirementslib-", suffix="-src")
else:
src_dir = os.path.join(root, "src")
return src_dir
@lru_cache()
def ensure_reqs(reqs):
# type: (List[Union[S, PkgResourcesRequirement]]) -> List[PkgResourcesRequirement]
import pkg_resources
if not isinstance(reqs, Iterable):
raise TypeError("Expecting an Iterable, got %r" % reqs)
new_reqs = []
for req in reqs:
if not req:
continue
if isinstance(req, six.string_types):
req = pkg_resources.Requirement.parse("{0}".format(str(req)))
# req = strip_extras_markers_from_requirement(req)
new_reqs.append(req)
return new_reqs
def _prepare_wheel_building_kwargs(
ireq=None, # type: Optional[InstallRequirement]
src_root=None, # type: Optional[STRING_TYPE]
src_dir=None, # type: Optional[STRING_TYPE]
editable=False, # type: bool
):
# type: (...) -> Dict[STRING_TYPE, STRING_TYPE]
download_dir = os.path.join(CACHE_DIR, "pkgs") # type: STRING_TYPE
mkdir_p(download_dir)
wheel_download_dir = os.path.join(CACHE_DIR, "wheels") # type: STRING_TYPE
mkdir_p(wheel_download_dir)
if src_dir is None:
if editable and src_root is not None:
src_dir = src_root
elif src_root is not None:
src_dir = _get_src_dir(root=src_root) # type: STRING_TYPE
else:
src_dir = create_tracked_tempdir(prefix="reqlib-src")
# Let's always resolve in isolation
if src_dir is None:
src_dir = create_tracked_tempdir(prefix="reqlib-src")
build_dir = create_tracked_tempdir(prefix="reqlib-build")
return {
"build_dir": build_dir,
"src_dir": src_dir,
"download_dir": download_dir,
"wheel_download_dir": wheel_download_dir,
}
class ScandirCloser(object):
def __init__(self, path):
self.iterator = scandir(path)
def __next__(self):
return next(iter(self.iterator))
def __iter__(self):
return self
def next(self):
return self.__next__()
def close(self):
if getattr(self.iterator, "close", None):
self.iterator.close()
else:
pass
def iter_metadata(path, pkg_name=None, metadata_type="egg-info"):
# type: (AnyStr, Optional[AnyStr], AnyStr) -> Generator
if pkg_name is not None:
pkg_variants = get_name_variants(pkg_name)
dirs_to_search = [path]
while dirs_to_search:
p = dirs_to_search.pop(0)
with contextlib.closing(ScandirCloser(p)) as path_iterator:
for entry in path_iterator:
if entry.is_dir():
entry_name, ext = os.path.splitext(entry.name)
if ext.endswith(metadata_type):
if pkg_name is None or entry_name.lower() in pkg_variants:
yield entry
elif not entry.name.endswith(metadata_type):
dirs_to_search.append(entry.path)
def find_egginfo(target, pkg_name=None):
# type: (AnyStr, Optional[AnyStr]) -> Generator
egg_dirs = (
egg_dir
for egg_dir in iter_metadata(target, pkg_name=pkg_name)
if egg_dir is not None
)
if pkg_name:
yield next(iter(eggdir for eggdir in egg_dirs if eggdir is not None), None)
else:
for egg_dir in egg_dirs:
yield egg_dir
def find_distinfo(target, pkg_name=None):
# type: (AnyStr, Optional[AnyStr]) -> Generator
dist_dirs = (
dist_dir
for dist_dir in iter_metadata(
target, pkg_name=pkg_name, metadata_type="dist-info"
)
if dist_dir is not None
)
if pkg_name:
yield next(iter(dist for dist in dist_dirs if dist is not None), None)
else:
for dist_dir in dist_dirs:
yield dist_dir
def get_distinfo_dist(path, pkg_name=None):
# type: (S, Optional[S]) -> Optional[DistInfoDistribution]
import pkg_resources
dist_dir = next(iter(find_distinfo(path, pkg_name=pkg_name)), None)
if dist_dir is not None:
metadata_dir = dist_dir.path
base_dir = os.path.dirname(metadata_dir)
dist = next(iter(pkg_resources.find_distributions(base_dir)), None)
if dist is not None:
return dist
return None
def get_egginfo_dist(path, pkg_name=None):
# type: (S, Optional[S]) -> Optional[EggInfoDistribution]
import pkg_resources
egg_dir = next(iter(find_egginfo(path, pkg_name=pkg_name)), None)
if egg_dir is not None:
metadata_dir = egg_dir.path
base_dir = os.path.dirname(metadata_dir)
path_metadata = pkg_resources.PathMetadata(base_dir, metadata_dir)
dist_iter = pkg_resources.distributions_from_metadata(path_metadata.egg_info)
dist = next(iter(dist_iter), None)
if dist is not None:
return dist
return None
def get_metadata(path, pkg_name=None, metadata_type=None):
# type: (S, Optional[S], Optional[S]) -> Dict[S, Union[S, List[RequirementType], Dict[S, RequirementType]]]
wheel_allowed = metadata_type == "wheel" or metadata_type is None
egg_allowed = metadata_type == "egg" or metadata_type is None
dist = None # type: Optional[Union[DistInfoDistribution, EggInfoDistribution]]
if wheel_allowed:
dist = get_distinfo_dist(path, pkg_name=pkg_name)
if egg_allowed and dist is None:
dist = get_egginfo_dist(path, pkg_name=pkg_name)
if dist is not None:
return get_metadata_from_dist(dist)
return {}
@lru_cache()
def get_extra_name_from_marker(marker):
# type: (MarkerType) -> Optional[S]
if not marker:
raise ValueError("Invalid value for marker: {0!r}".format(marker))
if not getattr(marker, "_markers", None):
raise TypeError("Expecting a marker instance, received {0!r}".format(marker))
for elem in marker._markers:
if isinstance(elem, tuple) and elem[0].value == "extra":
return elem[2].value
return None
def get_metadata_from_wheel(wheel_path):
# type: (S) -> Dict[Any, Any]
if not isinstance(wheel_path, six.string_types):
raise TypeError("Expected string instance, received {0!r}".format(wheel_path))
try:
dist = Wheel(wheel_path)
except Exception:
pass
metadata = dist.metadata
name = metadata.name
version = metadata.version
requires = []
extras_keys = getattr(metadata, "extras", []) # type: List[STRING_TYPE]
extras = {
k: [] for k in extras_keys
} # type: Dict[STRING_TYPE, List[RequirementType]]
for req in getattr(metadata, "run_requires", []):
parsed_req = init_requirement(req)
parsed_marker = parsed_req.marker
if parsed_marker:
extra = get_extra_name_from_marker(parsed_marker)
if extra is None:
requires.append(parsed_req)
continue
if extra not in extras:
extras[extra] = []
parsed_req = strip_extras_markers_from_requirement(parsed_req)
extras[extra].append(parsed_req)
else:
requires.append(parsed_req)
return {"name": name, "version": version, "requires": requires, "extras": extras}
def get_metadata_from_dist(dist):
# type: (Union[PathMetadata, EggInfoDistribution, DistInfoDistribution]) -> Dict[S, Union[S, List[RequirementType], Dict[S, RequirementType]]]
try:
requires = dist.requires()
except Exception:
requires = []
try:
dep_map = dist._build_dep_map()
except Exception:
dep_map = {}
deps = [] # type: List[PkgResourcesRequirement]
extras = {}
for k in dep_map.keys():
if k is None:
deps.extend(dep_map.get(k))
continue
else:
extra = None
_deps = dep_map.get(k)
if k.startswith(":python_version"):
marker = k.replace(":", "; ")
else:
if ":python_version" in k:
extra, _, marker = k.partition(":")
marker = "; {0}".format(marker)
else:
marker = ""
extra = "{0}".format(k)
_deps = ensure_reqs(
tuple(["{0}{1}".format(str(req), marker) for req in _deps])
)
if extra:
extras[extra] = _deps
else:
deps.extend(_deps)
requires.extend(deps)
return {
"name": dist.project_name,
"version": dist.version,
"requires": requires,
"extras": extras,
}
AST_BINOP_MAP = dict(
(
(ast.Add, operator.add),
(ast.Sub, operator.sub),
(ast.Mult, operator.mul),
(ast.Div, operator.floordiv),
(ast.Mod, operator.mod),
(ast.Pow, operator.pow),
(ast.LShift, operator.lshift),
(ast.RShift, operator.rshift),
(ast.BitAnd, operator.and_),
(ast.BitOr, operator.or_),
(ast.BitXor, operator.xor),
)
)
AST_COMPARATORS = dict(
(
(ast.Lt, operator.lt),
(ast.LtE, operator.le),
(ast.Eq, operator.eq),
(ast.Gt, operator.gt),
(ast.GtE, operator.ge),
(ast.NotEq, operator.ne),
(ast.Is, operator.is_),
(ast.IsNot, operator.is_not),
(ast.And, operator.and_),
(ast.Or, operator.or_),
(ast.Not, operator.not_),
(ast.In, lambda a, b: operator.contains(b, a)),
)
)
if getattr(ast, "AnnAssign", None):
ASSIGN_NODES = (ast.Assign, ast.AnnAssign)
else:
ASSIGN_NODES = (ast.Assign,)
class Analyzer(ast.NodeVisitor):
def __init__(self):
self.name_types = []
self.function_map = {} # type: Dict[Any, Any]
self.function_names = {}
self.resolved_function_names = {}
self.functions = []
self.strings = []
self.assignments = {}
self.binOps = []
self.binOps_map = {}
self.recurse = True
super(Analyzer, self).__init__()
def generic_visit(self, node):
if isinstance(node, ast.Call):
self.functions.append(node)
self.function_map.update(ast_unparse(node, initial_mapping=True))
if isinstance(node, ast.Name):
self.name_types.append(node)
if isinstance(node, ast.Str):
self.strings.append(node)
if isinstance(node, ASSIGN_NODES):
self.assignments.update(ast_unparse(node, initial_mapping=True))
super(Analyzer, self).generic_visit(node)
@contextlib.contextmanager
def no_recurse(self):
original_recurse_val = self.recurse
try:
self.recurse = False
yield
finally:
self.recurse = original_recurse_val
def visit_BinOp(self, node):
node = ast_unparse(node, initial_mapping=True)
self.binOps.append(node)
def unmap_binops(self):
for binop in self.binOps:
self.binOps_map[binop] = ast_unparse(binop, analyzer=self)
def match_assignment_str(self, match):
matches = [k for k in self.assignments if getattr(k, "id", "") == match]
if matches:
return matches[-1]
return None
def match_assignment_name(self, match):
matches = [k for k in self.assignments if getattr(k, "id", "") == match.id]
if matches:
return matches[-1]
return None
def generic_unparse(self, item):
if any(isinstance(item, k) for k in AST_BINOP_MAP.keys()):
return AST_BINOP_MAP[type(item)]
elif any(isinstance(item, k) for k in AST_COMPARATORS.keys()):
return AST_COMPARATORS[type(item)]
return item
def unparse(self, item):
unparser = getattr(
self, "unparse_{0}".format(item.__class__.__name__), self.generic_unparse
)
return unparser(item)
def unparse_Dict(self, item):
# unparsed = dict(zip(unparse(item.keys), unparse(item.values)))
return dict(
(self.unparse(k), self.unparse(v)) for k, v in zip(item.keys, item.values)
)
def unparse_List(self, item):
return [self.unparse(el) for el in item.elts]
def unparse_Tuple(self, item):
return tuple([self.unparse(el) for el in item.elts])
def unparse_Str(self, item):
return item.s
def unparse_Subscript(self, item):
unparsed = self.unparse(item.value)
if isinstance(item.slice, ast.Index):
try:
unparsed = unparsed[self.unparse(item.slice.value)]
except (KeyError, TypeError):
# not everything can be looked up before runtime
unparsed = item
return unparsed
def unparse_Num(self, item):
return item.n
def unparse_BinOp(self, item):
if item in self.binOps_map:
unparsed = self.binOps_map[item]
else:
right_item = self.unparse(item.right)
left_item = self.unparse(item.left)
op = getattr(item, "op", None)
op_func = self.unparse(op) if op is not None else op
try:
unparsed = op_func(left_item, right_item)
except Exception:
unparsed = (left_item, op_func, right_item)
return unparsed
def unparse_Name(self, item):
unparsed = item.id
if not self.recurse:
return unparsed
if item in self.assignments and self.recurse:
items = self.unparse(self.assignments[item])
unparsed = items.get(item.id, item.id)
else:
assignment = self.match_assignment_name(item)
if assignment is not None:
items = self.unparse(self.assignments[assignment])
unparsed = items.get(item.id, item.id)
return unparsed
def unparse_NameConstant(self, item):
return item.value
def unparse_Constant(self, item):
return item.value
def unparse_Ellipsis(self, item):
return item.value
def unparse_Attribute(self, item):
attr_name = getattr(item, "value", None)
attr_attr = getattr(item, "attr", None)
name = None
name = self.unparse(attr_name) if attr_name is not None else attr_attr
if attr_name and not self.recurse:
name = attr_name
elif name and attr_attr:
if isinstance(name, six.string_types):
unparsed = ".".join([item for item in (name, attr_attr) if item])
else:
unparsed = item
elif attr_attr and not name:
unparsed = attr_attr
else:
unparsed = name if not unparsed else unparsed
return unparsed
def unparse_Compare(self, item):
if isinstance(item.left, ast.Attribute) or isinstance(item.left, ast.Str):
import importlib
left = self.unparse(item.left)
if "." in left:
name, _, val = left.rpartition(".")
left = getattr(importlib.import_module(name), val, left)
comparators = []
for comparator in item.comparators:
right = self.unparse(comparator)
if isinstance(comparator, ast.Attribute) and "." in right:
name, _, val = right.rpartition(".")
right = getattr(importlib.import_module(name), val, right)
comparators.append(right)
unparsed = (left, self.unparse(item.ops), comparators)
else:
unparsed = item
return unparsed
def unparse_IfExp(self, item):
ops, truth_vals = [], []
if isinstance(item.test, ast.Compare):
left, ops, right = self.unparse(item.test)
else:
result = self.unparse(item.test)
if isinstance(result, dict):
k, v = result.popitem()
if not v:
truth_vals = [False]
for i, op in enumerate(ops):
if i == 0:
truth_vals.append(op(left, right[i]))
else:
truth_vals.append(op(right[i - 1], right[i]))
if all(truth_vals):
unparsed = self.unparse(item.body)
else:
unparsed = self.unparse(item.orelse)
return unparsed
def unparse_Call(self, item):
unparsed = {}
if isinstance(item.func, (ast.Name, ast.Attribute)):
func_name = self.unparse(item.func)
else:
try:
func_name = self.unparse(item.func)
except Exception:
func_name = None
if not func_name:
return {}
if isinstance(func_name, dict):
unparsed.update(func_name)
func_name = next(iter(func_name.keys()))
else:
unparsed[func_name] = {}
for key in ("kwargs", "keywords"):
val = getattr(item, key, [])
if val is None:
continue
for keyword in self.unparse(val):
unparsed[func_name].update(self.unparse(keyword))
return unparsed
def unparse_keyword(self, item):
return {self.unparse(item.arg): self.unparse(item.value)}
def unparse_Assign(self, item):
# XXX: DO NOT UNPARSE THIS
# XXX: If we unparse this it becomes impossible to map it back
# XXX: To the original node in the AST so we can find the
# XXX: Original reference
with self.no_recurse():
target = self.unparse(next(iter(item.targets)))
val = self.unparse(item.value)
if isinstance(target, (tuple, set, list)):
unparsed = dict(zip(target, val))
else:
unparsed = {target: val}
return unparsed
def unparse_Mapping(self, item):
unparsed = {}
for k, v in item.items():
try:
unparsed[self.unparse(k)] = self.unparse(v)
except TypeError:
unparsed[k] = self.unparse(v)
return unparsed
def unparse_list(self, item):
return type(item)([self.unparse(el) for el in item])
def unparse_tuple(self, item):
return self.unparse_list(item)
def unparse_str(self, item):
return item
def parse_function_names(self, should_retry=True, function_map=None):
if function_map is None:
function_map = {}
retries = []
for k, v in function_map.items():
fn_name = ""
if k in self.function_names:
fn_name = self.function_names[k]
elif isinstance(k, ast.Name):
fn_name = k.id
elif isinstance(k, ast.Attribute):
try:
fn = ast_unparse(k, analyzer=self)
except Exception:
if should_retry:
retries.append((k, v))
continue
else:
if isinstance(fn, six.string_types):
_, _, fn_name = fn.rpartition(".")
if fn_name:
self.resolved_function_names[fn_name] = ast_unparse(v, analyzer=self)
return retries
def parse_functions(self):
retries = self.parse_function_names(function_map=self.function_map)
if retries:
failures = self.parse_function_names(
should_retry=False, function_map=dict(retries)
)
return self.resolved_function_names
def parse_setup_function(self):
setup = {} # type: Dict[Any, Any]
self.unmap_binops()
function_names = self.parse_functions()
if "setup" in function_names:
setup = self.unparse(function_names["setup"])
keys = list(setup.keys())
if len(keys) == 1 and keys[0] is None:
_, setup = setup.popitem()
keys = list(setup.keys())
for k in keys:
# XXX: Remove unresolved functions from the setup dictionary
if isinstance(setup[k], dict):
if not setup[k]:
continue
key = next(iter(setup[k].keys()))
val = setup[k][key]
if key in function_names and val is None or val == {}:
setup.pop(k)
return setup
def ast_unparse(item, initial_mapping=False, analyzer=None, recurse=True): # noqa:C901
# type: (Any, bool, Optional[Analyzer], bool) -> Union[List[Any], Dict[Any, Any], Tuple[Any, ...], STRING_TYPE]
unparse = partial(
ast_unparse, initial_mapping=initial_mapping, analyzer=analyzer, recurse=recurse
)
if getattr(ast, "Constant", None):